blob: 9f661cd3b3bf98df89699250cd47a2e0fdc7f066 [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
10// C Includes
11#include <errno.h>
12#include <poll.h>
13#include <string.h>
14#include <unistd.h>
15#include <sys/ptrace.h>
16#include <sys/socket.h>
17#include <sys/types.h>
Benjamin Kramerc2b5c672012-04-07 09:13:49 +000018#include <sys/user.h>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000019#include <sys/wait.h>
20
21// C++ Includes
22// Other libraries and framework includes
Johnny Chen0d5f2d42011-10-18 18:09:30 +000023#include "lldb/Core/Debugger.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000024#include "lldb/Core/Error.h"
Johnny Chen13e8e1c2011-05-13 21:29:50 +000025#include "lldb/Core/RegisterValue.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000026#include "lldb/Core/Scalar.h"
27#include "lldb/Host/Host.h"
28#include "lldb/Target/Thread.h"
29#include "lldb/Target/RegisterContext.h"
30#include "lldb/Utility/PseudoTerminal.h"
31
Johnny Chen30213ff2012-01-05 19:17:38 +000032#include "POSIXThread.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000033#include "ProcessLinux.h"
Johnny Chen30213ff2012-01-05 19:17:38 +000034#include "ProcessPOSIXLog.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000035#include "ProcessMonitor.h"
36
37
Greg Clayton386ff182011-11-05 01:09:16 +000038#define DEBUG_PTRACE_MAXBYTES 20
39
Stephen Wilsone6f9f662010-07-24 02:19:04 +000040using namespace lldb_private;
41
Johnny Chen0d5f2d42011-10-18 18:09:30 +000042// FIXME: this code is host-dependent with respect to types and
43// endianness and needs to be fixed. For example, lldb::addr_t is
44// hard-coded to uint64_t, but on a 32-bit Linux host, ptrace requires
45// 32-bit pointer arguments. This code uses casts to work around the
46// problem.
47
48// We disable the tracing of ptrace calls for integration builds to
49// avoid the additional indirection and checks.
50#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
51
Greg Clayton386ff182011-11-05 01:09:16 +000052static void
53DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
54{
55 uint8_t *ptr = (uint8_t *)bytes;
56 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
57 for(uint32_t i=0; i<loop_count; i++)
58 {
59 s.Printf ("[%x]", *ptr);
60 ptr++;
61 }
62}
63
64static void PtraceDisplayBytes(__ptrace_request &req, void *data)
65{
66 StreamString buf;
Johnny Chen30213ff2012-01-05 19:17:38 +000067 LogSP verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
68 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
Greg Clayton386ff182011-11-05 01:09:16 +000069
70 if (verbose_log)
71 {
72 switch(req)
73 {
74 case PTRACE_POKETEXT:
75 {
76 DisplayBytes(buf, &data, 8);
77 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
78 break;
79 }
Greg Clayton542e4072012-09-07 17:49:29 +000080 case PTRACE_POKEDATA:
Greg Clayton386ff182011-11-05 01:09:16 +000081 {
82 DisplayBytes(buf, &data, 8);
83 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
84 break;
85 }
Greg Clayton542e4072012-09-07 17:49:29 +000086 case PTRACE_POKEUSER:
Greg Clayton386ff182011-11-05 01:09:16 +000087 {
88 DisplayBytes(buf, &data, 8);
89 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
90 break;
91 }
Greg Clayton542e4072012-09-07 17:49:29 +000092 case PTRACE_SETREGS:
Greg Clayton386ff182011-11-05 01:09:16 +000093 {
94 DisplayBytes(buf, data, sizeof(user_regs_struct));
95 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
96 break;
97 }
98 case PTRACE_SETFPREGS:
99 {
100 DisplayBytes(buf, data, sizeof(user_fpregs_struct));
101 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
102 break;
103 }
Greg Clayton542e4072012-09-07 17:49:29 +0000104 case PTRACE_SETSIGINFO:
Greg Clayton386ff182011-11-05 01:09:16 +0000105 {
106 DisplayBytes(buf, data, sizeof(siginfo_t));
107 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
108 break;
109 }
110 default:
111 {
112 }
113 }
114 }
115}
116
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000117// Wrapper for ptrace to catch errors and log calls.
118extern long
119PtraceWrapper(__ptrace_request req, pid_t pid, void *addr, void *data,
120 const char* reqName, const char* file, int line)
121{
Greg Clayton386ff182011-11-05 01:09:16 +0000122 long int result;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000123
Johnny Chen30213ff2012-01-05 19:17:38 +0000124 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
Greg Clayton386ff182011-11-05 01:09:16 +0000125
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000126 if (log)
127 log->Printf("ptrace(%s, %u, %p, %p) called from file %s line %d",
128 reqName, pid, addr, data, file, line);
Greg Clayton542e4072012-09-07 17:49:29 +0000129
Greg Clayton386ff182011-11-05 01:09:16 +0000130 PtraceDisplayBytes(req, data);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000131
132 errno = 0;
133 result = ptrace(req, pid, addr, data);
134
Greg Clayton386ff182011-11-05 01:09:16 +0000135 PtraceDisplayBytes(req, data);
136
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000137 if (log && (result == -1 || errno != 0))
138 {
139 const char* str;
140 switch (errno)
141 {
142 case ESRCH: str = "ESRCH"; break;
143 case EINVAL: str = "EINVAL"; break;
144 case EBUSY: str = "EBUSY"; break;
145 case EPERM: str = "EPERM"; break;
146 default: str = "<unknown>";
147 }
148 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
149 }
150
151 return result;
152}
153
154#define PTRACE(req, pid, addr, data) \
155 PtraceWrapper((req), (pid), (addr), (data), #req, __FILE__, __LINE__)
156#else
157#define PTRACE ptrace
158#endif
159
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000160//------------------------------------------------------------------------------
161// Static implementations of ProcessMonitor::ReadMemory and
162// ProcessMonitor::WriteMemory. This enables mutual recursion between these
163// functions without needed to go thru the thread funnel.
164
165static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000166DoReadMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000167 lldb::addr_t vm_addr, void *buf, size_t size, Error &error)
168{
Greg Clayton542e4072012-09-07 17:49:29 +0000169 // ptrace word size is determined by the host, not the child
170 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000171 unsigned char *dst = static_cast<unsigned char*>(buf);
172 size_t bytes_read;
173 size_t remainder;
174 long data;
175
Johnny Chen30213ff2012-01-05 19:17:38 +0000176 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000177 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000178 ProcessPOSIXLog::IncNestLevel();
179 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000180 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000181 pid, word_size, (void*)vm_addr, buf, size);
182
183 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000184 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
185 {
186 errno = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000187 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, NULL);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000188 if (data == -1L && errno)
189 {
190 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000191 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000192 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000193 return bytes_read;
194 }
195
196 remainder = size - bytes_read;
197 remainder = remainder > word_size ? word_size : remainder;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000198
199 // Copy the data into our buffer
200 if (log)
201 memset(dst, 0, sizeof(dst));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000202 for (unsigned i = 0; i < remainder; ++i)
203 dst[i] = ((data >> i*8) & 0xFF);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000204
Johnny Chen30213ff2012-01-05 19:17:38 +0000205 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
206 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
207 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
208 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000209 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
210 (void*)vm_addr, *(unsigned long*)dst, (unsigned long)data);
211
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000212 vm_addr += word_size;
213 dst += word_size;
214 }
215
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000216 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000217 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000218 return bytes_read;
219}
220
221static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000222DoWriteMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000223 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
224{
Greg Clayton542e4072012-09-07 17:49:29 +0000225 // ptrace word size is determined by the host, not the child
226 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000227 const unsigned char *src = static_cast<const unsigned char*>(buf);
228 size_t bytes_written = 0;
229 size_t remainder;
230
Johnny Chen30213ff2012-01-05 19:17:38 +0000231 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000232 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000233 ProcessPOSIXLog::IncNestLevel();
234 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000235 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000236 pid, word_size, (void*)vm_addr, buf, size);
237
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000238 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
239 {
240 remainder = size - bytes_written;
241 remainder = remainder > word_size ? word_size : remainder;
242
243 if (remainder == word_size)
244 {
245 unsigned long data = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000246 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000247 for (unsigned i = 0; i < word_size; ++i)
248 data |= (unsigned long)src[i] << i*8;
249
Johnny Chen30213ff2012-01-05 19:17:38 +0000250 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
251 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
252 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
253 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000254 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
255 (void*)vm_addr, *(unsigned long*)src, data);
256
257 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000258 {
259 error.SetErrorToErrno();
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_written;
263 }
264 }
265 else
266 {
267 unsigned char buff[8];
Greg Clayton542e4072012-09-07 17:49:29 +0000268 if (DoReadMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000269 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000270 {
271 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000272 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000273 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000274 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000275
276 memcpy(buff, src, remainder);
277
Greg Clayton542e4072012-09-07 17:49:29 +0000278 if (DoWriteMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000279 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000280 {
281 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000282 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000283 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000284 }
285
Johnny Chen30213ff2012-01-05 19:17:38 +0000286 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
287 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
288 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
289 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000290 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
291 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000292 }
293
294 vm_addr += word_size;
295 src += word_size;
296 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000297 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000298 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000299 return bytes_written;
300}
301
Stephen Wilson26977162011-03-23 02:14:42 +0000302// Simple helper function to ensure flags are enabled on the given file
303// descriptor.
304static bool
305EnsureFDFlags(int fd, int flags, Error &error)
306{
307 int status;
308
309 if ((status = fcntl(fd, F_GETFL)) == -1)
310 {
311 error.SetErrorToErrno();
312 return false;
313 }
314
315 if (fcntl(fd, F_SETFL, status | flags) == -1)
316 {
317 error.SetErrorToErrno();
318 return false;
319 }
320
321 return true;
322}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000323
324//------------------------------------------------------------------------------
325/// @class Operation
326/// @brief Represents a ProcessMonitor operation.
327///
328/// Under Linux, it is not possible to ptrace() from any other thread but the
329/// one that spawned or attached to the process from the start. Therefore, when
330/// a ProcessMonitor is asked to deliver or change the state of an inferior
331/// process the operation must be "funneled" to a specific thread to perform the
332/// task. The Operation class provides an abstract base for all services the
333/// ProcessMonitor must perform via the single virtual function Execute, thus
334/// encapsulating the code that needs to run in the privileged context.
335class Operation
336{
337public:
338 virtual void Execute(ProcessMonitor *monitor) = 0;
339};
340
341//------------------------------------------------------------------------------
342/// @class ReadOperation
343/// @brief Implements ProcessMonitor::ReadMemory.
344class ReadOperation : public Operation
345{
346public:
347 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
348 Error &error, size_t &result)
349 : m_addr(addr), m_buff(buff), m_size(size),
350 m_error(error), m_result(result)
351 { }
352
353 void Execute(ProcessMonitor *monitor);
354
355private:
356 lldb::addr_t m_addr;
357 void *m_buff;
358 size_t m_size;
359 Error &m_error;
360 size_t &m_result;
361};
362
363void
364ReadOperation::Execute(ProcessMonitor *monitor)
365{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000366 lldb::pid_t pid = monitor->GetPID();
367
Greg Clayton542e4072012-09-07 17:49:29 +0000368 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000369}
370
371//------------------------------------------------------------------------------
372/// @class ReadOperation
373/// @brief Implements ProcessMonitor::WriteMemory.
374class WriteOperation : public Operation
375{
376public:
377 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
378 Error &error, size_t &result)
379 : m_addr(addr), m_buff(buff), m_size(size),
380 m_error(error), m_result(result)
381 { }
382
383 void Execute(ProcessMonitor *monitor);
384
385private:
386 lldb::addr_t m_addr;
387 const void *m_buff;
388 size_t m_size;
389 Error &m_error;
390 size_t &m_result;
391};
392
393void
394WriteOperation::Execute(ProcessMonitor *monitor)
395{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000396 lldb::pid_t pid = monitor->GetPID();
397
Greg Clayton542e4072012-09-07 17:49:29 +0000398 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000399}
400
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000401
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000402//------------------------------------------------------------------------------
403/// @class ReadRegOperation
404/// @brief Implements ProcessMonitor::ReadRegisterValue.
405class ReadRegOperation : public Operation
406{
407public:
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000408 ReadRegOperation(unsigned offset, RegisterValue &value, bool &result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000409 : m_offset(offset), m_value(value), m_result(result)
410 { }
411
412 void Execute(ProcessMonitor *monitor);
413
414private:
415 unsigned m_offset;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000416 RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000417 bool &m_result;
418};
419
420void
421ReadRegOperation::Execute(ProcessMonitor *monitor)
422{
423 lldb::pid_t pid = monitor->GetPID();
Johnny Chen30213ff2012-01-05 19:17:38 +0000424 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000425
426 // Set errno to zero so that we can detect a failed peek.
427 errno = 0;
Greg Clayton386ff182011-11-05 01:09:16 +0000428 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, pid, (void*)m_offset, NULL);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000429 if (data == -1UL && errno)
430 m_result = false;
431 else
432 {
433 m_value = data;
434 m_result = true;
435 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000436 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000437 log->Printf ("ProcessMonitor::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
Johnny Chen30213ff2012-01-05 19:17:38 +0000438 POSIXThread::GetRegisterNameFromOffset(m_offset), data);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000439}
440
441//------------------------------------------------------------------------------
442/// @class WriteRegOperation
443/// @brief Implements ProcessMonitor::WriteRegisterValue.
444class WriteRegOperation : public Operation
445{
446public:
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000447 WriteRegOperation(unsigned offset, const RegisterValue &value, bool &result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000448 : m_offset(offset), m_value(value), m_result(result)
449 { }
450
451 void Execute(ProcessMonitor *monitor);
452
453private:
454 unsigned m_offset;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000455 const RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000456 bool &m_result;
457};
458
459void
460WriteRegOperation::Execute(ProcessMonitor *monitor)
461{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000462 void* buf;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000463 lldb::pid_t pid = monitor->GetPID();
Johnny Chen30213ff2012-01-05 19:17:38 +0000464 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000465
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000466 if (sizeof(void*) == sizeof(uint64_t))
467 buf = (void*) m_value.GetAsUInt64();
468 else
469 {
470 assert(sizeof(void*) == sizeof(uint32_t));
471 buf = (void*) m_value.GetAsUInt32();
472 }
473
474 if (log)
475 log->Printf ("ProcessMonitor::%s() reg %s: %p", __FUNCTION__,
Johnny Chen30213ff2012-01-05 19:17:38 +0000476 POSIXThread::GetRegisterNameFromOffset(m_offset), buf);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000477 if (PTRACE(PTRACE_POKEUSER, pid, (void*)m_offset, buf))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000478 m_result = false;
479 else
480 m_result = true;
481}
482
483//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000484/// @class ReadGPROperation
485/// @brief Implements ProcessMonitor::ReadGPR.
486class ReadGPROperation : public Operation
487{
488public:
489 ReadGPROperation(void *buf, bool &result)
490 : m_buf(buf), m_result(result)
491 { }
492
493 void Execute(ProcessMonitor *monitor);
494
495private:
496 void *m_buf;
497 bool &m_result;
498};
499
500void
501ReadGPROperation::Execute(ProcessMonitor *monitor)
502{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000503 if (PTRACE(PTRACE_GETREGS, monitor->GetPID(), NULL, m_buf) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000504 m_result = false;
505 else
506 m_result = true;
507}
508
509//------------------------------------------------------------------------------
510/// @class ReadFPROperation
511/// @brief Implements ProcessMonitor::ReadFPR.
512class ReadFPROperation : public Operation
513{
514public:
515 ReadFPROperation(void *buf, bool &result)
516 : m_buf(buf), m_result(result)
517 { }
518
519 void Execute(ProcessMonitor *monitor);
520
521private:
522 void *m_buf;
523 bool &m_result;
524};
525
526void
527ReadFPROperation::Execute(ProcessMonitor *monitor)
528{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000529 if (PTRACE(PTRACE_GETFPREGS, monitor->GetPID(), NULL, m_buf) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000530 m_result = false;
531 else
532 m_result = true;
533}
534
535//------------------------------------------------------------------------------
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000536/// @class WriteGPROperation
537/// @brief Implements ProcessMonitor::WriteGPR.
538class WriteGPROperation : public Operation
539{
540public:
541 WriteGPROperation(void *buf, bool &result)
542 : m_buf(buf), m_result(result)
543 { }
544
545 void Execute(ProcessMonitor *monitor);
546
547private:
548 void *m_buf;
549 bool &m_result;
550};
551
552void
553WriteGPROperation::Execute(ProcessMonitor *monitor)
554{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000555 if (PTRACE(PTRACE_SETREGS, monitor->GetPID(), NULL, m_buf) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000556 m_result = false;
557 else
558 m_result = true;
559}
560
561//------------------------------------------------------------------------------
562/// @class WriteFPROperation
563/// @brief Implements ProcessMonitor::WriteFPR.
564class WriteFPROperation : public Operation
565{
566public:
567 WriteFPROperation(void *buf, bool &result)
568 : m_buf(buf), m_result(result)
569 { }
570
571 void Execute(ProcessMonitor *monitor);
572
573private:
574 void *m_buf;
575 bool &m_result;
576};
577
578void
579WriteFPROperation::Execute(ProcessMonitor *monitor)
580{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000581 if (PTRACE(PTRACE_SETFPREGS, monitor->GetPID(), NULL, m_buf) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000582 m_result = false;
583 else
584 m_result = true;
585}
586
587//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000588/// @class ResumeOperation
589/// @brief Implements ProcessMonitor::Resume.
590class ResumeOperation : public Operation
591{
592public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000593 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
594 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000595
596 void Execute(ProcessMonitor *monitor);
597
598private:
599 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000600 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000601 bool &m_result;
602};
603
604void
605ResumeOperation::Execute(ProcessMonitor *monitor)
606{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000607 int data = 0;
608
609 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
610 data = m_signo;
611
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000612 if (PTRACE(PTRACE_CONT, m_tid, NULL, (void*)data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000613 m_result = false;
614 else
615 m_result = true;
616}
617
618//------------------------------------------------------------------------------
619/// @class ResumeOperation
620/// @brief Implements ProcessMonitor::SingleStep.
621class SingleStepOperation : public Operation
622{
623public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000624 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
625 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000626
627 void Execute(ProcessMonitor *monitor);
628
629private:
630 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000631 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000632 bool &m_result;
633};
634
635void
636SingleStepOperation::Execute(ProcessMonitor *monitor)
637{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000638 int data = 0;
639
640 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
641 data = m_signo;
642
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000643 if (PTRACE(PTRACE_SINGLESTEP, m_tid, NULL, (void*)data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000644 m_result = false;
645 else
646 m_result = true;
647}
648
649//------------------------------------------------------------------------------
650/// @class SiginfoOperation
651/// @brief Implements ProcessMonitor::GetSignalInfo.
652class SiginfoOperation : public Operation
653{
654public:
Daniel Maleaa35970a2012-11-23 18:09:58 +0000655 SiginfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
656 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000657
658 void Execute(ProcessMonitor *monitor);
659
660private:
661 lldb::tid_t m_tid;
662 void *m_info;
663 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000664 int &m_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000665};
666
667void
668SiginfoOperation::Execute(ProcessMonitor *monitor)
669{
Daniel Maleaa35970a2012-11-23 18:09:58 +0000670 if (PTRACE(PTRACE_GETSIGINFO, m_tid, NULL, m_info)) {
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000671 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000672 m_err = errno;
673 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000674 else
675 m_result = true;
676}
677
678//------------------------------------------------------------------------------
679/// @class EventMessageOperation
680/// @brief Implements ProcessMonitor::GetEventMessage.
681class EventMessageOperation : public Operation
682{
683public:
684 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
685 : m_tid(tid), m_message(message), m_result(result) { }
686
687 void Execute(ProcessMonitor *monitor);
688
689private:
690 lldb::tid_t m_tid;
691 unsigned long *m_message;
692 bool &m_result;
693};
694
695void
696EventMessageOperation::Execute(ProcessMonitor *monitor)
697{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000698 if (PTRACE(PTRACE_GETEVENTMSG, m_tid, NULL, m_message))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000699 m_result = false;
700 else
701 m_result = true;
702}
703
704//------------------------------------------------------------------------------
705/// @class KillOperation
706/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
707class KillOperation : public Operation
708{
709public:
710 KillOperation(bool &result) : m_result(result) { }
711
712 void Execute(ProcessMonitor *monitor);
713
714private:
715 bool &m_result;
716};
717
718void
719KillOperation::Execute(ProcessMonitor *monitor)
720{
721 lldb::pid_t pid = monitor->GetPID();
722
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000723 if (PTRACE(PTRACE_KILL, pid, NULL, NULL))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000724 m_result = false;
725 else
726 m_result = true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000727}
728
Greg Clayton28041352011-11-29 20:50:10 +0000729//------------------------------------------------------------------------------
730/// @class KillOperation
731/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
732class DetachOperation : public Operation
733{
734public:
735 DetachOperation(Error &result) : m_error(result) { }
736
737 void Execute(ProcessMonitor *monitor);
738
739private:
740 Error &m_error;
741};
742
743void
744DetachOperation::Execute(ProcessMonitor *monitor)
745{
746 lldb::pid_t pid = monitor->GetPID();
747
748 if (ptrace(PT_DETACH, pid, NULL, 0) < 0)
749 m_error.SetErrorToErrno();
Greg Clayton542e4072012-09-07 17:49:29 +0000750
Greg Clayton28041352011-11-29 20:50:10 +0000751}
752
Johnny Chen25e68e32011-06-14 19:19:50 +0000753ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
754 : m_monitor(monitor)
755{
756 sem_init(&m_semaphore, 0, 0);
757}
758
759ProcessMonitor::OperationArgs::~OperationArgs()
760{
761 sem_destroy(&m_semaphore);
762}
763
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000764ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
765 lldb_private::Module *module,
766 char const **argv,
767 char const **envp,
768 const char *stdin_path,
769 const char *stdout_path,
770 const char *stderr_path)
Johnny Chen25e68e32011-06-14 19:19:50 +0000771 : OperationArgs(monitor),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000772 m_module(module),
773 m_argv(argv),
774 m_envp(envp),
775 m_stdin_path(stdin_path),
776 m_stdout_path(stdout_path),
Johnny Chen25e68e32011-06-14 19:19:50 +0000777 m_stderr_path(stderr_path) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000778
779ProcessMonitor::LaunchArgs::~LaunchArgs()
Johnny Chen25e68e32011-06-14 19:19:50 +0000780{ }
781
782ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
783 lldb::pid_t pid)
784 : OperationArgs(monitor), m_pid(pid) { }
785
786ProcessMonitor::AttachArgs::~AttachArgs()
787{ }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000788
789//------------------------------------------------------------------------------
790/// The basic design of the ProcessMonitor is built around two threads.
791///
792/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
793/// for changes in the debugee state. When a change is detected a
794/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
795/// "drives" state changes in the debugger.
796///
797/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000798/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000799/// operations such as register reads/writes, stepping, etc. See the comments
800/// on the Operation class for more info as to why this is needed.
Johnny Chen30213ff2012-01-05 19:17:38 +0000801ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000802 Module *module,
803 const char *argv[],
804 const char *envp[],
805 const char *stdin_path,
806 const char *stdout_path,
807 const char *stderr_path,
808 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000809 : m_process(static_cast<ProcessLinux *>(process)),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000810 m_operation_thread(LLDB_INVALID_HOST_THREAD),
811 m_pid(LLDB_INVALID_PROCESS_ID),
812 m_terminal_fd(-1),
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000813 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000814 m_client_fd(-1),
815 m_server_fd(-1)
816{
Stephen Wilson57740ec2011-01-15 00:12:41 +0000817 std::auto_ptr<LaunchArgs> args;
818
819 args.reset(new LaunchArgs(this, module, argv, envp,
820 stdin_path, stdout_path, stderr_path));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000821
822 // Server/client descriptors.
823 if (!EnableIPC())
824 {
825 error.SetErrorToGenericError();
826 error.SetErrorString("Monitor failed to initialize.");
827 }
828
Johnny Chen25e68e32011-06-14 19:19:50 +0000829 StartLaunchOpThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000830 if (!error.Success())
831 return;
832
833WAIT_AGAIN:
834 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000835 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000836 {
837 if (errno == EINTR)
838 goto WAIT_AGAIN;
839 else
840 {
841 error.SetErrorToErrno();
842 return;
843 }
844 }
845
846 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000847 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000848 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000849 StopOpThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000850 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000851 return;
852 }
853
854 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000855 m_monitor_thread = Host::StartMonitoringChildProcess(
856 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Stephen Wilsond4182f42011-02-09 20:10:35 +0000857 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000858 {
859 error.SetErrorToGenericError();
860 error.SetErrorString("Process launch failed.");
861 return;
862 }
863}
864
Johnny Chen30213ff2012-01-05 19:17:38 +0000865ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen25e68e32011-06-14 19:19:50 +0000866 lldb::pid_t pid,
867 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000868 : m_process(static_cast<ProcessLinux *>(process)),
Johnny Chen25e68e32011-06-14 19:19:50 +0000869 m_operation_thread(LLDB_INVALID_HOST_THREAD),
870 m_pid(LLDB_INVALID_PROCESS_ID),
871 m_terminal_fd(-1),
872 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
873 m_client_fd(-1),
874 m_server_fd(-1)
875{
876 std::auto_ptr<AttachArgs> args;
877
878 args.reset(new AttachArgs(this, pid));
879
880 // Server/client descriptors.
881 if (!EnableIPC())
882 {
883 error.SetErrorToGenericError();
884 error.SetErrorString("Monitor failed to initialize.");
885 }
886
887 StartAttachOpThread(args.get(), error);
888 if (!error.Success())
889 return;
890
891WAIT_AGAIN:
892 // Wait for the operation thread to initialize.
893 if (sem_wait(&args->m_semaphore))
894 {
895 if (errno == EINTR)
896 goto WAIT_AGAIN;
897 else
898 {
899 error.SetErrorToErrno();
900 return;
901 }
902 }
903
Greg Clayton743ecf42012-10-16 20:20:18 +0000904 // Check that the attach was a success.
Johnny Chen25e68e32011-06-14 19:19:50 +0000905 if (!args->m_error.Success())
906 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000907 StopOpThread();
Johnny Chen25e68e32011-06-14 19:19:50 +0000908 error = args->m_error;
909 return;
910 }
911
912 // Finally, start monitoring the child process for change in state.
913 m_monitor_thread = Host::StartMonitoringChildProcess(
914 ProcessMonitor::MonitorCallback, this, GetPID(), true);
915 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
916 {
917 error.SetErrorToGenericError();
918 error.SetErrorString("Process attach failed.");
919 return;
920 }
921}
922
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000923ProcessMonitor::~ProcessMonitor()
924{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000925 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000926}
927
928//------------------------------------------------------------------------------
929// Thread setup and tear down.
930void
Johnny Chen25e68e32011-06-14 19:19:50 +0000931ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000932{
933 static const char *g_thread_name = "lldb.process.linux.operation";
934
Stephen Wilsond4182f42011-02-09 20:10:35 +0000935 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000936 return;
937
938 m_operation_thread =
Johnny Chen25e68e32011-06-14 19:19:50 +0000939 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000940}
941
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000942void *
Johnny Chen25e68e32011-06-14 19:19:50 +0000943ProcessMonitor::LaunchOpThread(void *arg)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000944{
945 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
946
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +0000947 if (!Launch(args)) {
948 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000949 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +0000950 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000951
Stephen Wilson570243b2011-01-19 01:37:06 +0000952 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000953 return NULL;
954}
955
956bool
957ProcessMonitor::Launch(LaunchArgs *args)
958{
959 ProcessMonitor *monitor = args->m_monitor;
960 ProcessLinux &process = monitor->GetProcess();
961 const char **argv = args->m_argv;
962 const char **envp = args->m_envp;
963 const char *stdin_path = args->m_stdin_path;
964 const char *stdout_path = args->m_stdout_path;
965 const char *stderr_path = args->m_stderr_path;
966
967 lldb_utility::PseudoTerminal terminal;
968 const size_t err_len = 1024;
969 char err_str[err_len];
970 lldb::pid_t pid;
971
972 lldb::ThreadSP inferior;
Johnny Chen30213ff2012-01-05 19:17:38 +0000973 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000974
Stephen Wilson57740ec2011-01-15 00:12:41 +0000975 // Propagate the environment if one is not supplied.
976 if (envp == NULL || envp[0] == NULL)
977 envp = const_cast<const char **>(environ);
978
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000979 // Pseudo terminal setup.
980 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
981 {
982 args->m_error.SetErrorToGenericError();
983 args->m_error.SetErrorString("Could not open controlling TTY.");
984 goto FINISH;
985 }
986
987 if ((pid = terminal.Fork(err_str, err_len)) < 0)
988 {
989 args->m_error.SetErrorToGenericError();
990 args->m_error.SetErrorString("Process fork failed.");
991 goto FINISH;
992 }
993
Peter Collingbourne6a520222011-06-14 03:55:58 +0000994 // Recognized child exit status codes.
995 enum {
996 ePtraceFailed = 1,
997 eDupStdinFailed,
998 eDupStdoutFailed,
999 eDupStderrFailed,
1000 eExecFailed
1001 };
1002
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001003 // Child process.
1004 if (pid == 0)
1005 {
1006 // Trace this process.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001007 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL) < 0)
Peter Collingbourne6a520222011-06-14 03:55:58 +00001008 exit(ePtraceFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001009
1010 // Do not inherit setgid powers.
1011 setgid(getgid());
1012
1013 // Let us have our own process group.
1014 setpgid(0, 0);
1015
Greg Clayton710dd5a2011-01-08 20:28:42 +00001016 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001017 //
1018 // FIXME: If two or more of the paths are the same we needlessly open
1019 // the same file multiple times.
1020 if (stdin_path != NULL && stdin_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001021 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001022 exit(eDupStdinFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001023
1024 if (stdout_path != NULL && stdout_path[0])
1025 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001026 exit(eDupStdoutFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001027
1028 if (stderr_path != NULL && stderr_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001029 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001030 exit(eDupStderrFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001031
1032 // Execute. We should never return.
1033 execve(argv[0],
1034 const_cast<char *const *>(argv),
1035 const_cast<char *const *>(envp));
Peter Collingbourne6a520222011-06-14 03:55:58 +00001036 exit(eExecFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001037 }
1038
1039 // Wait for the child process to to trap on its call to execve.
Peter Collingbourne6a520222011-06-14 03:55:58 +00001040 pid_t wpid;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001041 int status;
Peter Collingbourne6a520222011-06-14 03:55:58 +00001042 if ((wpid = waitpid(pid, &status, 0)) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001043 {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001044 args->m_error.SetErrorToErrno();
1045 goto FINISH;
1046 }
Peter Collingbourne6a520222011-06-14 03:55:58 +00001047 else if (WIFEXITED(status))
1048 {
1049 // open, dup or execve likely failed for some reason.
1050 args->m_error.SetErrorToGenericError();
1051 switch (WEXITSTATUS(status))
1052 {
Greg Clayton542e4072012-09-07 17:49:29 +00001053 case ePtraceFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001054 args->m_error.SetErrorString("Child ptrace failed.");
1055 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001056 case eDupStdinFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001057 args->m_error.SetErrorString("Child open stdin failed.");
1058 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001059 case eDupStdoutFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001060 args->m_error.SetErrorString("Child open stdout failed.");
1061 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001062 case eDupStderrFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001063 args->m_error.SetErrorString("Child open stderr failed.");
1064 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001065 case eExecFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001066 args->m_error.SetErrorString("Child exec failed.");
1067 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001068 default:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001069 args->m_error.SetErrorString("Child returned unknown exit status.");
1070 break;
1071 }
1072 goto FINISH;
1073 }
1074 assert(WIFSTOPPED(status) && wpid == pid &&
1075 "Could not sync with inferior process.");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001076
1077 // Have the child raise an event on exit. This is used to keep the child in
1078 // limbo until it is destroyed.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001079 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)PTRACE_O_TRACEEXIT) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001080 {
1081 args->m_error.SetErrorToErrno();
1082 goto FINISH;
1083 }
1084
1085 // Release the master terminal descriptor and pass it off to the
1086 // ProcessMonitor instance. Similarly stash the inferior pid.
1087 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1088 monitor->m_pid = pid;
1089
Stephen Wilson26977162011-03-23 02:14:42 +00001090 // Set the terminal fd to be in non blocking mode (it simplifies the
1091 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1092 // descriptor to read from).
1093 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1094 goto FINISH;
1095
Johnny Chen30213ff2012-01-05 19:17:38 +00001096 // Update the process thread list with this new thread.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001097 // FIXME: should we be letting UpdateThreadList handle this?
1098 // FIXME: by using pids instead of tids, we can only support one thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001099 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001100 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001101 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001102 process.GetThreadList().AddThread(inferior);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001103
1104 // Let our process instance know the thread has stopped.
1105 process.SendMessage(ProcessMessage::Trace(pid));
1106
1107FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001108 return args->m_error.Success();
1109}
1110
1111bool
1112ProcessMonitor::EnableIPC()
1113{
1114 int fd[2];
1115
1116 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
1117 return false;
1118
1119 m_client_fd = fd[0];
1120 m_server_fd = fd[1];
1121 return true;
1122}
1123
Johnny Chen25e68e32011-06-14 19:19:50 +00001124void
1125ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1126{
1127 static const char *g_thread_name = "lldb.process.linux.operation";
1128
1129 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1130 return;
1131
1132 m_operation_thread =
1133 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1134}
1135
Johnny Chen25e68e32011-06-14 19:19:50 +00001136void *
1137ProcessMonitor::AttachOpThread(void *arg)
1138{
1139 AttachArgs *args = static_cast<AttachArgs*>(arg);
1140
Greg Clayton743ecf42012-10-16 20:20:18 +00001141 if (!Attach(args)) {
1142 sem_post(&args->m_semaphore);
Johnny Chen25e68e32011-06-14 19:19:50 +00001143 return NULL;
Greg Clayton743ecf42012-10-16 20:20:18 +00001144 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001145
1146 ServeOperation(args);
1147 return NULL;
1148}
1149
1150bool
1151ProcessMonitor::Attach(AttachArgs *args)
1152{
1153 lldb::pid_t pid = args->m_pid;
1154
1155 ProcessMonitor *monitor = args->m_monitor;
1156 ProcessLinux &process = monitor->GetProcess();
Johnny Chen25e68e32011-06-14 19:19:50 +00001157 lldb::ThreadSP inferior;
Johnny Chen30213ff2012-01-05 19:17:38 +00001158 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen25e68e32011-06-14 19:19:50 +00001159
1160 if (pid <= 1)
1161 {
1162 args->m_error.SetErrorToGenericError();
1163 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1164 goto FINISH;
1165 }
1166
1167 // Attach to the requested process.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001168 if (PTRACE(PTRACE_ATTACH, pid, NULL, NULL) < 0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001169 {
1170 args->m_error.SetErrorToErrno();
1171 goto FINISH;
1172 }
1173
1174 int status;
1175 if ((status = waitpid(pid, NULL, 0)) < 0)
1176 {
1177 args->m_error.SetErrorToErrno();
1178 goto FINISH;
1179 }
1180
Greg Clayton926cce72012-10-12 16:10:12 +00001181 monitor->m_pid = pid;
1182
Johnny Chen30213ff2012-01-05 19:17:38 +00001183 // Update the process thread list with the attached thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001184 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001185 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001186 log->Printf ("ProcessMonitor::%s() adding tid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen25e68e32011-06-14 19:19:50 +00001187 process.GetThreadList().AddThread(inferior);
Johnny Chen25e68e32011-06-14 19:19:50 +00001188
1189 // Let our process instance know the thread has stopped.
1190 process.SendMessage(ProcessMessage::Trace(pid));
1191
1192 FINISH:
1193 return args->m_error.Success();
1194}
1195
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001196bool
1197ProcessMonitor::MonitorCallback(void *callback_baton,
1198 lldb::pid_t pid,
Peter Collingbourne2c67b9a2011-11-21 00:10:19 +00001199 bool exited,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001200 int signal,
1201 int status)
1202{
1203 ProcessMessage message;
1204 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
1205 ProcessLinux *process = monitor->m_process;
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001206 assert(process);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001207 bool stop_monitoring;
1208 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001209 int ptrace_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001210
Daniel Maleaa35970a2012-11-23 18:09:58 +00001211 if (!monitor->GetSignalInfo(pid, &info, ptrace_err)) {
1212 if (ptrace_err == EINVAL) {
1213 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1214 if (!monitor->Resume(pid, SIGSTOP)) {
1215 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1216 }
1217 stop_monitoring = false;
1218 } else {
1219 // ptrace(GETSIGINFO) failed (but not due to group-stop). Most likely,
1220 // this means the child pid is gone (or not being debugged) therefore
1221 // stop the monitor thread.
1222 stop_monitoring = true;
1223 }
1224 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00001225 else {
1226 switch (info.si_signo)
1227 {
1228 case SIGTRAP:
1229 message = MonitorSIGTRAP(monitor, &info, pid);
1230 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001231
Stephen Wilson84ffe702011-03-30 15:55:52 +00001232 default:
1233 message = MonitorSignal(monitor, &info, pid);
1234 break;
1235 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001236
Stephen Wilson84ffe702011-03-30 15:55:52 +00001237 process->SendMessage(message);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001238 stop_monitoring = !process->IsAlive();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001239 }
1240
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001241 return stop_monitoring;
1242}
1243
1244ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +00001245ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001246 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001247{
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001248 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001249
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001250 assert(monitor);
1251 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001252
Stephen Wilson84ffe702011-03-30 15:55:52 +00001253 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001254 {
1255 default:
1256 assert(false && "Unexpected SIGTRAP code!");
1257 break;
1258
1259 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1260 {
1261 // The inferior process is about to exit. Maintain the process in a
1262 // state of "limbo" until we are explicitly commanded to detach,
1263 // destroy, resume, etc.
1264 unsigned long data = 0;
1265 if (!monitor->GetEventMessage(pid, &data))
1266 data = -1;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001267 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001268 break;
1269 }
1270
1271 case 0:
1272 case TRAP_TRACE:
1273 message = ProcessMessage::Trace(pid);
1274 break;
1275
1276 case SI_KERNEL:
1277 case TRAP_BRKPT:
1278 message = ProcessMessage::Break(pid);
1279 break;
1280 }
1281
1282 return message;
1283}
1284
Stephen Wilson84ffe702011-03-30 15:55:52 +00001285ProcessMessage
1286ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001287 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001288{
1289 ProcessMessage message;
1290 int signo = info->si_signo;
1291
1292 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1293 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1294 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1295 //
1296 // IOW, user generated signals never generate what we consider to be a
1297 // "crash".
1298 //
1299 // Similarly, ACK signals generated by this monitor.
1300 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1301 {
1302 if (info->si_pid == getpid())
1303 return ProcessMessage::SignalDelivered(pid, signo);
1304 else
1305 return ProcessMessage::Signal(pid, signo);
1306 }
1307
1308 if (signo == SIGSEGV) {
1309 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1310 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1311 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1312 }
1313
1314 if (signo == SIGILL) {
1315 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1316 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1317 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1318 }
1319
1320 if (signo == SIGFPE) {
1321 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1322 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1323 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1324 }
1325
1326 if (signo == SIGBUS) {
1327 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1328 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1329 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1330 }
1331
1332 // Everything else is "normal" and does not require any special action on
1333 // our part.
1334 return ProcessMessage::Signal(pid, signo);
1335}
1336
1337ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001338ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001339{
1340 ProcessMessage::CrashReason reason;
1341 assert(info->si_signo == SIGSEGV);
1342
1343 reason = ProcessMessage::eInvalidCrashReason;
1344
Greg Clayton542e4072012-09-07 17:49:29 +00001345 switch (info->si_code)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001346 {
1347 default:
1348 assert(false && "unexpected si_code for SIGSEGV");
1349 break;
1350 case SEGV_MAPERR:
1351 reason = ProcessMessage::eInvalidAddress;
1352 break;
1353 case SEGV_ACCERR:
1354 reason = ProcessMessage::ePrivilegedAddress;
1355 break;
1356 }
Greg Clayton542e4072012-09-07 17:49:29 +00001357
Stephen Wilson84ffe702011-03-30 15:55:52 +00001358 return reason;
1359}
1360
1361ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001362ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001363{
1364 ProcessMessage::CrashReason reason;
1365 assert(info->si_signo == SIGILL);
1366
1367 reason = ProcessMessage::eInvalidCrashReason;
1368
1369 switch (info->si_code)
1370 {
1371 default:
1372 assert(false && "unexpected si_code for SIGILL");
1373 break;
1374 case ILL_ILLOPC:
1375 reason = ProcessMessage::eIllegalOpcode;
1376 break;
1377 case ILL_ILLOPN:
1378 reason = ProcessMessage::eIllegalOperand;
1379 break;
1380 case ILL_ILLADR:
1381 reason = ProcessMessage::eIllegalAddressingMode;
1382 break;
1383 case ILL_ILLTRP:
1384 reason = ProcessMessage::eIllegalTrap;
1385 break;
1386 case ILL_PRVOPC:
1387 reason = ProcessMessage::ePrivilegedOpcode;
1388 break;
1389 case ILL_PRVREG:
1390 reason = ProcessMessage::ePrivilegedRegister;
1391 break;
1392 case ILL_COPROC:
1393 reason = ProcessMessage::eCoprocessorError;
1394 break;
1395 case ILL_BADSTK:
1396 reason = ProcessMessage::eInternalStackError;
1397 break;
1398 }
1399
1400 return reason;
1401}
1402
1403ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001404ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001405{
1406 ProcessMessage::CrashReason reason;
1407 assert(info->si_signo == SIGFPE);
1408
1409 reason = ProcessMessage::eInvalidCrashReason;
1410
1411 switch (info->si_code)
1412 {
1413 default:
1414 assert(false && "unexpected si_code for SIGFPE");
1415 break;
1416 case FPE_INTDIV:
1417 reason = ProcessMessage::eIntegerDivideByZero;
1418 break;
1419 case FPE_INTOVF:
1420 reason = ProcessMessage::eIntegerOverflow;
1421 break;
1422 case FPE_FLTDIV:
1423 reason = ProcessMessage::eFloatDivideByZero;
1424 break;
1425 case FPE_FLTOVF:
1426 reason = ProcessMessage::eFloatOverflow;
1427 break;
1428 case FPE_FLTUND:
1429 reason = ProcessMessage::eFloatUnderflow;
1430 break;
1431 case FPE_FLTRES:
1432 reason = ProcessMessage::eFloatInexactResult;
1433 break;
1434 case FPE_FLTINV:
1435 reason = ProcessMessage::eFloatInvalidOperation;
1436 break;
1437 case FPE_FLTSUB:
1438 reason = ProcessMessage::eFloatSubscriptRange;
1439 break;
1440 }
1441
1442 return reason;
1443}
1444
1445ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001446ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001447{
1448 ProcessMessage::CrashReason reason;
1449 assert(info->si_signo == SIGBUS);
1450
1451 reason = ProcessMessage::eInvalidCrashReason;
1452
1453 switch (info->si_code)
1454 {
1455 default:
1456 assert(false && "unexpected si_code for SIGBUS");
1457 break;
1458 case BUS_ADRALN:
1459 reason = ProcessMessage::eIllegalAlignment;
1460 break;
1461 case BUS_ADRERR:
1462 reason = ProcessMessage::eIllegalAddress;
1463 break;
1464 case BUS_OBJERR:
1465 reason = ProcessMessage::eHardwareError;
1466 break;
1467 }
1468
1469 return reason;
1470}
1471
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001472void
Johnny Chen25e68e32011-06-14 19:19:50 +00001473ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001474{
1475 int status;
1476 pollfd fdset;
Johnny Chen25e68e32011-06-14 19:19:50 +00001477
Stephen Wilson570243b2011-01-19 01:37:06 +00001478 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001479
1480 fdset.fd = monitor->m_server_fd;
1481 fdset.events = POLLIN | POLLPRI;
1482 fdset.revents = 0;
1483
Stephen Wilson570243b2011-01-19 01:37:06 +00001484 // We are finised with the arguments and are ready to go. Sync with the
1485 // parent thread and start serving operations on the inferior.
1486 sem_post(&args->m_semaphore);
1487
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001488 for (;;)
1489 {
1490 if ((status = poll(&fdset, 1, -1)) < 0)
1491 {
1492 switch (errno)
1493 {
1494 default:
1495 assert(false && "Unexpected poll() failure!");
1496 continue;
1497
1498 case EINTR: continue; // Just poll again.
1499 case EBADF: return; // Connection terminated.
1500 }
1501 }
1502
1503 assert(status == 1 && "Too many descriptors!");
1504
1505 if (fdset.revents & POLLIN)
1506 {
1507 Operation *op = NULL;
1508
1509 READ_AGAIN:
1510 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1511 {
1512 // There is only one acceptable failure.
1513 assert(errno == EINTR);
1514 goto READ_AGAIN;
1515 }
1516
1517 assert(status == sizeof(op));
1518 op->Execute(monitor);
1519 write(fdset.fd, &op, sizeof(op));
1520 }
1521 }
1522}
1523
1524void
1525ProcessMonitor::DoOperation(Operation *op)
1526{
1527 int status;
1528 Operation *ack = NULL;
1529 Mutex::Locker lock(m_server_mutex);
1530
1531 // FIXME: Do proper error checking here.
1532 write(m_client_fd, &op, sizeof(op));
1533
1534READ_AGAIN:
1535 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1536 {
1537 // If interrupted by a signal handler try again. Otherwise the monitor
1538 // thread probably died and we have a stale file descriptor -- abort the
1539 // operation.
1540 if (errno == EINTR)
1541 goto READ_AGAIN;
1542 return;
1543 }
1544
1545 assert(status == sizeof(ack));
1546 assert(ack == op && "Invalid monitor thread response!");
1547}
1548
1549size_t
1550ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1551 Error &error)
1552{
1553 size_t result;
1554 ReadOperation op(vm_addr, buf, size, error, result);
1555 DoOperation(&op);
1556 return result;
1557}
1558
1559size_t
1560ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1561 lldb_private::Error &error)
1562{
1563 size_t result;
1564 WriteOperation op(vm_addr, buf, size, error, result);
1565 DoOperation(&op);
1566 return result;
1567}
1568
1569bool
Johnny Chen30213ff2012-01-05 19:17:38 +00001570ProcessMonitor::ReadRegisterValue(unsigned offset, unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001571{
1572 bool result;
1573 ReadRegOperation op(offset, value, result);
1574 DoOperation(&op);
1575 return result;
1576}
1577
1578bool
Johnny Chen13e8e1c2011-05-13 21:29:50 +00001579ProcessMonitor::WriteRegisterValue(unsigned offset, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001580{
1581 bool result;
1582 WriteRegOperation op(offset, value, result);
1583 DoOperation(&op);
1584 return result;
1585}
1586
1587bool
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001588ProcessMonitor::ReadGPR(void *buf)
1589{
1590 bool result;
1591 ReadGPROperation op(buf, result);
1592 DoOperation(&op);
1593 return result;
1594}
1595
1596bool
1597ProcessMonitor::ReadFPR(void *buf)
1598{
1599 bool result;
1600 ReadFPROperation op(buf, result);
1601 DoOperation(&op);
1602 return result;
1603}
1604
1605bool
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001606ProcessMonitor::WriteGPR(void *buf)
1607{
1608 bool result;
1609 WriteGPROperation op(buf, result);
1610 DoOperation(&op);
1611 return result;
1612}
1613
1614bool
1615ProcessMonitor::WriteFPR(void *buf)
1616{
1617 bool result;
1618 WriteFPROperation op(buf, result);
1619 DoOperation(&op);
1620 return result;
1621}
1622
1623bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001624ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001625{
1626 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001627 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001628 DoOperation(&op);
1629 return result;
1630}
1631
1632bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001633ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001634{
1635 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001636 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001637 DoOperation(&op);
1638 return result;
1639}
1640
1641bool
1642ProcessMonitor::BringProcessIntoLimbo()
1643{
1644 bool result;
1645 KillOperation op(result);
1646 DoOperation(&op);
1647 return result;
1648}
1649
1650bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00001651ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001652{
1653 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001654 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001655 DoOperation(&op);
1656 return result;
1657}
1658
1659bool
1660ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1661{
1662 bool result;
1663 EventMessageOperation op(tid, message, result);
1664 DoOperation(&op);
1665 return result;
1666}
1667
Greg Clayton743ecf42012-10-16 20:20:18 +00001668lldb_private::Error
Stephen Wilson84ffe702011-03-30 15:55:52 +00001669ProcessMonitor::Detach()
1670{
Greg Clayton28041352011-11-29 20:50:10 +00001671 lldb_private::Error error;
Greg Clayton743ecf42012-10-16 20:20:18 +00001672 if (m_pid != LLDB_INVALID_PROCESS_ID) {
1673 DetachOperation op(error);
1674 DoOperation(&op);
1675 }
Greg Clayton743ecf42012-10-16 20:20:18 +00001676 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00001677}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001678
1679bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001680ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1681{
Peter Collingbourne62343202011-06-14 03:55:54 +00001682 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001683
1684 if (target_fd == -1)
1685 return false;
1686
Peter Collingbourne62343202011-06-14 03:55:54 +00001687 return (dup2(target_fd, fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001688}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001689
1690void
1691ProcessMonitor::StopMonitoringChildProcess()
1692{
1693 lldb::thread_result_t thread_result;
1694
Stephen Wilsond4182f42011-02-09 20:10:35 +00001695 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001696 {
1697 Host::ThreadCancel(m_monitor_thread, NULL);
1698 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1699 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1700 }
1701}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001702
1703void
1704ProcessMonitor::StopMonitor()
1705{
1706 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00001707 StopOpThread();
Stephen Wilson84ffe702011-03-30 15:55:52 +00001708 CloseFD(m_terminal_fd);
1709 CloseFD(m_client_fd);
1710 CloseFD(m_server_fd);
1711}
1712
1713void
Greg Clayton743ecf42012-10-16 20:20:18 +00001714ProcessMonitor::StopOpThread()
1715{
1716 lldb::thread_result_t result;
1717
1718 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1719 return;
1720
1721 Host::ThreadCancel(m_operation_thread, NULL);
1722 Host::ThreadJoin(m_operation_thread, &result, NULL);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001723 m_operation_thread = LLDB_INVALID_HOST_THREAD;
Greg Clayton743ecf42012-10-16 20:20:18 +00001724}
1725
1726void
Stephen Wilson84ffe702011-03-30 15:55:52 +00001727ProcessMonitor::CloseFD(int &fd)
1728{
1729 if (fd != -1)
1730 {
1731 close(fd);
1732 fd = -1;
1733 }
1734}