blob: e9a45d79da672a5ba686a77c65bb216d198cc982 [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>
20#include <sys/types.h>
21#include <sys/wait.h>
22
23// C++ Includes
24// Other libraries and framework includes
Johnny Chen0d5f2d42011-10-18 18:09:30 +000025#include "lldb/Core/Debugger.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000026#include "lldb/Core/Error.h"
Johnny Chen13e8e1c2011-05-13 21:29:50 +000027#include "lldb/Core/RegisterValue.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000028#include "lldb/Core/Scalar.h"
29#include "lldb/Host/Host.h"
30#include "lldb/Target/Thread.h"
31#include "lldb/Target/RegisterContext.h"
32#include "lldb/Utility/PseudoTerminal.h"
33
Johnny Chen30213ff2012-01-05 19:17:38 +000034#include "POSIXThread.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000035#include "ProcessLinux.h"
Johnny Chen30213ff2012-01-05 19:17:38 +000036#include "ProcessPOSIXLog.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000037#include "ProcessMonitor.h"
38
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
Stephen Wilsone6f9f662010-07-24 02:19:04 +000055using namespace lldb_private;
56
Johnny Chen0d5f2d42011-10-18 18:09:30 +000057// FIXME: this code is host-dependent with respect to types and
58// endianness and needs to be fixed. For example, lldb::addr_t is
59// hard-coded to uint64_t, but on a 32-bit Linux host, ptrace requires
60// 32-bit pointer arguments. This code uses casts to work around the
61// problem.
62
63// We disable the tracing of ptrace calls for integration builds to
64// avoid the additional indirection and checks.
65#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
66
Greg Clayton386ff182011-11-05 01:09:16 +000067static void
68DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
69{
70 uint8_t *ptr = (uint8_t *)bytes;
71 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
72 for(uint32_t i=0; i<loop_count; i++)
73 {
74 s.Printf ("[%x]", *ptr);
75 ptr++;
76 }
77}
78
Matt Kopec58c0b962013-03-20 20:34:35 +000079static void PtraceDisplayBytes(int &req, void *data, size_t data_size)
Greg Clayton386ff182011-11-05 01:09:16 +000080{
81 StreamString buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +000082 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
Johnny Chen30213ff2012-01-05 19:17:38 +000083 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
Greg Clayton386ff182011-11-05 01:09:16 +000084
85 if (verbose_log)
86 {
87 switch(req)
88 {
89 case PTRACE_POKETEXT:
90 {
91 DisplayBytes(buf, &data, 8);
92 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
93 break;
94 }
Greg Clayton542e4072012-09-07 17:49:29 +000095 case PTRACE_POKEDATA:
Greg Clayton386ff182011-11-05 01:09:16 +000096 {
97 DisplayBytes(buf, &data, 8);
98 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
99 break;
100 }
Greg Clayton542e4072012-09-07 17:49:29 +0000101 case PTRACE_POKEUSER:
Greg Clayton386ff182011-11-05 01:09:16 +0000102 {
103 DisplayBytes(buf, &data, 8);
104 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
105 break;
106 }
Greg Clayton542e4072012-09-07 17:49:29 +0000107 case PTRACE_SETREGS:
Greg Clayton386ff182011-11-05 01:09:16 +0000108 {
Matt Kopec7de48462013-03-06 17:20:48 +0000109 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000110 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
111 break;
112 }
113 case PTRACE_SETFPREGS:
114 {
Matt Kopec7de48462013-03-06 17:20:48 +0000115 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000116 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
117 break;
118 }
Greg Clayton542e4072012-09-07 17:49:29 +0000119 case PTRACE_SETSIGINFO:
Greg Clayton386ff182011-11-05 01:09:16 +0000120 {
121 DisplayBytes(buf, data, sizeof(siginfo_t));
122 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
123 break;
124 }
Matt Kopec58c0b962013-03-20 20:34:35 +0000125 case PTRACE_SETREGSET:
126 {
127 // Extract iov_base from data, which is a pointer to the struct IOVEC
128 DisplayBytes(buf, *(void **)data, data_size);
129 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
130 break;
131 }
Greg Clayton386ff182011-11-05 01:09:16 +0000132 default:
133 {
134 }
135 }
136 }
137}
138
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000139// Wrapper for ptrace to catch errors and log calls.
Ashok Thirumurthi762fbd02013-03-27 21:09:30 +0000140// 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 +0000141extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000142PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000143 const char* reqName, const char* file, int line)
144{
Greg Clayton386ff182011-11-05 01:09:16 +0000145 long int result;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000146
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000147 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
Greg Clayton386ff182011-11-05 01:09:16 +0000148
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000149 if (log)
Matt Kopec58c0b962013-03-20 20:34:35 +0000150 log->Printf("ptrace(%s, %lu, %p, %p, %zu) called from file %s line %d",
Matt Kopec7de48462013-03-06 17:20:48 +0000151 reqName, pid, addr, data, data_size, file, line);
Greg Clayton542e4072012-09-07 17:49:29 +0000152
Matt Kopec7de48462013-03-06 17:20:48 +0000153 PtraceDisplayBytes(req, data, data_size);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000154
155 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000156 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
157 result = ptrace(static_cast<__ptrace_request>(req), pid, *(unsigned int *)addr, data);
158 else
159 result = ptrace(static_cast<__ptrace_request>(req), pid, addr, data);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000160
Matt Kopec7de48462013-03-06 17:20:48 +0000161 PtraceDisplayBytes(req, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000162
Matt Kopec7de48462013-03-06 17:20:48 +0000163 if (log && errno != 0)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000164 {
165 const char* str;
166 switch (errno)
167 {
168 case ESRCH: str = "ESRCH"; break;
169 case EINVAL: str = "EINVAL"; break;
170 case EBUSY: str = "EBUSY"; break;
171 case EPERM: str = "EPERM"; break;
172 default: str = "<unknown>";
173 }
174 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
175 }
176
177 return result;
178}
179
Matt Kopec7de48462013-03-06 17:20:48 +0000180// Wrapper for ptrace when logging is not required.
181// Sets errno to 0 prior to calling ptrace.
182extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000183PtraceWrapper(int req, pid_t pid, void *addr, void *data, size_t data_size)
Matt Kopec7de48462013-03-06 17:20:48 +0000184{
Matt Kopec58c0b962013-03-20 20:34:35 +0000185 long result = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000186 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000187 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
188 result = ptrace(static_cast<__ptrace_request>(req), pid, *(unsigned int *)addr, data);
189 else
190 result = ptrace(static_cast<__ptrace_request>(req), pid, addr, data);
Matt Kopec7de48462013-03-06 17:20:48 +0000191 return result;
192}
193
194#define PTRACE(req, pid, addr, data, data_size) \
195 PtraceWrapper((req), (pid), (addr), (data), (data_size), #req, __FILE__, __LINE__)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000196#else
Matt Kopec7de48462013-03-06 17:20:48 +0000197 PtraceWrapper((req), (pid), (addr), (data), (data_size))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000198#endif
199
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000200//------------------------------------------------------------------------------
201// Static implementations of ProcessMonitor::ReadMemory and
202// ProcessMonitor::WriteMemory. This enables mutual recursion between these
203// functions without needed to go thru the thread funnel.
204
205static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000206DoReadMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000207 lldb::addr_t vm_addr, void *buf, size_t size, Error &error)
208{
Greg Clayton542e4072012-09-07 17:49:29 +0000209 // ptrace word size is determined by the host, not the child
210 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000211 unsigned char *dst = static_cast<unsigned char*>(buf);
212 size_t bytes_read;
213 size_t remainder;
214 long data;
215
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000216 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000217 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000218 ProcessPOSIXLog::IncNestLevel();
219 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000220 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000221 pid, word_size, (void*)vm_addr, buf, size);
222
223 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000224 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
225 {
226 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000227 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, NULL, 0);
228 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000229 {
230 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000231 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000232 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000233 return bytes_read;
234 }
235
236 remainder = size - bytes_read;
237 remainder = remainder > word_size ? word_size : remainder;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000238
239 // Copy the data into our buffer
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000240 for (unsigned i = 0; i < remainder; ++i)
241 dst[i] = ((data >> i*8) & 0xFF);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000242
Johnny Chen30213ff2012-01-05 19:17:38 +0000243 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
244 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
245 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
246 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Daniel Maleac63dddd2012-12-14 21:07:07 +0000247 {
248 uintptr_t print_dst = 0;
249 // Format bytes from data by moving into print_dst for log output
250 for (unsigned i = 0; i < remainder; ++i)
251 print_dst |= (((data >> i*8) & 0xFF) << i*8);
252 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
253 (void*)vm_addr, print_dst, (unsigned long)data);
254 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000255
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000256 vm_addr += word_size;
257 dst += word_size;
258 }
259
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000260 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000261 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000262 return bytes_read;
263}
264
265static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000266DoWriteMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000267 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
268{
Greg Clayton542e4072012-09-07 17:49:29 +0000269 // ptrace word size is determined by the host, not the child
270 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000271 const unsigned char *src = static_cast<const unsigned char*>(buf);
272 size_t bytes_written = 0;
273 size_t remainder;
274
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000275 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000276 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000277 ProcessPOSIXLog::IncNestLevel();
278 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000279 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000280 pid, word_size, (void*)vm_addr, buf, size);
281
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000282 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
283 {
284 remainder = size - bytes_written;
285 remainder = remainder > word_size ? word_size : remainder;
286
287 if (remainder == word_size)
288 {
289 unsigned long data = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000290 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000291 for (unsigned i = 0; i < word_size; ++i)
292 data |= (unsigned long)src[i] << i*8;
293
Johnny Chen30213ff2012-01-05 19:17:38 +0000294 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
295 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
296 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
297 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000298 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
299 (void*)vm_addr, *(unsigned long*)src, data);
300
Matt Kopec7de48462013-03-06 17:20:48 +0000301 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000302 {
303 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000304 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000305 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000306 return bytes_written;
307 }
308 }
309 else
310 {
311 unsigned char buff[8];
Greg Clayton542e4072012-09-07 17:49:29 +0000312 if (DoReadMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000313 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000314 {
315 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000316 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000317 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000318 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000319
320 memcpy(buff, src, remainder);
321
Greg Clayton542e4072012-09-07 17:49:29 +0000322 if (DoWriteMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000323 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000324 {
325 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000326 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000327 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000328 }
329
Johnny Chen30213ff2012-01-05 19:17:38 +0000330 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
331 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
332 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
333 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000334 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
335 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000336 }
337
338 vm_addr += word_size;
339 src += word_size;
340 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000341 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000342 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000343 return bytes_written;
344}
345
Stephen Wilson26977162011-03-23 02:14:42 +0000346// Simple helper function to ensure flags are enabled on the given file
347// descriptor.
348static bool
349EnsureFDFlags(int fd, int flags, Error &error)
350{
351 int status;
352
353 if ((status = fcntl(fd, F_GETFL)) == -1)
354 {
355 error.SetErrorToErrno();
356 return false;
357 }
358
359 if (fcntl(fd, F_SETFL, status | flags) == -1)
360 {
361 error.SetErrorToErrno();
362 return false;
363 }
364
365 return true;
366}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000367
368//------------------------------------------------------------------------------
369/// @class Operation
370/// @brief Represents a ProcessMonitor operation.
371///
372/// Under Linux, it is not possible to ptrace() from any other thread but the
373/// one that spawned or attached to the process from the start. Therefore, when
374/// a ProcessMonitor is asked to deliver or change the state of an inferior
375/// process the operation must be "funneled" to a specific thread to perform the
376/// task. The Operation class provides an abstract base for all services the
377/// ProcessMonitor must perform via the single virtual function Execute, thus
378/// encapsulating the code that needs to run in the privileged context.
379class Operation
380{
381public:
382 virtual void Execute(ProcessMonitor *monitor) = 0;
383};
384
385//------------------------------------------------------------------------------
386/// @class ReadOperation
387/// @brief Implements ProcessMonitor::ReadMemory.
388class ReadOperation : public Operation
389{
390public:
391 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
392 Error &error, size_t &result)
393 : m_addr(addr), m_buff(buff), m_size(size),
394 m_error(error), m_result(result)
395 { }
396
397 void Execute(ProcessMonitor *monitor);
398
399private:
400 lldb::addr_t m_addr;
401 void *m_buff;
402 size_t m_size;
403 Error &m_error;
404 size_t &m_result;
405};
406
407void
408ReadOperation::Execute(ProcessMonitor *monitor)
409{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000410 lldb::pid_t pid = monitor->GetPID();
411
Greg Clayton542e4072012-09-07 17:49:29 +0000412 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000413}
414
415//------------------------------------------------------------------------------
416/// @class ReadOperation
417/// @brief Implements ProcessMonitor::WriteMemory.
418class WriteOperation : public Operation
419{
420public:
421 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
422 Error &error, size_t &result)
423 : m_addr(addr), m_buff(buff), m_size(size),
424 m_error(error), m_result(result)
425 { }
426
427 void Execute(ProcessMonitor *monitor);
428
429private:
430 lldb::addr_t m_addr;
431 const void *m_buff;
432 size_t m_size;
433 Error &m_error;
434 size_t &m_result;
435};
436
437void
438WriteOperation::Execute(ProcessMonitor *monitor)
439{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000440 lldb::pid_t pid = monitor->GetPID();
441
Greg Clayton542e4072012-09-07 17:49:29 +0000442 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000443}
444
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000445
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000446//------------------------------------------------------------------------------
447/// @class ReadRegOperation
448/// @brief Implements ProcessMonitor::ReadRegisterValue.
449class ReadRegOperation : public Operation
450{
451public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000452 ReadRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000453 RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000454 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000455 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000456 { }
457
458 void Execute(ProcessMonitor *monitor);
459
460private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000461 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000462 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000463 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000464 RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000465 bool &m_result;
466};
467
468void
469ReadRegOperation::Execute(ProcessMonitor *monitor)
470{
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000471 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000472
473 // Set errno to zero so that we can detect a failed peek.
474 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000475 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, NULL, 0);
476 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000477 m_result = false;
478 else
479 {
480 m_value = data;
481 m_result = true;
482 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000483 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000484 log->Printf ("ProcessMonitor::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000485 m_reg_name, data);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000486}
487
488//------------------------------------------------------------------------------
489/// @class WriteRegOperation
490/// @brief Implements ProcessMonitor::WriteRegisterValue.
491class WriteRegOperation : public Operation
492{
493public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000494 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000495 const RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000496 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000497 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000498 { }
499
500 void Execute(ProcessMonitor *monitor);
501
502private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000503 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000504 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000505 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000506 const RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000507 bool &m_result;
508};
509
510void
511WriteRegOperation::Execute(ProcessMonitor *monitor)
512{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000513 void* buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000514 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000515
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000516#if __WORDSIZE == 32
517 buf = (void*) m_value.GetAsUInt32();
518#else
519 buf = (void*) m_value.GetAsUInt64();
520#endif
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000521
522 if (log)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000523 log->Printf ("ProcessMonitor::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Matt Kopec7de48462013-03-06 17:20:48 +0000524 if (PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000525 m_result = false;
526 else
527 m_result = true;
528}
529
530//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000531/// @class ReadGPROperation
532/// @brief Implements ProcessMonitor::ReadGPR.
533class ReadGPROperation : public Operation
534{
535public:
Matt Kopec7de48462013-03-06 17:20:48 +0000536 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
537 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000538 { }
539
540 void Execute(ProcessMonitor *monitor);
541
542private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000543 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000544 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000545 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000546 bool &m_result;
547};
548
549void
550ReadGPROperation::Execute(ProcessMonitor *monitor)
551{
Matt Kopec7de48462013-03-06 17:20:48 +0000552 if (PTRACE(PTRACE_GETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000553 m_result = false;
554 else
555 m_result = true;
556}
557
558//------------------------------------------------------------------------------
559/// @class ReadFPROperation
560/// @brief Implements ProcessMonitor::ReadFPR.
561class ReadFPROperation : public Operation
562{
563public:
Matt Kopec7de48462013-03-06 17:20:48 +0000564 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
565 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000566 { }
567
568 void Execute(ProcessMonitor *monitor);
569
570private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000571 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000572 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000573 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000574 bool &m_result;
575};
576
577void
578ReadFPROperation::Execute(ProcessMonitor *monitor)
579{
Matt Kopec7de48462013-03-06 17:20:48 +0000580 if (PTRACE(PTRACE_GETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000581 m_result = false;
582 else
583 m_result = true;
584}
585
586//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000587/// @class ReadRegisterSetOperation
588/// @brief Implements ProcessMonitor::ReadRegisterSet.
589class ReadRegisterSetOperation : public Operation
590{
591public:
592 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
593 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
594 { }
595
596 void Execute(ProcessMonitor *monitor);
597
598private:
599 lldb::tid_t m_tid;
600 void *m_buf;
601 size_t m_buf_size;
602 const unsigned int m_regset;
603 bool &m_result;
604};
605
606void
607ReadRegisterSetOperation::Execute(ProcessMonitor *monitor)
608{
609 if (PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
610 m_result = false;
611 else
612 m_result = true;
613}
614
615//------------------------------------------------------------------------------
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000616/// @class WriteGPROperation
617/// @brief Implements ProcessMonitor::WriteGPR.
618class WriteGPROperation : public Operation
619{
620public:
Matt Kopec7de48462013-03-06 17:20:48 +0000621 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
622 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000623 { }
624
625 void Execute(ProcessMonitor *monitor);
626
627private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000628 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000629 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000630 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000631 bool &m_result;
632};
633
634void
635WriteGPROperation::Execute(ProcessMonitor *monitor)
636{
Matt Kopec7de48462013-03-06 17:20:48 +0000637 if (PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000638 m_result = false;
639 else
640 m_result = true;
641}
642
643//------------------------------------------------------------------------------
644/// @class WriteFPROperation
645/// @brief Implements ProcessMonitor::WriteFPR.
646class WriteFPROperation : public Operation
647{
648public:
Matt Kopec7de48462013-03-06 17:20:48 +0000649 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
650 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000651 { }
652
653 void Execute(ProcessMonitor *monitor);
654
655private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000656 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000657 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000658 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000659 bool &m_result;
660};
661
662void
663WriteFPROperation::Execute(ProcessMonitor *monitor)
664{
Matt Kopec7de48462013-03-06 17:20:48 +0000665 if (PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000666 m_result = false;
667 else
668 m_result = true;
669}
670
671//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000672/// @class WriteRegisterSetOperation
673/// @brief Implements ProcessMonitor::WriteRegisterSet.
674class WriteRegisterSetOperation : public Operation
675{
676public:
677 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
678 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
679 { }
680
681 void Execute(ProcessMonitor *monitor);
682
683private:
684 lldb::tid_t m_tid;
685 void *m_buf;
686 size_t m_buf_size;
687 const unsigned int m_regset;
688 bool &m_result;
689};
690
691void
692WriteRegisterSetOperation::Execute(ProcessMonitor *monitor)
693{
694 if (PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
695 m_result = false;
696 else
697 m_result = true;
698}
699
700//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000701/// @class ResumeOperation
702/// @brief Implements ProcessMonitor::Resume.
703class ResumeOperation : public Operation
704{
705public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000706 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
707 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000708
709 void Execute(ProcessMonitor *monitor);
710
711private:
712 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000713 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000714 bool &m_result;
715};
716
717void
718ResumeOperation::Execute(ProcessMonitor *monitor)
719{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000720 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000721
722 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
723 data = m_signo;
724
Matt Kopec7de48462013-03-06 17:20:48 +0000725 if (PTRACE(PTRACE_CONT, m_tid, NULL, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000726 m_result = false;
727 else
728 m_result = true;
729}
730
731//------------------------------------------------------------------------------
732/// @class ResumeOperation
733/// @brief Implements ProcessMonitor::SingleStep.
734class SingleStepOperation : public Operation
735{
736public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000737 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
738 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000739
740 void Execute(ProcessMonitor *monitor);
741
742private:
743 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000744 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000745 bool &m_result;
746};
747
748void
749SingleStepOperation::Execute(ProcessMonitor *monitor)
750{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000751 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000752
753 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
754 data = m_signo;
755
Matt Kopec7de48462013-03-06 17:20:48 +0000756 if (PTRACE(PTRACE_SINGLESTEP, m_tid, NULL, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000757 m_result = false;
758 else
759 m_result = true;
760}
761
762//------------------------------------------------------------------------------
763/// @class SiginfoOperation
764/// @brief Implements ProcessMonitor::GetSignalInfo.
765class SiginfoOperation : public Operation
766{
767public:
Daniel Maleaa35970a2012-11-23 18:09:58 +0000768 SiginfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
769 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000770
771 void Execute(ProcessMonitor *monitor);
772
773private:
774 lldb::tid_t m_tid;
775 void *m_info;
776 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000777 int &m_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000778};
779
780void
781SiginfoOperation::Execute(ProcessMonitor *monitor)
782{
Matt Kopec7de48462013-03-06 17:20:48 +0000783 if (PTRACE(PTRACE_GETSIGINFO, m_tid, NULL, m_info, 0)) {
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000784 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000785 m_err = errno;
786 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000787 else
788 m_result = true;
789}
790
791//------------------------------------------------------------------------------
792/// @class EventMessageOperation
793/// @brief Implements ProcessMonitor::GetEventMessage.
794class EventMessageOperation : public Operation
795{
796public:
797 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
798 : m_tid(tid), m_message(message), m_result(result) { }
799
800 void Execute(ProcessMonitor *monitor);
801
802private:
803 lldb::tid_t m_tid;
804 unsigned long *m_message;
805 bool &m_result;
806};
807
808void
809EventMessageOperation::Execute(ProcessMonitor *monitor)
810{
Matt Kopec7de48462013-03-06 17:20:48 +0000811 if (PTRACE(PTRACE_GETEVENTMSG, m_tid, NULL, m_message, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000812 m_result = false;
813 else
814 m_result = true;
815}
816
817//------------------------------------------------------------------------------
818/// @class KillOperation
819/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
820class KillOperation : public Operation
821{
822public:
823 KillOperation(bool &result) : m_result(result) { }
824
825 void Execute(ProcessMonitor *monitor);
826
827private:
828 bool &m_result;
829};
830
831void
832KillOperation::Execute(ProcessMonitor *monitor)
833{
834 lldb::pid_t pid = monitor->GetPID();
835
Matt Kopec7de48462013-03-06 17:20:48 +0000836 if (PTRACE(PTRACE_KILL, pid, NULL, NULL, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000837 m_result = false;
838 else
839 m_result = true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000840}
841
Greg Clayton28041352011-11-29 20:50:10 +0000842//------------------------------------------------------------------------------
843/// @class KillOperation
844/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
845class DetachOperation : public Operation
846{
847public:
848 DetachOperation(Error &result) : m_error(result) { }
849
850 void Execute(ProcessMonitor *monitor);
851
852private:
853 Error &m_error;
854};
855
856void
857DetachOperation::Execute(ProcessMonitor *monitor)
858{
859 lldb::pid_t pid = monitor->GetPID();
860
861 if (ptrace(PT_DETACH, pid, NULL, 0) < 0)
862 m_error.SetErrorToErrno();
Greg Clayton542e4072012-09-07 17:49:29 +0000863
Greg Clayton28041352011-11-29 20:50:10 +0000864}
865
Johnny Chen25e68e32011-06-14 19:19:50 +0000866ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
867 : m_monitor(monitor)
868{
869 sem_init(&m_semaphore, 0, 0);
870}
871
872ProcessMonitor::OperationArgs::~OperationArgs()
873{
874 sem_destroy(&m_semaphore);
875}
876
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000877ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
878 lldb_private::Module *module,
879 char const **argv,
880 char const **envp,
881 const char *stdin_path,
882 const char *stdout_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000883 const char *stderr_path,
884 const char *working_dir)
Johnny Chen25e68e32011-06-14 19:19:50 +0000885 : OperationArgs(monitor),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000886 m_module(module),
887 m_argv(argv),
888 m_envp(envp),
889 m_stdin_path(stdin_path),
890 m_stdout_path(stdout_path),
Daniel Malea6217d2a2013-01-08 14:49:22 +0000891 m_stderr_path(stderr_path),
892 m_working_dir(working_dir) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000893
894ProcessMonitor::LaunchArgs::~LaunchArgs()
Johnny Chen25e68e32011-06-14 19:19:50 +0000895{ }
896
897ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
898 lldb::pid_t pid)
899 : OperationArgs(monitor), m_pid(pid) { }
900
901ProcessMonitor::AttachArgs::~AttachArgs()
902{ }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000903
904//------------------------------------------------------------------------------
905/// The basic design of the ProcessMonitor is built around two threads.
906///
907/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
908/// for changes in the debugee state. When a change is detected a
909/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
910/// "drives" state changes in the debugger.
911///
912/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000913/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000914/// operations such as register reads/writes, stepping, etc. See the comments
915/// on the Operation class for more info as to why this is needed.
Johnny Chen30213ff2012-01-05 19:17:38 +0000916ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000917 Module *module,
918 const char *argv[],
919 const char *envp[],
920 const char *stdin_path,
921 const char *stdout_path,
922 const char *stderr_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000923 const char *working_dir,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000924 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000925 : m_process(static_cast<ProcessLinux *>(process)),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000926 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +0000927 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000928 m_pid(LLDB_INVALID_PROCESS_ID),
929 m_terminal_fd(-1),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000930 m_client_fd(-1),
931 m_server_fd(-1)
932{
Greg Clayton7b0992d2013-04-18 22:45:39 +0000933 std::unique_ptr<LaunchArgs> args;
Stephen Wilson57740ec2011-01-15 00:12:41 +0000934
935 args.reset(new LaunchArgs(this, module, argv, envp,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000936 stdin_path, stdout_path, stderr_path, working_dir));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000937
938 // Server/client descriptors.
939 if (!EnableIPC())
940 {
941 error.SetErrorToGenericError();
942 error.SetErrorString("Monitor failed to initialize.");
943 }
944
Johnny Chen25e68e32011-06-14 19:19:50 +0000945 StartLaunchOpThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000946 if (!error.Success())
947 return;
948
949WAIT_AGAIN:
950 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000951 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000952 {
953 if (errno == EINTR)
954 goto WAIT_AGAIN;
955 else
956 {
957 error.SetErrorToErrno();
958 return;
959 }
960 }
961
962 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000963 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000964 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000965 StopOpThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000966 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000967 return;
968 }
969
970 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000971 m_monitor_thread = Host::StartMonitoringChildProcess(
972 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Stephen Wilsond4182f42011-02-09 20:10:35 +0000973 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000974 {
975 error.SetErrorToGenericError();
976 error.SetErrorString("Process launch failed.");
977 return;
978 }
979}
980
Johnny Chen30213ff2012-01-05 19:17:38 +0000981ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen25e68e32011-06-14 19:19:50 +0000982 lldb::pid_t pid,
983 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000984 : m_process(static_cast<ProcessLinux *>(process)),
Johnny Chen25e68e32011-06-14 19:19:50 +0000985 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +0000986 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Johnny Chen25e68e32011-06-14 19:19:50 +0000987 m_pid(LLDB_INVALID_PROCESS_ID),
988 m_terminal_fd(-1),
Matt Kopec7de48462013-03-06 17:20:48 +0000989
Johnny Chen25e68e32011-06-14 19:19:50 +0000990 m_client_fd(-1),
991 m_server_fd(-1)
992{
Greg Clayton7b0992d2013-04-18 22:45:39 +0000993 std::unique_ptr<AttachArgs> args;
Johnny Chen25e68e32011-06-14 19:19:50 +0000994
995 args.reset(new AttachArgs(this, pid));
996
997 // Server/client descriptors.
998 if (!EnableIPC())
999 {
1000 error.SetErrorToGenericError();
1001 error.SetErrorString("Monitor failed to initialize.");
1002 }
1003
1004 StartAttachOpThread(args.get(), error);
1005 if (!error.Success())
1006 return;
1007
1008WAIT_AGAIN:
1009 // Wait for the operation thread to initialize.
1010 if (sem_wait(&args->m_semaphore))
1011 {
1012 if (errno == EINTR)
1013 goto WAIT_AGAIN;
1014 else
1015 {
1016 error.SetErrorToErrno();
1017 return;
1018 }
1019 }
1020
Greg Clayton743ecf42012-10-16 20:20:18 +00001021 // Check that the attach was a success.
Johnny Chen25e68e32011-06-14 19:19:50 +00001022 if (!args->m_error.Success())
1023 {
Greg Clayton743ecf42012-10-16 20:20:18 +00001024 StopOpThread();
Johnny Chen25e68e32011-06-14 19:19:50 +00001025 error = args->m_error;
1026 return;
1027 }
1028
1029 // Finally, start monitoring the child process for change in state.
1030 m_monitor_thread = Host::StartMonitoringChildProcess(
1031 ProcessMonitor::MonitorCallback, this, GetPID(), true);
1032 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
1033 {
1034 error.SetErrorToGenericError();
1035 error.SetErrorString("Process attach failed.");
1036 return;
1037 }
1038}
1039
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001040ProcessMonitor::~ProcessMonitor()
1041{
Stephen Wilson84ffe702011-03-30 15:55:52 +00001042 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001043}
1044
1045//------------------------------------------------------------------------------
1046// Thread setup and tear down.
1047void
Johnny Chen25e68e32011-06-14 19:19:50 +00001048ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001049{
1050 static const char *g_thread_name = "lldb.process.linux.operation";
1051
Stephen Wilsond4182f42011-02-09 20:10:35 +00001052 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001053 return;
1054
1055 m_operation_thread =
Johnny Chen25e68e32011-06-14 19:19:50 +00001056 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001057}
1058
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001059void *
Johnny Chen25e68e32011-06-14 19:19:50 +00001060ProcessMonitor::LaunchOpThread(void *arg)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001061{
1062 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1063
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001064 if (!Launch(args)) {
1065 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001066 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001067 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001068
Stephen Wilson570243b2011-01-19 01:37:06 +00001069 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001070 return NULL;
1071}
1072
1073bool
1074ProcessMonitor::Launch(LaunchArgs *args)
1075{
1076 ProcessMonitor *monitor = args->m_monitor;
1077 ProcessLinux &process = monitor->GetProcess();
1078 const char **argv = args->m_argv;
1079 const char **envp = args->m_envp;
1080 const char *stdin_path = args->m_stdin_path;
1081 const char *stdout_path = args->m_stdout_path;
1082 const char *stderr_path = args->m_stderr_path;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001083 const char *working_dir = args->m_working_dir;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001084
1085 lldb_utility::PseudoTerminal terminal;
1086 const size_t err_len = 1024;
1087 char err_str[err_len];
1088 lldb::pid_t pid;
Matt Kopec650648f2013-01-08 16:30:18 +00001089 long ptrace_opts = 0;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001090
1091 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001092 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001093
Stephen Wilson57740ec2011-01-15 00:12:41 +00001094 // Propagate the environment if one is not supplied.
1095 if (envp == NULL || envp[0] == NULL)
1096 envp = const_cast<const char **>(environ);
1097
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001098 // Pseudo terminal setup.
1099 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
1100 {
1101 args->m_error.SetErrorToGenericError();
1102 args->m_error.SetErrorString("Could not open controlling TTY.");
1103 goto FINISH;
1104 }
1105
Daniel Maleaa85e6b62012-12-07 22:21:08 +00001106 if ((pid = terminal.Fork(err_str, err_len)) == -1)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001107 {
1108 args->m_error.SetErrorToGenericError();
1109 args->m_error.SetErrorString("Process fork failed.");
1110 goto FINISH;
1111 }
1112
Peter Collingbourne6a520222011-06-14 03:55:58 +00001113 // Recognized child exit status codes.
1114 enum {
1115 ePtraceFailed = 1,
1116 eDupStdinFailed,
1117 eDupStdoutFailed,
1118 eDupStderrFailed,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001119 eChdirFailed,
Peter Collingbourne6a520222011-06-14 03:55:58 +00001120 eExecFailed
1121 };
1122
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001123 // Child process.
1124 if (pid == 0)
1125 {
1126 // Trace this process.
Matt Kopec7de48462013-03-06 17:20:48 +00001127 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL, 0) < 0)
Peter Collingbourne6a520222011-06-14 03:55:58 +00001128 exit(ePtraceFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001129
1130 // Do not inherit setgid powers.
1131 setgid(getgid());
1132
1133 // Let us have our own process group.
1134 setpgid(0, 0);
1135
Greg Clayton710dd5a2011-01-08 20:28:42 +00001136 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001137 //
1138 // FIXME: If two or more of the paths are the same we needlessly open
1139 // the same file multiple times.
1140 if (stdin_path != NULL && stdin_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001141 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001142 exit(eDupStdinFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001143
1144 if (stdout_path != NULL && stdout_path[0])
1145 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001146 exit(eDupStdoutFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001147
1148 if (stderr_path != NULL && stderr_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001149 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001150 exit(eDupStderrFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001151
Daniel Malea6217d2a2013-01-08 14:49:22 +00001152 // Change working directory
1153 if (working_dir != NULL && working_dir[0])
1154 if (0 != ::chdir(working_dir))
1155 exit(eChdirFailed);
1156
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001157 // Execute. We should never return.
1158 execve(argv[0],
1159 const_cast<char *const *>(argv),
1160 const_cast<char *const *>(envp));
Peter Collingbourne6a520222011-06-14 03:55:58 +00001161 exit(eExecFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001162 }
1163
1164 // Wait for the child process to to trap on its call to execve.
Peter Collingbourne6a520222011-06-14 03:55:58 +00001165 pid_t wpid;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001166 int status;
Peter Collingbourne6a520222011-06-14 03:55:58 +00001167 if ((wpid = waitpid(pid, &status, 0)) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001168 {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001169 args->m_error.SetErrorToErrno();
1170 goto FINISH;
1171 }
Peter Collingbourne6a520222011-06-14 03:55:58 +00001172 else if (WIFEXITED(status))
1173 {
1174 // open, dup or execve likely failed for some reason.
1175 args->m_error.SetErrorToGenericError();
1176 switch (WEXITSTATUS(status))
1177 {
Greg Clayton542e4072012-09-07 17:49:29 +00001178 case ePtraceFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001179 args->m_error.SetErrorString("Child ptrace failed.");
1180 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001181 case eDupStdinFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001182 args->m_error.SetErrorString("Child open stdin failed.");
1183 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001184 case eDupStdoutFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001185 args->m_error.SetErrorString("Child open stdout failed.");
1186 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001187 case eDupStderrFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001188 args->m_error.SetErrorString("Child open stderr failed.");
1189 break;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001190 case eChdirFailed:
1191 args->m_error.SetErrorString("Child failed to set working directory.");
1192 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001193 case eExecFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001194 args->m_error.SetErrorString("Child exec failed.");
1195 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001196 default:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001197 args->m_error.SetErrorString("Child returned unknown exit status.");
1198 break;
1199 }
1200 goto FINISH;
1201 }
1202 assert(WIFSTOPPED(status) && wpid == pid &&
1203 "Could not sync with inferior process.");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001204
1205 // Have the child raise an event on exit. This is used to keep the child in
1206 // limbo until it is destroyed.
Matt Kopec650648f2013-01-08 16:30:18 +00001207 ptrace_opts |= PTRACE_O_TRACEEXIT;
1208
1209 // Have the tracer trace threads which spawn in the inferior process.
1210 ptrace_opts |= PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE;
1211
Matt Kopec7de48462013-03-06 17:20:48 +00001212 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)ptrace_opts, 0) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001213 {
1214 args->m_error.SetErrorToErrno();
1215 goto FINISH;
1216 }
1217
1218 // Release the master terminal descriptor and pass it off to the
1219 // ProcessMonitor instance. Similarly stash the inferior pid.
1220 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1221 monitor->m_pid = pid;
1222
Stephen Wilson26977162011-03-23 02:14:42 +00001223 // Set the terminal fd to be in non blocking mode (it simplifies the
1224 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1225 // descriptor to read from).
1226 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1227 goto FINISH;
1228
Johnny Chen30213ff2012-01-05 19:17:38 +00001229 // Update the process thread list with this new thread.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001230 // FIXME: should we be letting UpdateThreadList handle this?
1231 // FIXME: by using pids instead of tids, we can only support one thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001232 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001233 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001234 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001235 process.GetThreadList().AddThread(inferior);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001236
1237 // Let our process instance know the thread has stopped.
1238 process.SendMessage(ProcessMessage::Trace(pid));
1239
1240FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001241 return args->m_error.Success();
1242}
1243
1244bool
1245ProcessMonitor::EnableIPC()
1246{
1247 int fd[2];
1248
1249 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
1250 return false;
1251
1252 m_client_fd = fd[0];
1253 m_server_fd = fd[1];
1254 return true;
1255}
1256
Johnny Chen25e68e32011-06-14 19:19:50 +00001257void
1258ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1259{
1260 static const char *g_thread_name = "lldb.process.linux.operation";
1261
1262 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1263 return;
1264
1265 m_operation_thread =
1266 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1267}
1268
Johnny Chen25e68e32011-06-14 19:19:50 +00001269void *
1270ProcessMonitor::AttachOpThread(void *arg)
1271{
1272 AttachArgs *args = static_cast<AttachArgs*>(arg);
1273
Greg Clayton743ecf42012-10-16 20:20:18 +00001274 if (!Attach(args)) {
1275 sem_post(&args->m_semaphore);
Johnny Chen25e68e32011-06-14 19:19:50 +00001276 return NULL;
Greg Clayton743ecf42012-10-16 20:20:18 +00001277 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001278
1279 ServeOperation(args);
1280 return NULL;
1281}
1282
1283bool
1284ProcessMonitor::Attach(AttachArgs *args)
1285{
1286 lldb::pid_t pid = args->m_pid;
1287
1288 ProcessMonitor *monitor = args->m_monitor;
1289 ProcessLinux &process = monitor->GetProcess();
Johnny Chen25e68e32011-06-14 19:19:50 +00001290 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001291 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen25e68e32011-06-14 19:19:50 +00001292
1293 if (pid <= 1)
1294 {
1295 args->m_error.SetErrorToGenericError();
1296 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1297 goto FINISH;
1298 }
1299
1300 // Attach to the requested process.
Matt Kopec7de48462013-03-06 17:20:48 +00001301 if (PTRACE(PTRACE_ATTACH, pid, NULL, NULL, 0) < 0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001302 {
1303 args->m_error.SetErrorToErrno();
1304 goto FINISH;
1305 }
1306
1307 int status;
1308 if ((status = waitpid(pid, NULL, 0)) < 0)
1309 {
1310 args->m_error.SetErrorToErrno();
1311 goto FINISH;
1312 }
1313
Greg Clayton926cce72012-10-12 16:10:12 +00001314 monitor->m_pid = pid;
1315
Johnny Chen30213ff2012-01-05 19:17:38 +00001316 // Update the process thread list with the attached thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001317 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001318 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001319 log->Printf ("ProcessMonitor::%s() adding tid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen25e68e32011-06-14 19:19:50 +00001320 process.GetThreadList().AddThread(inferior);
Johnny Chen25e68e32011-06-14 19:19:50 +00001321
1322 // Let our process instance know the thread has stopped.
1323 process.SendMessage(ProcessMessage::Trace(pid));
1324
1325 FINISH:
1326 return args->m_error.Success();
1327}
1328
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001329bool
1330ProcessMonitor::MonitorCallback(void *callback_baton,
1331 lldb::pid_t pid,
Peter Collingbourne2c67b9a2011-11-21 00:10:19 +00001332 bool exited,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001333 int signal,
1334 int status)
1335{
1336 ProcessMessage message;
1337 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
1338 ProcessLinux *process = monitor->m_process;
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001339 assert(process);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001340 bool stop_monitoring;
1341 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001342 int ptrace_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001343
Daniel Maleaa35970a2012-11-23 18:09:58 +00001344 if (!monitor->GetSignalInfo(pid, &info, ptrace_err)) {
1345 if (ptrace_err == EINVAL) {
1346 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1347 if (!monitor->Resume(pid, SIGSTOP)) {
1348 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1349 }
1350 stop_monitoring = false;
1351 } else {
1352 // ptrace(GETSIGINFO) failed (but not due to group-stop). Most likely,
1353 // this means the child pid is gone (or not being debugged) therefore
1354 // stop the monitor thread.
1355 stop_monitoring = true;
1356 }
1357 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00001358 else {
1359 switch (info.si_signo)
1360 {
1361 case SIGTRAP:
1362 message = MonitorSIGTRAP(monitor, &info, pid);
1363 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001364
Stephen Wilson84ffe702011-03-30 15:55:52 +00001365 default:
1366 message = MonitorSignal(monitor, &info, pid);
1367 break;
1368 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001369
Stephen Wilson84ffe702011-03-30 15:55:52 +00001370 process->SendMessage(message);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001371 stop_monitoring = !process->IsAlive();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001372 }
1373
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001374 return stop_monitoring;
1375}
1376
1377ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +00001378ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001379 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001380{
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001381 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001382
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001383 assert(monitor);
1384 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001385
Stephen Wilson84ffe702011-03-30 15:55:52 +00001386 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001387 {
1388 default:
1389 assert(false && "Unexpected SIGTRAP code!");
1390 break;
1391
Matt Kopec650648f2013-01-08 16:30:18 +00001392 case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1393 case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1394 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1395 {
1396 unsigned long tid = 0;
1397 if (!monitor->GetEventMessage(pid, &tid))
1398 tid = -1;
1399 message = ProcessMessage::NewThread(pid, tid);
1400 break;
1401 }
1402
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001403 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1404 {
1405 // The inferior process is about to exit. Maintain the process in a
1406 // state of "limbo" until we are explicitly commanded to detach,
1407 // destroy, resume, etc.
1408 unsigned long data = 0;
1409 if (!monitor->GetEventMessage(pid, &data))
1410 data = -1;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001411 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001412 break;
1413 }
1414
1415 case 0:
1416 case TRAP_TRACE:
1417 message = ProcessMessage::Trace(pid);
1418 break;
1419
1420 case SI_KERNEL:
1421 case TRAP_BRKPT:
1422 message = ProcessMessage::Break(pid);
1423 break;
Matt Kopece9ea0da2013-05-07 19:29:28 +00001424
1425 case TRAP_HWBKPT:
1426 message = ProcessMessage::Watch(pid, (lldb::addr_t)info->si_addr);
1427 break;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001428 }
1429
1430 return message;
1431}
1432
Stephen Wilson84ffe702011-03-30 15:55:52 +00001433ProcessMessage
1434ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001435 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001436{
1437 ProcessMessage message;
1438 int signo = info->si_signo;
1439
1440 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1441 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1442 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1443 //
1444 // IOW, user generated signals never generate what we consider to be a
1445 // "crash".
1446 //
1447 // Similarly, ACK signals generated by this monitor.
1448 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1449 {
1450 if (info->si_pid == getpid())
1451 return ProcessMessage::SignalDelivered(pid, signo);
1452 else
1453 return ProcessMessage::Signal(pid, signo);
1454 }
1455
1456 if (signo == SIGSEGV) {
1457 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1458 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1459 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1460 }
1461
1462 if (signo == SIGILL) {
1463 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1464 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1465 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1466 }
1467
1468 if (signo == SIGFPE) {
1469 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1470 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1471 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1472 }
1473
1474 if (signo == SIGBUS) {
1475 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1476 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1477 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1478 }
1479
1480 // Everything else is "normal" and does not require any special action on
1481 // our part.
1482 return ProcessMessage::Signal(pid, signo);
1483}
1484
1485ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001486ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001487{
1488 ProcessMessage::CrashReason reason;
1489 assert(info->si_signo == SIGSEGV);
1490
1491 reason = ProcessMessage::eInvalidCrashReason;
1492
Greg Clayton542e4072012-09-07 17:49:29 +00001493 switch (info->si_code)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001494 {
1495 default:
1496 assert(false && "unexpected si_code for SIGSEGV");
1497 break;
1498 case SEGV_MAPERR:
1499 reason = ProcessMessage::eInvalidAddress;
1500 break;
1501 case SEGV_ACCERR:
1502 reason = ProcessMessage::ePrivilegedAddress;
1503 break;
1504 }
Greg Clayton542e4072012-09-07 17:49:29 +00001505
Stephen Wilson84ffe702011-03-30 15:55:52 +00001506 return reason;
1507}
1508
1509ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001510ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001511{
1512 ProcessMessage::CrashReason reason;
1513 assert(info->si_signo == SIGILL);
1514
1515 reason = ProcessMessage::eInvalidCrashReason;
1516
1517 switch (info->si_code)
1518 {
1519 default:
1520 assert(false && "unexpected si_code for SIGILL");
1521 break;
1522 case ILL_ILLOPC:
1523 reason = ProcessMessage::eIllegalOpcode;
1524 break;
1525 case ILL_ILLOPN:
1526 reason = ProcessMessage::eIllegalOperand;
1527 break;
1528 case ILL_ILLADR:
1529 reason = ProcessMessage::eIllegalAddressingMode;
1530 break;
1531 case ILL_ILLTRP:
1532 reason = ProcessMessage::eIllegalTrap;
1533 break;
1534 case ILL_PRVOPC:
1535 reason = ProcessMessage::ePrivilegedOpcode;
1536 break;
1537 case ILL_PRVREG:
1538 reason = ProcessMessage::ePrivilegedRegister;
1539 break;
1540 case ILL_COPROC:
1541 reason = ProcessMessage::eCoprocessorError;
1542 break;
1543 case ILL_BADSTK:
1544 reason = ProcessMessage::eInternalStackError;
1545 break;
1546 }
1547
1548 return reason;
1549}
1550
1551ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001552ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001553{
1554 ProcessMessage::CrashReason reason;
1555 assert(info->si_signo == SIGFPE);
1556
1557 reason = ProcessMessage::eInvalidCrashReason;
1558
1559 switch (info->si_code)
1560 {
1561 default:
1562 assert(false && "unexpected si_code for SIGFPE");
1563 break;
1564 case FPE_INTDIV:
1565 reason = ProcessMessage::eIntegerDivideByZero;
1566 break;
1567 case FPE_INTOVF:
1568 reason = ProcessMessage::eIntegerOverflow;
1569 break;
1570 case FPE_FLTDIV:
1571 reason = ProcessMessage::eFloatDivideByZero;
1572 break;
1573 case FPE_FLTOVF:
1574 reason = ProcessMessage::eFloatOverflow;
1575 break;
1576 case FPE_FLTUND:
1577 reason = ProcessMessage::eFloatUnderflow;
1578 break;
1579 case FPE_FLTRES:
1580 reason = ProcessMessage::eFloatInexactResult;
1581 break;
1582 case FPE_FLTINV:
1583 reason = ProcessMessage::eFloatInvalidOperation;
1584 break;
1585 case FPE_FLTSUB:
1586 reason = ProcessMessage::eFloatSubscriptRange;
1587 break;
1588 }
1589
1590 return reason;
1591}
1592
1593ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001594ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001595{
1596 ProcessMessage::CrashReason reason;
1597 assert(info->si_signo == SIGBUS);
1598
1599 reason = ProcessMessage::eInvalidCrashReason;
1600
1601 switch (info->si_code)
1602 {
1603 default:
1604 assert(false && "unexpected si_code for SIGBUS");
1605 break;
1606 case BUS_ADRALN:
1607 reason = ProcessMessage::eIllegalAlignment;
1608 break;
1609 case BUS_ADRERR:
1610 reason = ProcessMessage::eIllegalAddress;
1611 break;
1612 case BUS_OBJERR:
1613 reason = ProcessMessage::eHardwareError;
1614 break;
1615 }
1616
1617 return reason;
1618}
1619
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001620void
Johnny Chen25e68e32011-06-14 19:19:50 +00001621ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001622{
1623 int status;
1624 pollfd fdset;
Johnny Chen25e68e32011-06-14 19:19:50 +00001625
Stephen Wilson570243b2011-01-19 01:37:06 +00001626 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001627
1628 fdset.fd = monitor->m_server_fd;
1629 fdset.events = POLLIN | POLLPRI;
1630 fdset.revents = 0;
1631
Stephen Wilson570243b2011-01-19 01:37:06 +00001632 // We are finised with the arguments and are ready to go. Sync with the
1633 // parent thread and start serving operations on the inferior.
1634 sem_post(&args->m_semaphore);
1635
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001636 for (;;)
1637 {
1638 if ((status = poll(&fdset, 1, -1)) < 0)
1639 {
1640 switch (errno)
1641 {
1642 default:
1643 assert(false && "Unexpected poll() failure!");
1644 continue;
1645
1646 case EINTR: continue; // Just poll again.
1647 case EBADF: return; // Connection terminated.
1648 }
1649 }
1650
1651 assert(status == 1 && "Too many descriptors!");
1652
1653 if (fdset.revents & POLLIN)
1654 {
1655 Operation *op = NULL;
1656
1657 READ_AGAIN:
1658 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1659 {
1660 // There is only one acceptable failure.
1661 assert(errno == EINTR);
1662 goto READ_AGAIN;
1663 }
Matt Kopec9eb40a92013-03-14 21:35:26 +00001664 if (status == 0)
1665 continue; // Poll again. The connection probably terminated.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001666 assert(status == sizeof(op));
1667 op->Execute(monitor);
1668 write(fdset.fd, &op, sizeof(op));
1669 }
1670 }
1671}
1672
1673void
1674ProcessMonitor::DoOperation(Operation *op)
1675{
1676 int status;
1677 Operation *ack = NULL;
1678 Mutex::Locker lock(m_server_mutex);
1679
1680 // FIXME: Do proper error checking here.
1681 write(m_client_fd, &op, sizeof(op));
1682
1683READ_AGAIN:
1684 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1685 {
1686 // If interrupted by a signal handler try again. Otherwise the monitor
1687 // thread probably died and we have a stale file descriptor -- abort the
1688 // operation.
1689 if (errno == EINTR)
1690 goto READ_AGAIN;
1691 return;
1692 }
1693
1694 assert(status == sizeof(ack));
1695 assert(ack == op && "Invalid monitor thread response!");
1696}
1697
1698size_t
1699ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1700 Error &error)
1701{
1702 size_t result;
1703 ReadOperation op(vm_addr, buf, size, error, result);
1704 DoOperation(&op);
1705 return result;
1706}
1707
1708size_t
1709ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1710 lldb_private::Error &error)
1711{
1712 size_t result;
1713 WriteOperation op(vm_addr, buf, size, error, result);
1714 DoOperation(&op);
1715 return result;
1716}
1717
1718bool
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00001719ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
Matt Kopec7de48462013-03-06 17:20:48 +00001720 unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001721{
1722 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00001723 ReadRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001724 DoOperation(&op);
1725 return result;
1726}
1727
1728bool
Matt Kopec7de48462013-03-06 17:20:48 +00001729ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00001730 const char* reg_name, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001731{
1732 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00001733 WriteRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001734 DoOperation(&op);
1735 return result;
1736}
1737
1738bool
Matt Kopec7de48462013-03-06 17:20:48 +00001739ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001740{
1741 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00001742 ReadGPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001743 DoOperation(&op);
1744 return result;
1745}
1746
1747bool
Matt Kopec7de48462013-03-06 17:20:48 +00001748ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001749{
1750 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00001751 ReadFPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001752 DoOperation(&op);
1753 return result;
1754}
1755
1756bool
Matt Kopec58c0b962013-03-20 20:34:35 +00001757ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1758{
1759 bool result;
1760 ReadRegisterSetOperation op(tid, buf, buf_size, regset, result);
1761 DoOperation(&op);
1762 return result;
1763}
1764
1765bool
Matt Kopec7de48462013-03-06 17:20:48 +00001766ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001767{
1768 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00001769 WriteGPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001770 DoOperation(&op);
1771 return result;
1772}
1773
1774bool
Matt Kopec7de48462013-03-06 17:20:48 +00001775ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001776{
1777 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00001778 WriteFPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001779 DoOperation(&op);
1780 return result;
1781}
1782
1783bool
Matt Kopec58c0b962013-03-20 20:34:35 +00001784ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1785{
1786 bool result;
1787 WriteRegisterSetOperation op(tid, buf, buf_size, regset, result);
1788 DoOperation(&op);
1789 return result;
1790}
1791
1792bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001793ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001794{
1795 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001796 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001797 DoOperation(&op);
1798 return result;
1799}
1800
1801bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001802ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001803{
1804 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001805 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001806 DoOperation(&op);
1807 return result;
1808}
1809
1810bool
1811ProcessMonitor::BringProcessIntoLimbo()
1812{
1813 bool result;
1814 KillOperation op(result);
1815 DoOperation(&op);
1816 return result;
1817}
1818
1819bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00001820ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001821{
1822 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001823 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001824 DoOperation(&op);
1825 return result;
1826}
1827
1828bool
1829ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1830{
1831 bool result;
1832 EventMessageOperation op(tid, message, result);
1833 DoOperation(&op);
1834 return result;
1835}
1836
Greg Clayton743ecf42012-10-16 20:20:18 +00001837lldb_private::Error
Stephen Wilson84ffe702011-03-30 15:55:52 +00001838ProcessMonitor::Detach()
1839{
Greg Clayton28041352011-11-29 20:50:10 +00001840 lldb_private::Error error;
Greg Clayton743ecf42012-10-16 20:20:18 +00001841 if (m_pid != LLDB_INVALID_PROCESS_ID) {
1842 DetachOperation op(error);
1843 DoOperation(&op);
1844 }
Greg Clayton743ecf42012-10-16 20:20:18 +00001845 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00001846}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001847
1848bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001849ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1850{
Peter Collingbourne62343202011-06-14 03:55:54 +00001851 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001852
1853 if (target_fd == -1)
1854 return false;
1855
Peter Collingbourne62343202011-06-14 03:55:54 +00001856 return (dup2(target_fd, fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001857}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001858
1859void
1860ProcessMonitor::StopMonitoringChildProcess()
1861{
1862 lldb::thread_result_t thread_result;
1863
Stephen Wilsond4182f42011-02-09 20:10:35 +00001864 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001865 {
1866 Host::ThreadCancel(m_monitor_thread, NULL);
1867 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1868 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1869 }
1870}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001871
1872void
1873ProcessMonitor::StopMonitor()
1874{
1875 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00001876 StopOpThread();
Stephen Wilson84ffe702011-03-30 15:55:52 +00001877 CloseFD(m_terminal_fd);
1878 CloseFD(m_client_fd);
1879 CloseFD(m_server_fd);
1880}
1881
1882void
Greg Clayton743ecf42012-10-16 20:20:18 +00001883ProcessMonitor::StopOpThread()
1884{
1885 lldb::thread_result_t result;
1886
1887 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1888 return;
1889
1890 Host::ThreadCancel(m_operation_thread, NULL);
1891 Host::ThreadJoin(m_operation_thread, &result, NULL);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001892 m_operation_thread = LLDB_INVALID_HOST_THREAD;
Greg Clayton743ecf42012-10-16 20:20:18 +00001893}
1894
1895void
Stephen Wilson84ffe702011-03-30 15:55:52 +00001896ProcessMonitor::CloseFD(int &fd)
1897{
1898 if (fd != -1)
1899 {
1900 close(fd);
1901 fd = -1;
1902 }
1903}