blob: 4ebde16245e0e513bd51acca2a99cc048899b239 [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:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000452 ReadRegOperation(lldb::tid_t tid, unsigned offset,
453 RegisterValue &value, bool &result)
454 : m_tid(tid), m_offset(offset),
455 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;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000463 RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000464 bool &m_result;
465};
466
467void
468ReadRegOperation::Execute(ProcessMonitor *monitor)
469{
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000470 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000471
472 // Set errno to zero so that we can detect a failed peek.
473 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000474 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, NULL, 0);
475 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000476 m_result = false;
477 else
478 {
479 m_value = data;
480 m_result = true;
481 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000482 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000483 log->Printf ("ProcessMonitor::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
Johnny Chen30213ff2012-01-05 19:17:38 +0000484 POSIXThread::GetRegisterNameFromOffset(m_offset), data);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000485}
486
487//------------------------------------------------------------------------------
488/// @class WriteRegOperation
489/// @brief Implements ProcessMonitor::WriteRegisterValue.
490class WriteRegOperation : public Operation
491{
492public:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000493 WriteRegOperation(lldb::tid_t tid, unsigned offset,
494 const RegisterValue &value, bool &result)
495 : m_tid(tid), m_offset(offset),
496 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000497 { }
498
499 void Execute(ProcessMonitor *monitor);
500
501private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000502 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000503 uintptr_t m_offset;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000504 const RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000505 bool &m_result;
506};
507
508void
509WriteRegOperation::Execute(ProcessMonitor *monitor)
510{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000511 void* buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000512 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000513
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000514#if __WORDSIZE == 32
515 buf = (void*) m_value.GetAsUInt32();
516#else
517 buf = (void*) m_value.GetAsUInt64();
518#endif
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000519
520 if (log)
521 log->Printf ("ProcessMonitor::%s() reg %s: %p", __FUNCTION__,
Johnny Chen30213ff2012-01-05 19:17:38 +0000522 POSIXThread::GetRegisterNameFromOffset(m_offset), buf);
Matt Kopec7de48462013-03-06 17:20:48 +0000523 if (PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000524 m_result = false;
525 else
526 m_result = true;
527}
528
529//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000530/// @class ReadGPROperation
531/// @brief Implements ProcessMonitor::ReadGPR.
532class ReadGPROperation : public Operation
533{
534public:
Matt Kopec7de48462013-03-06 17:20:48 +0000535 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
536 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000537 { }
538
539 void Execute(ProcessMonitor *monitor);
540
541private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000542 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000543 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000544 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000545 bool &m_result;
546};
547
548void
549ReadGPROperation::Execute(ProcessMonitor *monitor)
550{
Matt Kopec7de48462013-03-06 17:20:48 +0000551 if (PTRACE(PTRACE_GETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000552 m_result = false;
553 else
554 m_result = true;
555}
556
557//------------------------------------------------------------------------------
558/// @class ReadFPROperation
559/// @brief Implements ProcessMonitor::ReadFPR.
560class ReadFPROperation : public Operation
561{
562public:
Matt Kopec7de48462013-03-06 17:20:48 +0000563 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
564 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000565 { }
566
567 void Execute(ProcessMonitor *monitor);
568
569private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000570 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000571 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000572 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000573 bool &m_result;
574};
575
576void
577ReadFPROperation::Execute(ProcessMonitor *monitor)
578{
Matt Kopec7de48462013-03-06 17:20:48 +0000579 if (PTRACE(PTRACE_GETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000580 m_result = false;
581 else
582 m_result = true;
583}
584
585//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000586/// @class ReadRegisterSetOperation
587/// @brief Implements ProcessMonitor::ReadRegisterSet.
588class ReadRegisterSetOperation : public Operation
589{
590public:
591 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
592 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
593 { }
594
595 void Execute(ProcessMonitor *monitor);
596
597private:
598 lldb::tid_t m_tid;
599 void *m_buf;
600 size_t m_buf_size;
601 const unsigned int m_regset;
602 bool &m_result;
603};
604
605void
606ReadRegisterSetOperation::Execute(ProcessMonitor *monitor)
607{
608 if (PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
609 m_result = false;
610 else
611 m_result = true;
612}
613
614//------------------------------------------------------------------------------
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000615/// @class WriteGPROperation
616/// @brief Implements ProcessMonitor::WriteGPR.
617class WriteGPROperation : public Operation
618{
619public:
Matt Kopec7de48462013-03-06 17:20:48 +0000620 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
621 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000622 { }
623
624 void Execute(ProcessMonitor *monitor);
625
626private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000627 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000628 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000629 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000630 bool &m_result;
631};
632
633void
634WriteGPROperation::Execute(ProcessMonitor *monitor)
635{
Matt Kopec7de48462013-03-06 17:20:48 +0000636 if (PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000637 m_result = false;
638 else
639 m_result = true;
640}
641
642//------------------------------------------------------------------------------
643/// @class WriteFPROperation
644/// @brief Implements ProcessMonitor::WriteFPR.
645class WriteFPROperation : public Operation
646{
647public:
Matt Kopec7de48462013-03-06 17:20:48 +0000648 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
649 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000650 { }
651
652 void Execute(ProcessMonitor *monitor);
653
654private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000655 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000656 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000657 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000658 bool &m_result;
659};
660
661void
662WriteFPROperation::Execute(ProcessMonitor *monitor)
663{
Matt Kopec7de48462013-03-06 17:20:48 +0000664 if (PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000665 m_result = false;
666 else
667 m_result = true;
668}
669
670//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000671/// @class WriteRegisterSetOperation
672/// @brief Implements ProcessMonitor::WriteRegisterSet.
673class WriteRegisterSetOperation : public Operation
674{
675public:
676 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
677 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
678 { }
679
680 void Execute(ProcessMonitor *monitor);
681
682private:
683 lldb::tid_t m_tid;
684 void *m_buf;
685 size_t m_buf_size;
686 const unsigned int m_regset;
687 bool &m_result;
688};
689
690void
691WriteRegisterSetOperation::Execute(ProcessMonitor *monitor)
692{
693 if (PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
694 m_result = false;
695 else
696 m_result = true;
697}
698
699//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000700/// @class ResumeOperation
701/// @brief Implements ProcessMonitor::Resume.
702class ResumeOperation : public Operation
703{
704public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000705 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
706 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000707
708 void Execute(ProcessMonitor *monitor);
709
710private:
711 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000712 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000713 bool &m_result;
714};
715
716void
717ResumeOperation::Execute(ProcessMonitor *monitor)
718{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000719 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000720
721 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
722 data = m_signo;
723
Matt Kopec7de48462013-03-06 17:20:48 +0000724 if (PTRACE(PTRACE_CONT, m_tid, NULL, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000725 m_result = false;
726 else
727 m_result = true;
728}
729
730//------------------------------------------------------------------------------
731/// @class ResumeOperation
732/// @brief Implements ProcessMonitor::SingleStep.
733class SingleStepOperation : public Operation
734{
735public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000736 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
737 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000738
739 void Execute(ProcessMonitor *monitor);
740
741private:
742 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000743 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000744 bool &m_result;
745};
746
747void
748SingleStepOperation::Execute(ProcessMonitor *monitor)
749{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000750 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000751
752 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
753 data = m_signo;
754
Matt Kopec7de48462013-03-06 17:20:48 +0000755 if (PTRACE(PTRACE_SINGLESTEP, m_tid, NULL, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000756 m_result = false;
757 else
758 m_result = true;
759}
760
761//------------------------------------------------------------------------------
762/// @class SiginfoOperation
763/// @brief Implements ProcessMonitor::GetSignalInfo.
764class SiginfoOperation : public Operation
765{
766public:
Daniel Maleaa35970a2012-11-23 18:09:58 +0000767 SiginfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
768 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000769
770 void Execute(ProcessMonitor *monitor);
771
772private:
773 lldb::tid_t m_tid;
774 void *m_info;
775 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000776 int &m_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000777};
778
779void
780SiginfoOperation::Execute(ProcessMonitor *monitor)
781{
Matt Kopec7de48462013-03-06 17:20:48 +0000782 if (PTRACE(PTRACE_GETSIGINFO, m_tid, NULL, m_info, 0)) {
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000783 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000784 m_err = errno;
785 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000786 else
787 m_result = true;
788}
789
790//------------------------------------------------------------------------------
791/// @class EventMessageOperation
792/// @brief Implements ProcessMonitor::GetEventMessage.
793class EventMessageOperation : public Operation
794{
795public:
796 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
797 : m_tid(tid), m_message(message), m_result(result) { }
798
799 void Execute(ProcessMonitor *monitor);
800
801private:
802 lldb::tid_t m_tid;
803 unsigned long *m_message;
804 bool &m_result;
805};
806
807void
808EventMessageOperation::Execute(ProcessMonitor *monitor)
809{
Matt Kopec7de48462013-03-06 17:20:48 +0000810 if (PTRACE(PTRACE_GETEVENTMSG, m_tid, NULL, m_message, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000811 m_result = false;
812 else
813 m_result = true;
814}
815
816//------------------------------------------------------------------------------
817/// @class KillOperation
818/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
819class KillOperation : public Operation
820{
821public:
822 KillOperation(bool &result) : m_result(result) { }
823
824 void Execute(ProcessMonitor *monitor);
825
826private:
827 bool &m_result;
828};
829
830void
831KillOperation::Execute(ProcessMonitor *monitor)
832{
833 lldb::pid_t pid = monitor->GetPID();
834
Matt Kopec7de48462013-03-06 17:20:48 +0000835 if (PTRACE(PTRACE_KILL, pid, NULL, NULL, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000836 m_result = false;
837 else
838 m_result = true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000839}
840
Greg Clayton28041352011-11-29 20:50:10 +0000841//------------------------------------------------------------------------------
842/// @class KillOperation
843/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
844class DetachOperation : public Operation
845{
846public:
847 DetachOperation(Error &result) : m_error(result) { }
848
849 void Execute(ProcessMonitor *monitor);
850
851private:
852 Error &m_error;
853};
854
855void
856DetachOperation::Execute(ProcessMonitor *monitor)
857{
858 lldb::pid_t pid = monitor->GetPID();
859
860 if (ptrace(PT_DETACH, pid, NULL, 0) < 0)
861 m_error.SetErrorToErrno();
Greg Clayton542e4072012-09-07 17:49:29 +0000862
Greg Clayton28041352011-11-29 20:50:10 +0000863}
864
Johnny Chen25e68e32011-06-14 19:19:50 +0000865ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
866 : m_monitor(monitor)
867{
868 sem_init(&m_semaphore, 0, 0);
869}
870
871ProcessMonitor::OperationArgs::~OperationArgs()
872{
873 sem_destroy(&m_semaphore);
874}
875
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000876ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
877 lldb_private::Module *module,
878 char const **argv,
879 char const **envp,
880 const char *stdin_path,
881 const char *stdout_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000882 const char *stderr_path,
883 const char *working_dir)
Johnny Chen25e68e32011-06-14 19:19:50 +0000884 : OperationArgs(monitor),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000885 m_module(module),
886 m_argv(argv),
887 m_envp(envp),
888 m_stdin_path(stdin_path),
889 m_stdout_path(stdout_path),
Daniel Malea6217d2a2013-01-08 14:49:22 +0000890 m_stderr_path(stderr_path),
891 m_working_dir(working_dir) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000892
893ProcessMonitor::LaunchArgs::~LaunchArgs()
Johnny Chen25e68e32011-06-14 19:19:50 +0000894{ }
895
896ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
897 lldb::pid_t pid)
898 : OperationArgs(monitor), m_pid(pid) { }
899
900ProcessMonitor::AttachArgs::~AttachArgs()
901{ }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000902
903//------------------------------------------------------------------------------
904/// The basic design of the ProcessMonitor is built around two threads.
905///
906/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
907/// for changes in the debugee state. When a change is detected a
908/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
909/// "drives" state changes in the debugger.
910///
911/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000912/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000913/// operations such as register reads/writes, stepping, etc. See the comments
914/// on the Operation class for more info as to why this is needed.
Johnny Chen30213ff2012-01-05 19:17:38 +0000915ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000916 Module *module,
917 const char *argv[],
918 const char *envp[],
919 const char *stdin_path,
920 const char *stdout_path,
921 const char *stderr_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000922 const char *working_dir,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000923 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000924 : m_process(static_cast<ProcessLinux *>(process)),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000925 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +0000926 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000927 m_pid(LLDB_INVALID_PROCESS_ID),
928 m_terminal_fd(-1),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000929 m_client_fd(-1),
930 m_server_fd(-1)
931{
Greg Clayton7b0992d2013-04-18 22:45:39 +0000932 std::unique_ptr<LaunchArgs> args;
Stephen Wilson57740ec2011-01-15 00:12:41 +0000933
934 args.reset(new LaunchArgs(this, module, argv, envp,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000935 stdin_path, stdout_path, stderr_path, working_dir));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000936
937 // Server/client descriptors.
938 if (!EnableIPC())
939 {
940 error.SetErrorToGenericError();
941 error.SetErrorString("Monitor failed to initialize.");
942 }
943
Johnny Chen25e68e32011-06-14 19:19:50 +0000944 StartLaunchOpThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000945 if (!error.Success())
946 return;
947
948WAIT_AGAIN:
949 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000950 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000951 {
952 if (errno == EINTR)
953 goto WAIT_AGAIN;
954 else
955 {
956 error.SetErrorToErrno();
957 return;
958 }
959 }
960
961 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000962 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000963 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000964 StopOpThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000965 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000966 return;
967 }
968
969 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000970 m_monitor_thread = Host::StartMonitoringChildProcess(
971 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Stephen Wilsond4182f42011-02-09 20:10:35 +0000972 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000973 {
974 error.SetErrorToGenericError();
975 error.SetErrorString("Process launch failed.");
976 return;
977 }
978}
979
Johnny Chen30213ff2012-01-05 19:17:38 +0000980ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen25e68e32011-06-14 19:19:50 +0000981 lldb::pid_t pid,
982 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000983 : m_process(static_cast<ProcessLinux *>(process)),
Johnny Chen25e68e32011-06-14 19:19:50 +0000984 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +0000985 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Johnny Chen25e68e32011-06-14 19:19:50 +0000986 m_pid(LLDB_INVALID_PROCESS_ID),
987 m_terminal_fd(-1),
Matt Kopec7de48462013-03-06 17:20:48 +0000988
Johnny Chen25e68e32011-06-14 19:19:50 +0000989 m_client_fd(-1),
990 m_server_fd(-1)
991{
Greg Clayton7b0992d2013-04-18 22:45:39 +0000992 std::unique_ptr<AttachArgs> args;
Johnny Chen25e68e32011-06-14 19:19:50 +0000993
994 args.reset(new AttachArgs(this, pid));
995
996 // Server/client descriptors.
997 if (!EnableIPC())
998 {
999 error.SetErrorToGenericError();
1000 error.SetErrorString("Monitor failed to initialize.");
1001 }
1002
1003 StartAttachOpThread(args.get(), error);
1004 if (!error.Success())
1005 return;
1006
1007WAIT_AGAIN:
1008 // Wait for the operation thread to initialize.
1009 if (sem_wait(&args->m_semaphore))
1010 {
1011 if (errno == EINTR)
1012 goto WAIT_AGAIN;
1013 else
1014 {
1015 error.SetErrorToErrno();
1016 return;
1017 }
1018 }
1019
Greg Clayton743ecf42012-10-16 20:20:18 +00001020 // Check that the attach was a success.
Johnny Chen25e68e32011-06-14 19:19:50 +00001021 if (!args->m_error.Success())
1022 {
Greg Clayton743ecf42012-10-16 20:20:18 +00001023 StopOpThread();
Johnny Chen25e68e32011-06-14 19:19:50 +00001024 error = args->m_error;
1025 return;
1026 }
1027
1028 // Finally, start monitoring the child process for change in state.
1029 m_monitor_thread = Host::StartMonitoringChildProcess(
1030 ProcessMonitor::MonitorCallback, this, GetPID(), true);
1031 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
1032 {
1033 error.SetErrorToGenericError();
1034 error.SetErrorString("Process attach failed.");
1035 return;
1036 }
1037}
1038
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001039ProcessMonitor::~ProcessMonitor()
1040{
Stephen Wilson84ffe702011-03-30 15:55:52 +00001041 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001042}
1043
1044//------------------------------------------------------------------------------
1045// Thread setup and tear down.
1046void
Johnny Chen25e68e32011-06-14 19:19:50 +00001047ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001048{
1049 static const char *g_thread_name = "lldb.process.linux.operation";
1050
Stephen Wilsond4182f42011-02-09 20:10:35 +00001051 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001052 return;
1053
1054 m_operation_thread =
Johnny Chen25e68e32011-06-14 19:19:50 +00001055 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001056}
1057
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001058void *
Johnny Chen25e68e32011-06-14 19:19:50 +00001059ProcessMonitor::LaunchOpThread(void *arg)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001060{
1061 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1062
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001063 if (!Launch(args)) {
1064 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001065 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001066 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001067
Stephen Wilson570243b2011-01-19 01:37:06 +00001068 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001069 return NULL;
1070}
1071
1072bool
1073ProcessMonitor::Launch(LaunchArgs *args)
1074{
1075 ProcessMonitor *monitor = args->m_monitor;
1076 ProcessLinux &process = monitor->GetProcess();
1077 const char **argv = args->m_argv;
1078 const char **envp = args->m_envp;
1079 const char *stdin_path = args->m_stdin_path;
1080 const char *stdout_path = args->m_stdout_path;
1081 const char *stderr_path = args->m_stderr_path;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001082 const char *working_dir = args->m_working_dir;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001083
1084 lldb_utility::PseudoTerminal terminal;
1085 const size_t err_len = 1024;
1086 char err_str[err_len];
1087 lldb::pid_t pid;
Matt Kopec650648f2013-01-08 16:30:18 +00001088 long ptrace_opts = 0;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001089
1090 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001091 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001092
Stephen Wilson57740ec2011-01-15 00:12:41 +00001093 // Propagate the environment if one is not supplied.
1094 if (envp == NULL || envp[0] == NULL)
1095 envp = const_cast<const char **>(environ);
1096
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001097 // Pseudo terminal setup.
1098 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
1099 {
1100 args->m_error.SetErrorToGenericError();
1101 args->m_error.SetErrorString("Could not open controlling TTY.");
1102 goto FINISH;
1103 }
1104
Daniel Maleaa85e6b62012-12-07 22:21:08 +00001105 if ((pid = terminal.Fork(err_str, err_len)) == -1)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001106 {
1107 args->m_error.SetErrorToGenericError();
1108 args->m_error.SetErrorString("Process fork failed.");
1109 goto FINISH;
1110 }
1111
Peter Collingbourne6a520222011-06-14 03:55:58 +00001112 // Recognized child exit status codes.
1113 enum {
1114 ePtraceFailed = 1,
1115 eDupStdinFailed,
1116 eDupStdoutFailed,
1117 eDupStderrFailed,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001118 eChdirFailed,
Peter Collingbourne6a520222011-06-14 03:55:58 +00001119 eExecFailed
1120 };
1121
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001122 // Child process.
1123 if (pid == 0)
1124 {
1125 // Trace this process.
Matt Kopec7de48462013-03-06 17:20:48 +00001126 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL, 0) < 0)
Peter Collingbourne6a520222011-06-14 03:55:58 +00001127 exit(ePtraceFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001128
1129 // Do not inherit setgid powers.
1130 setgid(getgid());
1131
1132 // Let us have our own process group.
1133 setpgid(0, 0);
1134
Greg Clayton710dd5a2011-01-08 20:28:42 +00001135 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001136 //
1137 // FIXME: If two or more of the paths are the same we needlessly open
1138 // the same file multiple times.
1139 if (stdin_path != NULL && stdin_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001140 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001141 exit(eDupStdinFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001142
1143 if (stdout_path != NULL && stdout_path[0])
1144 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001145 exit(eDupStdoutFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001146
1147 if (stderr_path != NULL && stderr_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001148 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001149 exit(eDupStderrFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001150
Daniel Malea6217d2a2013-01-08 14:49:22 +00001151 // Change working directory
1152 if (working_dir != NULL && working_dir[0])
1153 if (0 != ::chdir(working_dir))
1154 exit(eChdirFailed);
1155
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001156 // Execute. We should never return.
1157 execve(argv[0],
1158 const_cast<char *const *>(argv),
1159 const_cast<char *const *>(envp));
Peter Collingbourne6a520222011-06-14 03:55:58 +00001160 exit(eExecFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001161 }
1162
1163 // Wait for the child process to to trap on its call to execve.
Peter Collingbourne6a520222011-06-14 03:55:58 +00001164 pid_t wpid;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001165 int status;
Peter Collingbourne6a520222011-06-14 03:55:58 +00001166 if ((wpid = waitpid(pid, &status, 0)) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001167 {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001168 args->m_error.SetErrorToErrno();
1169 goto FINISH;
1170 }
Peter Collingbourne6a520222011-06-14 03:55:58 +00001171 else if (WIFEXITED(status))
1172 {
1173 // open, dup or execve likely failed for some reason.
1174 args->m_error.SetErrorToGenericError();
1175 switch (WEXITSTATUS(status))
1176 {
Greg Clayton542e4072012-09-07 17:49:29 +00001177 case ePtraceFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001178 args->m_error.SetErrorString("Child ptrace failed.");
1179 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001180 case eDupStdinFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001181 args->m_error.SetErrorString("Child open stdin failed.");
1182 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001183 case eDupStdoutFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001184 args->m_error.SetErrorString("Child open stdout failed.");
1185 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001186 case eDupStderrFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001187 args->m_error.SetErrorString("Child open stderr failed.");
1188 break;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001189 case eChdirFailed:
1190 args->m_error.SetErrorString("Child failed to set working directory.");
1191 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001192 case eExecFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001193 args->m_error.SetErrorString("Child exec failed.");
1194 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001195 default:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001196 args->m_error.SetErrorString("Child returned unknown exit status.");
1197 break;
1198 }
1199 goto FINISH;
1200 }
1201 assert(WIFSTOPPED(status) && wpid == pid &&
1202 "Could not sync with inferior process.");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001203
1204 // Have the child raise an event on exit. This is used to keep the child in
1205 // limbo until it is destroyed.
Matt Kopec650648f2013-01-08 16:30:18 +00001206 ptrace_opts |= PTRACE_O_TRACEEXIT;
1207
1208 // Have the tracer trace threads which spawn in the inferior process.
1209 ptrace_opts |= PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE;
1210
Matt Kopec7de48462013-03-06 17:20:48 +00001211 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)ptrace_opts, 0) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001212 {
1213 args->m_error.SetErrorToErrno();
1214 goto FINISH;
1215 }
1216
1217 // Release the master terminal descriptor and pass it off to the
1218 // ProcessMonitor instance. Similarly stash the inferior pid.
1219 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1220 monitor->m_pid = pid;
1221
Stephen Wilson26977162011-03-23 02:14:42 +00001222 // Set the terminal fd to be in non blocking mode (it simplifies the
1223 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1224 // descriptor to read from).
1225 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1226 goto FINISH;
1227
Johnny Chen30213ff2012-01-05 19:17:38 +00001228 // Update the process thread list with this new thread.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001229 // FIXME: should we be letting UpdateThreadList handle this?
1230 // FIXME: by using pids instead of tids, we can only support one thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001231 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001232 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001233 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001234 process.GetThreadList().AddThread(inferior);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001235
1236 // Let our process instance know the thread has stopped.
1237 process.SendMessage(ProcessMessage::Trace(pid));
1238
1239FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001240 return args->m_error.Success();
1241}
1242
1243bool
1244ProcessMonitor::EnableIPC()
1245{
1246 int fd[2];
1247
1248 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
1249 return false;
1250
1251 m_client_fd = fd[0];
1252 m_server_fd = fd[1];
1253 return true;
1254}
1255
Johnny Chen25e68e32011-06-14 19:19:50 +00001256void
1257ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1258{
1259 static const char *g_thread_name = "lldb.process.linux.operation";
1260
1261 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1262 return;
1263
1264 m_operation_thread =
1265 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1266}
1267
Johnny Chen25e68e32011-06-14 19:19:50 +00001268void *
1269ProcessMonitor::AttachOpThread(void *arg)
1270{
1271 AttachArgs *args = static_cast<AttachArgs*>(arg);
1272
Greg Clayton743ecf42012-10-16 20:20:18 +00001273 if (!Attach(args)) {
1274 sem_post(&args->m_semaphore);
Johnny Chen25e68e32011-06-14 19:19:50 +00001275 return NULL;
Greg Clayton743ecf42012-10-16 20:20:18 +00001276 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001277
1278 ServeOperation(args);
1279 return NULL;
1280}
1281
1282bool
1283ProcessMonitor::Attach(AttachArgs *args)
1284{
1285 lldb::pid_t pid = args->m_pid;
1286
1287 ProcessMonitor *monitor = args->m_monitor;
1288 ProcessLinux &process = monitor->GetProcess();
Johnny Chen25e68e32011-06-14 19:19:50 +00001289 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001290 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen25e68e32011-06-14 19:19:50 +00001291
1292 if (pid <= 1)
1293 {
1294 args->m_error.SetErrorToGenericError();
1295 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1296 goto FINISH;
1297 }
1298
1299 // Attach to the requested process.
Matt Kopec7de48462013-03-06 17:20:48 +00001300 if (PTRACE(PTRACE_ATTACH, pid, NULL, NULL, 0) < 0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001301 {
1302 args->m_error.SetErrorToErrno();
1303 goto FINISH;
1304 }
1305
1306 int status;
1307 if ((status = waitpid(pid, NULL, 0)) < 0)
1308 {
1309 args->m_error.SetErrorToErrno();
1310 goto FINISH;
1311 }
1312
Greg Clayton926cce72012-10-12 16:10:12 +00001313 monitor->m_pid = pid;
1314
Johnny Chen30213ff2012-01-05 19:17:38 +00001315 // Update the process thread list with the attached thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001316 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001317 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001318 log->Printf ("ProcessMonitor::%s() adding tid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen25e68e32011-06-14 19:19:50 +00001319 process.GetThreadList().AddThread(inferior);
Johnny Chen25e68e32011-06-14 19:19:50 +00001320
1321 // Let our process instance know the thread has stopped.
1322 process.SendMessage(ProcessMessage::Trace(pid));
1323
1324 FINISH:
1325 return args->m_error.Success();
1326}
1327
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001328bool
1329ProcessMonitor::MonitorCallback(void *callback_baton,
1330 lldb::pid_t pid,
Peter Collingbourne2c67b9a2011-11-21 00:10:19 +00001331 bool exited,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001332 int signal,
1333 int status)
1334{
1335 ProcessMessage message;
1336 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
1337 ProcessLinux *process = monitor->m_process;
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001338 assert(process);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001339 bool stop_monitoring;
1340 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001341 int ptrace_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001342
Daniel Maleaa35970a2012-11-23 18:09:58 +00001343 if (!monitor->GetSignalInfo(pid, &info, ptrace_err)) {
1344 if (ptrace_err == EINVAL) {
1345 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1346 if (!monitor->Resume(pid, SIGSTOP)) {
1347 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1348 }
1349 stop_monitoring = false;
1350 } else {
1351 // ptrace(GETSIGINFO) failed (but not due to group-stop). Most likely,
1352 // this means the child pid is gone (or not being debugged) therefore
1353 // stop the monitor thread.
1354 stop_monitoring = true;
1355 }
1356 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00001357 else {
1358 switch (info.si_signo)
1359 {
1360 case SIGTRAP:
1361 message = MonitorSIGTRAP(monitor, &info, pid);
1362 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001363
Stephen Wilson84ffe702011-03-30 15:55:52 +00001364 default:
1365 message = MonitorSignal(monitor, &info, pid);
1366 break;
1367 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001368
Stephen Wilson84ffe702011-03-30 15:55:52 +00001369 process->SendMessage(message);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001370 stop_monitoring = !process->IsAlive();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001371 }
1372
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001373 return stop_monitoring;
1374}
1375
1376ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +00001377ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001378 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001379{
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001380 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001381
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001382 assert(monitor);
1383 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001384
Stephen Wilson84ffe702011-03-30 15:55:52 +00001385 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001386 {
1387 default:
1388 assert(false && "Unexpected SIGTRAP code!");
1389 break;
1390
Matt Kopec650648f2013-01-08 16:30:18 +00001391 case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1392 case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1393 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1394 {
1395 unsigned long tid = 0;
1396 if (!monitor->GetEventMessage(pid, &tid))
1397 tid = -1;
1398 message = ProcessMessage::NewThread(pid, tid);
1399 break;
1400 }
1401
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001402 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1403 {
1404 // The inferior process is about to exit. Maintain the process in a
1405 // state of "limbo" until we are explicitly commanded to detach,
1406 // destroy, resume, etc.
1407 unsigned long data = 0;
1408 if (!monitor->GetEventMessage(pid, &data))
1409 data = -1;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001410 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001411 break;
1412 }
1413
1414 case 0:
1415 case TRAP_TRACE:
1416 message = ProcessMessage::Trace(pid);
1417 break;
1418
1419 case SI_KERNEL:
1420 case TRAP_BRKPT:
1421 message = ProcessMessage::Break(pid);
1422 break;
Matt Kopece9ea0da2013-05-07 19:29:28 +00001423
1424 case TRAP_HWBKPT:
1425 message = ProcessMessage::Watch(pid, (lldb::addr_t)info->si_addr);
1426 break;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001427 }
1428
1429 return message;
1430}
1431
Stephen Wilson84ffe702011-03-30 15:55:52 +00001432ProcessMessage
1433ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001434 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001435{
1436 ProcessMessage message;
1437 int signo = info->si_signo;
1438
1439 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1440 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1441 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1442 //
1443 // IOW, user generated signals never generate what we consider to be a
1444 // "crash".
1445 //
1446 // Similarly, ACK signals generated by this monitor.
1447 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1448 {
1449 if (info->si_pid == getpid())
1450 return ProcessMessage::SignalDelivered(pid, signo);
1451 else
1452 return ProcessMessage::Signal(pid, signo);
1453 }
1454
1455 if (signo == SIGSEGV) {
1456 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1457 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1458 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1459 }
1460
1461 if (signo == SIGILL) {
1462 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1463 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1464 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1465 }
1466
1467 if (signo == SIGFPE) {
1468 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1469 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1470 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1471 }
1472
1473 if (signo == SIGBUS) {
1474 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1475 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1476 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1477 }
1478
1479 // Everything else is "normal" and does not require any special action on
1480 // our part.
1481 return ProcessMessage::Signal(pid, signo);
1482}
1483
1484ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001485ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001486{
1487 ProcessMessage::CrashReason reason;
1488 assert(info->si_signo == SIGSEGV);
1489
1490 reason = ProcessMessage::eInvalidCrashReason;
1491
Greg Clayton542e4072012-09-07 17:49:29 +00001492 switch (info->si_code)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001493 {
1494 default:
1495 assert(false && "unexpected si_code for SIGSEGV");
1496 break;
1497 case SEGV_MAPERR:
1498 reason = ProcessMessage::eInvalidAddress;
1499 break;
1500 case SEGV_ACCERR:
1501 reason = ProcessMessage::ePrivilegedAddress;
1502 break;
1503 }
Greg Clayton542e4072012-09-07 17:49:29 +00001504
Stephen Wilson84ffe702011-03-30 15:55:52 +00001505 return reason;
1506}
1507
1508ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001509ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001510{
1511 ProcessMessage::CrashReason reason;
1512 assert(info->si_signo == SIGILL);
1513
1514 reason = ProcessMessage::eInvalidCrashReason;
1515
1516 switch (info->si_code)
1517 {
1518 default:
1519 assert(false && "unexpected si_code for SIGILL");
1520 break;
1521 case ILL_ILLOPC:
1522 reason = ProcessMessage::eIllegalOpcode;
1523 break;
1524 case ILL_ILLOPN:
1525 reason = ProcessMessage::eIllegalOperand;
1526 break;
1527 case ILL_ILLADR:
1528 reason = ProcessMessage::eIllegalAddressingMode;
1529 break;
1530 case ILL_ILLTRP:
1531 reason = ProcessMessage::eIllegalTrap;
1532 break;
1533 case ILL_PRVOPC:
1534 reason = ProcessMessage::ePrivilegedOpcode;
1535 break;
1536 case ILL_PRVREG:
1537 reason = ProcessMessage::ePrivilegedRegister;
1538 break;
1539 case ILL_COPROC:
1540 reason = ProcessMessage::eCoprocessorError;
1541 break;
1542 case ILL_BADSTK:
1543 reason = ProcessMessage::eInternalStackError;
1544 break;
1545 }
1546
1547 return reason;
1548}
1549
1550ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001551ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001552{
1553 ProcessMessage::CrashReason reason;
1554 assert(info->si_signo == SIGFPE);
1555
1556 reason = ProcessMessage::eInvalidCrashReason;
1557
1558 switch (info->si_code)
1559 {
1560 default:
1561 assert(false && "unexpected si_code for SIGFPE");
1562 break;
1563 case FPE_INTDIV:
1564 reason = ProcessMessage::eIntegerDivideByZero;
1565 break;
1566 case FPE_INTOVF:
1567 reason = ProcessMessage::eIntegerOverflow;
1568 break;
1569 case FPE_FLTDIV:
1570 reason = ProcessMessage::eFloatDivideByZero;
1571 break;
1572 case FPE_FLTOVF:
1573 reason = ProcessMessage::eFloatOverflow;
1574 break;
1575 case FPE_FLTUND:
1576 reason = ProcessMessage::eFloatUnderflow;
1577 break;
1578 case FPE_FLTRES:
1579 reason = ProcessMessage::eFloatInexactResult;
1580 break;
1581 case FPE_FLTINV:
1582 reason = ProcessMessage::eFloatInvalidOperation;
1583 break;
1584 case FPE_FLTSUB:
1585 reason = ProcessMessage::eFloatSubscriptRange;
1586 break;
1587 }
1588
1589 return reason;
1590}
1591
1592ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001593ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001594{
1595 ProcessMessage::CrashReason reason;
1596 assert(info->si_signo == SIGBUS);
1597
1598 reason = ProcessMessage::eInvalidCrashReason;
1599
1600 switch (info->si_code)
1601 {
1602 default:
1603 assert(false && "unexpected si_code for SIGBUS");
1604 break;
1605 case BUS_ADRALN:
1606 reason = ProcessMessage::eIllegalAlignment;
1607 break;
1608 case BUS_ADRERR:
1609 reason = ProcessMessage::eIllegalAddress;
1610 break;
1611 case BUS_OBJERR:
1612 reason = ProcessMessage::eHardwareError;
1613 break;
1614 }
1615
1616 return reason;
1617}
1618
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001619void
Johnny Chen25e68e32011-06-14 19:19:50 +00001620ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001621{
1622 int status;
1623 pollfd fdset;
Johnny Chen25e68e32011-06-14 19:19:50 +00001624
Stephen Wilson570243b2011-01-19 01:37:06 +00001625 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001626
1627 fdset.fd = monitor->m_server_fd;
1628 fdset.events = POLLIN | POLLPRI;
1629 fdset.revents = 0;
1630
Stephen Wilson570243b2011-01-19 01:37:06 +00001631 // We are finised with the arguments and are ready to go. Sync with the
1632 // parent thread and start serving operations on the inferior.
1633 sem_post(&args->m_semaphore);
1634
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001635 for (;;)
1636 {
1637 if ((status = poll(&fdset, 1, -1)) < 0)
1638 {
1639 switch (errno)
1640 {
1641 default:
1642 assert(false && "Unexpected poll() failure!");
1643 continue;
1644
1645 case EINTR: continue; // Just poll again.
1646 case EBADF: return; // Connection terminated.
1647 }
1648 }
1649
1650 assert(status == 1 && "Too many descriptors!");
1651
1652 if (fdset.revents & POLLIN)
1653 {
1654 Operation *op = NULL;
1655
1656 READ_AGAIN:
1657 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1658 {
1659 // There is only one acceptable failure.
1660 assert(errno == EINTR);
1661 goto READ_AGAIN;
1662 }
Matt Kopec9eb40a92013-03-14 21:35:26 +00001663 if (status == 0)
1664 continue; // Poll again. The connection probably terminated.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001665 assert(status == sizeof(op));
1666 op->Execute(monitor);
1667 write(fdset.fd, &op, sizeof(op));
1668 }
1669 }
1670}
1671
1672void
1673ProcessMonitor::DoOperation(Operation *op)
1674{
1675 int status;
1676 Operation *ack = NULL;
1677 Mutex::Locker lock(m_server_mutex);
1678
1679 // FIXME: Do proper error checking here.
1680 write(m_client_fd, &op, sizeof(op));
1681
1682READ_AGAIN:
1683 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1684 {
1685 // If interrupted by a signal handler try again. Otherwise the monitor
1686 // thread probably died and we have a stale file descriptor -- abort the
1687 // operation.
1688 if (errno == EINTR)
1689 goto READ_AGAIN;
1690 return;
1691 }
1692
1693 assert(status == sizeof(ack));
1694 assert(ack == op && "Invalid monitor thread response!");
1695}
1696
1697size_t
1698ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1699 Error &error)
1700{
1701 size_t result;
1702 ReadOperation op(vm_addr, buf, size, error, result);
1703 DoOperation(&op);
1704 return result;
1705}
1706
1707size_t
1708ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1709 lldb_private::Error &error)
1710{
1711 size_t result;
1712 WriteOperation op(vm_addr, buf, size, error, result);
1713 DoOperation(&op);
1714 return result;
1715}
1716
1717bool
Matt Kopec7de48462013-03-06 17:20:48 +00001718ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset,
1719 unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001720{
1721 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001722 ReadRegOperation op(tid, offset, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001723 DoOperation(&op);
1724 return result;
1725}
1726
1727bool
Matt Kopec7de48462013-03-06 17:20:48 +00001728ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
1729 const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001730{
1731 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001732 WriteRegOperation op(tid, offset, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001733 DoOperation(&op);
1734 return result;
1735}
1736
1737bool
Matt Kopec7de48462013-03-06 17:20:48 +00001738ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001739{
1740 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00001741 ReadGPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001742 DoOperation(&op);
1743 return result;
1744}
1745
1746bool
Matt Kopec7de48462013-03-06 17:20:48 +00001747ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001748{
1749 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00001750 ReadFPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001751 DoOperation(&op);
1752 return result;
1753}
1754
1755bool
Matt Kopec58c0b962013-03-20 20:34:35 +00001756ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1757{
1758 bool result;
1759 ReadRegisterSetOperation op(tid, buf, buf_size, regset, result);
1760 DoOperation(&op);
1761 return result;
1762}
1763
1764bool
Matt Kopec7de48462013-03-06 17:20:48 +00001765ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001766{
1767 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00001768 WriteGPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001769 DoOperation(&op);
1770 return result;
1771}
1772
1773bool
Matt Kopec7de48462013-03-06 17:20:48 +00001774ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001775{
1776 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00001777 WriteFPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001778 DoOperation(&op);
1779 return result;
1780}
1781
1782bool
Matt Kopec58c0b962013-03-20 20:34:35 +00001783ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1784{
1785 bool result;
1786 WriteRegisterSetOperation op(tid, buf, buf_size, regset, result);
1787 DoOperation(&op);
1788 return result;
1789}
1790
1791bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001792ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001793{
1794 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001795 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001796 DoOperation(&op);
1797 return result;
1798}
1799
1800bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001801ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001802{
1803 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001804 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001805 DoOperation(&op);
1806 return result;
1807}
1808
1809bool
1810ProcessMonitor::BringProcessIntoLimbo()
1811{
1812 bool result;
1813 KillOperation op(result);
1814 DoOperation(&op);
1815 return result;
1816}
1817
1818bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00001819ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001820{
1821 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001822 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001823 DoOperation(&op);
1824 return result;
1825}
1826
1827bool
1828ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1829{
1830 bool result;
1831 EventMessageOperation op(tid, message, result);
1832 DoOperation(&op);
1833 return result;
1834}
1835
Greg Clayton743ecf42012-10-16 20:20:18 +00001836lldb_private::Error
Stephen Wilson84ffe702011-03-30 15:55:52 +00001837ProcessMonitor::Detach()
1838{
Greg Clayton28041352011-11-29 20:50:10 +00001839 lldb_private::Error error;
Greg Clayton743ecf42012-10-16 20:20:18 +00001840 if (m_pid != LLDB_INVALID_PROCESS_ID) {
1841 DetachOperation op(error);
1842 DoOperation(&op);
1843 }
Greg Clayton743ecf42012-10-16 20:20:18 +00001844 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00001845}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001846
1847bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001848ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1849{
Peter Collingbourne62343202011-06-14 03:55:54 +00001850 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001851
1852 if (target_fd == -1)
1853 return false;
1854
Peter Collingbourne62343202011-06-14 03:55:54 +00001855 return (dup2(target_fd, fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001856}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001857
1858void
1859ProcessMonitor::StopMonitoringChildProcess()
1860{
1861 lldb::thread_result_t thread_result;
1862
Stephen Wilsond4182f42011-02-09 20:10:35 +00001863 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001864 {
1865 Host::ThreadCancel(m_monitor_thread, NULL);
1866 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1867 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1868 }
1869}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001870
1871void
1872ProcessMonitor::StopMonitor()
1873{
1874 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00001875 StopOpThread();
Stephen Wilson84ffe702011-03-30 15:55:52 +00001876 CloseFD(m_terminal_fd);
1877 CloseFD(m_client_fd);
1878 CloseFD(m_server_fd);
1879}
1880
1881void
Greg Clayton743ecf42012-10-16 20:20:18 +00001882ProcessMonitor::StopOpThread()
1883{
1884 lldb::thread_result_t result;
1885
1886 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1887 return;
1888
1889 Host::ThreadCancel(m_operation_thread, NULL);
1890 Host::ThreadJoin(m_operation_thread, &result, NULL);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001891 m_operation_thread = LLDB_INVALID_HOST_THREAD;
Greg Clayton743ecf42012-10-16 20:20:18 +00001892}
1893
1894void
Stephen Wilson84ffe702011-03-30 15:55:52 +00001895ProcessMonitor::CloseFD(int &fd)
1896{
1897 if (fd != -1)
1898 {
1899 close(fd);
1900 fd = -1;
1901 }
1902}