blob: 50beddcd9d0f0c203d78d15fad6c02ed124e43d9 [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>
Benjamin Kramerc2b5c672012-04-07 09:13:49 +000021#include <sys/user.h>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000022#include <sys/wait.h>
23
24// C++ Includes
25// Other libraries and framework includes
Johnny Chen0d5f2d42011-10-18 18:09:30 +000026#include "lldb/Core/Debugger.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000027#include "lldb/Core/Error.h"
Johnny Chen13e8e1c2011-05-13 21:29:50 +000028#include "lldb/Core/RegisterValue.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000029#include "lldb/Core/Scalar.h"
30#include "lldb/Host/Host.h"
31#include "lldb/Target/Thread.h"
32#include "lldb/Target/RegisterContext.h"
33#include "lldb/Utility/PseudoTerminal.h"
34
Johnny Chen30213ff2012-01-05 19:17:38 +000035#include "POSIXThread.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000036#include "ProcessLinux.h"
Johnny Chen30213ff2012-01-05 19:17:38 +000037#include "ProcessPOSIXLog.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000038#include "ProcessMonitor.h"
39
40
Greg Clayton386ff182011-11-05 01:09:16 +000041#define DEBUG_PTRACE_MAXBYTES 20
42
Stephen Wilsone6f9f662010-07-24 02:19:04 +000043using namespace lldb_private;
44
Johnny Chen0d5f2d42011-10-18 18:09:30 +000045// FIXME: this code is host-dependent with respect to types and
46// endianness and needs to be fixed. For example, lldb::addr_t is
47// hard-coded to uint64_t, but on a 32-bit Linux host, ptrace requires
48// 32-bit pointer arguments. This code uses casts to work around the
49// problem.
50
51// We disable the tracing of ptrace calls for integration builds to
52// avoid the additional indirection and checks.
53#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
54
Greg Clayton386ff182011-11-05 01:09:16 +000055static void
56DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
57{
58 uint8_t *ptr = (uint8_t *)bytes;
59 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
60 for(uint32_t i=0; i<loop_count; i++)
61 {
62 s.Printf ("[%x]", *ptr);
63 ptr++;
64 }
65}
66
67static void PtraceDisplayBytes(__ptrace_request &req, void *data)
68{
69 StreamString buf;
Johnny Chen30213ff2012-01-05 19:17:38 +000070 LogSP verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
71 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
Greg Clayton386ff182011-11-05 01:09:16 +000072
73 if (verbose_log)
74 {
75 switch(req)
76 {
77 case PTRACE_POKETEXT:
78 {
79 DisplayBytes(buf, &data, 8);
80 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
81 break;
82 }
Greg Clayton542e4072012-09-07 17:49:29 +000083 case PTRACE_POKEDATA:
Greg Clayton386ff182011-11-05 01:09:16 +000084 {
85 DisplayBytes(buf, &data, 8);
86 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
87 break;
88 }
Greg Clayton542e4072012-09-07 17:49:29 +000089 case PTRACE_POKEUSER:
Greg Clayton386ff182011-11-05 01:09:16 +000090 {
91 DisplayBytes(buf, &data, 8);
92 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
93 break;
94 }
Greg Clayton542e4072012-09-07 17:49:29 +000095 case PTRACE_SETREGS:
Greg Clayton386ff182011-11-05 01:09:16 +000096 {
97 DisplayBytes(buf, data, sizeof(user_regs_struct));
98 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
99 break;
100 }
101 case PTRACE_SETFPREGS:
102 {
103 DisplayBytes(buf, data, sizeof(user_fpregs_struct));
104 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
105 break;
106 }
Greg Clayton542e4072012-09-07 17:49:29 +0000107 case PTRACE_SETSIGINFO:
Greg Clayton386ff182011-11-05 01:09:16 +0000108 {
109 DisplayBytes(buf, data, sizeof(siginfo_t));
110 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
111 break;
112 }
113 default:
114 {
115 }
116 }
117 }
118}
119
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000120// Wrapper for ptrace to catch errors and log calls.
121extern long
122PtraceWrapper(__ptrace_request req, pid_t pid, void *addr, void *data,
123 const char* reqName, const char* file, int line)
124{
Greg Clayton386ff182011-11-05 01:09:16 +0000125 long int result;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000126
Johnny Chen30213ff2012-01-05 19:17:38 +0000127 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
Greg Clayton386ff182011-11-05 01:09:16 +0000128
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000129 if (log)
130 log->Printf("ptrace(%s, %u, %p, %p) called from file %s line %d",
131 reqName, pid, addr, data, file, line);
Greg Clayton542e4072012-09-07 17:49:29 +0000132
Greg Clayton386ff182011-11-05 01:09:16 +0000133 PtraceDisplayBytes(req, data);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000134
135 errno = 0;
136 result = ptrace(req, pid, addr, data);
137
Greg Clayton386ff182011-11-05 01:09:16 +0000138 PtraceDisplayBytes(req, data);
139
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000140 if (log && (result == -1 || errno != 0))
141 {
142 const char* str;
143 switch (errno)
144 {
145 case ESRCH: str = "ESRCH"; break;
146 case EINVAL: str = "EINVAL"; break;
147 case EBUSY: str = "EBUSY"; break;
148 case EPERM: str = "EPERM"; break;
149 default: str = "<unknown>";
150 }
151 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
152 }
153
154 return result;
155}
156
157#define PTRACE(req, pid, addr, data) \
158 PtraceWrapper((req), (pid), (addr), (data), #req, __FILE__, __LINE__)
159#else
160#define PTRACE ptrace
161#endif
162
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000163//------------------------------------------------------------------------------
164// Static implementations of ProcessMonitor::ReadMemory and
165// ProcessMonitor::WriteMemory. This enables mutual recursion between these
166// functions without needed to go thru the thread funnel.
167
168static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000169DoReadMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000170 lldb::addr_t vm_addr, void *buf, size_t size, Error &error)
171{
Greg Clayton542e4072012-09-07 17:49:29 +0000172 // ptrace word size is determined by the host, not the child
173 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000174 unsigned char *dst = static_cast<unsigned char*>(buf);
175 size_t bytes_read;
176 size_t remainder;
177 long data;
178
Johnny Chen30213ff2012-01-05 19:17:38 +0000179 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000180 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000181 ProcessPOSIXLog::IncNestLevel();
182 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000183 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000184 pid, word_size, (void*)vm_addr, buf, size);
185
186 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000187 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
188 {
189 errno = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000190 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, NULL);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000191 if (data == -1L && errno)
192 {
193 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000194 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000195 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000196 return bytes_read;
197 }
198
199 remainder = size - bytes_read;
200 remainder = remainder > word_size ? word_size : remainder;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000201
202 // Copy the data into our buffer
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000203 for (unsigned i = 0; i < remainder; ++i)
204 dst[i] = ((data >> i*8) & 0xFF);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000205
Johnny Chen30213ff2012-01-05 19:17:38 +0000206 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
207 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
208 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
209 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Daniel Maleac63dddd2012-12-14 21:07:07 +0000210 {
211 uintptr_t print_dst = 0;
212 // Format bytes from data by moving into print_dst for log output
213 for (unsigned i = 0; i < remainder; ++i)
214 print_dst |= (((data >> i*8) & 0xFF) << i*8);
215 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
216 (void*)vm_addr, print_dst, (unsigned long)data);
217 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000218
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000219 vm_addr += word_size;
220 dst += word_size;
221 }
222
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000223 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000224 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000225 return bytes_read;
226}
227
228static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000229DoWriteMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000230 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
231{
Greg Clayton542e4072012-09-07 17:49:29 +0000232 // ptrace word size is determined by the host, not the child
233 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000234 const unsigned char *src = static_cast<const unsigned char*>(buf);
235 size_t bytes_written = 0;
236 size_t remainder;
237
Johnny Chen30213ff2012-01-05 19:17:38 +0000238 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000239 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000240 ProcessPOSIXLog::IncNestLevel();
241 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000242 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000243 pid, word_size, (void*)vm_addr, buf, size);
244
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000245 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
246 {
247 remainder = size - bytes_written;
248 remainder = remainder > word_size ? word_size : remainder;
249
250 if (remainder == word_size)
251 {
252 unsigned long data = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000253 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000254 for (unsigned i = 0; i < word_size; ++i)
255 data |= (unsigned long)src[i] << i*8;
256
Johnny Chen30213ff2012-01-05 19:17:38 +0000257 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
258 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
259 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
260 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000261 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
262 (void*)vm_addr, *(unsigned long*)src, data);
263
264 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000265 {
266 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000267 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000268 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000269 return bytes_written;
270 }
271 }
272 else
273 {
274 unsigned char buff[8];
Greg Clayton542e4072012-09-07 17:49:29 +0000275 if (DoReadMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000276 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000277 {
278 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000279 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000280 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000281 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000282
283 memcpy(buff, src, remainder);
284
Greg Clayton542e4072012-09-07 17:49:29 +0000285 if (DoWriteMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000286 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000287 {
288 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000289 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000290 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000291 }
292
Johnny Chen30213ff2012-01-05 19:17:38 +0000293 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
294 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
295 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
296 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000297 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
298 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000299 }
300
301 vm_addr += word_size;
302 src += word_size;
303 }
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
Stephen Wilson26977162011-03-23 02:14:42 +0000309// Simple helper function to ensure flags are enabled on the given file
310// descriptor.
311static bool
312EnsureFDFlags(int fd, int flags, Error &error)
313{
314 int status;
315
316 if ((status = fcntl(fd, F_GETFL)) == -1)
317 {
318 error.SetErrorToErrno();
319 return false;
320 }
321
322 if (fcntl(fd, F_SETFL, status | flags) == -1)
323 {
324 error.SetErrorToErrno();
325 return false;
326 }
327
328 return true;
329}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000330
331//------------------------------------------------------------------------------
332/// @class Operation
333/// @brief Represents a ProcessMonitor operation.
334///
335/// Under Linux, it is not possible to ptrace() from any other thread but the
336/// one that spawned or attached to the process from the start. Therefore, when
337/// a ProcessMonitor is asked to deliver or change the state of an inferior
338/// process the operation must be "funneled" to a specific thread to perform the
339/// task. The Operation class provides an abstract base for all services the
340/// ProcessMonitor must perform via the single virtual function Execute, thus
341/// encapsulating the code that needs to run in the privileged context.
342class Operation
343{
344public:
345 virtual void Execute(ProcessMonitor *monitor) = 0;
346};
347
348//------------------------------------------------------------------------------
349/// @class ReadOperation
350/// @brief Implements ProcessMonitor::ReadMemory.
351class ReadOperation : public Operation
352{
353public:
354 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
355 Error &error, size_t &result)
356 : m_addr(addr), m_buff(buff), m_size(size),
357 m_error(error), m_result(result)
358 { }
359
360 void Execute(ProcessMonitor *monitor);
361
362private:
363 lldb::addr_t m_addr;
364 void *m_buff;
365 size_t m_size;
366 Error &m_error;
367 size_t &m_result;
368};
369
370void
371ReadOperation::Execute(ProcessMonitor *monitor)
372{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000373 lldb::pid_t pid = monitor->GetPID();
374
Greg Clayton542e4072012-09-07 17:49:29 +0000375 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000376}
377
378//------------------------------------------------------------------------------
379/// @class ReadOperation
380/// @brief Implements ProcessMonitor::WriteMemory.
381class WriteOperation : public Operation
382{
383public:
384 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
385 Error &error, size_t &result)
386 : m_addr(addr), m_buff(buff), m_size(size),
387 m_error(error), m_result(result)
388 { }
389
390 void Execute(ProcessMonitor *monitor);
391
392private:
393 lldb::addr_t m_addr;
394 const void *m_buff;
395 size_t m_size;
396 Error &m_error;
397 size_t &m_result;
398};
399
400void
401WriteOperation::Execute(ProcessMonitor *monitor)
402{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000403 lldb::pid_t pid = monitor->GetPID();
404
Greg Clayton542e4072012-09-07 17:49:29 +0000405 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000406}
407
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000408
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000409//------------------------------------------------------------------------------
410/// @class ReadRegOperation
411/// @brief Implements ProcessMonitor::ReadRegisterValue.
412class ReadRegOperation : public Operation
413{
414public:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000415 ReadRegOperation(lldb::tid_t tid, unsigned offset,
416 RegisterValue &value, bool &result)
417 : m_tid(tid), m_offset(offset),
418 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000419 { }
420
421 void Execute(ProcessMonitor *monitor);
422
423private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000424 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000425 uintptr_t m_offset;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000426 RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000427 bool &m_result;
428};
429
430void
431ReadRegOperation::Execute(ProcessMonitor *monitor)
432{
Johnny Chen30213ff2012-01-05 19:17:38 +0000433 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000434
435 // Set errno to zero so that we can detect a failed peek.
436 errno = 0;
Daniel Maleaf0da3712012-12-18 19:50:15 +0000437 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, NULL);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000438 if (data == -1UL && errno)
439 m_result = false;
440 else
441 {
442 m_value = data;
443 m_result = true;
444 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000445 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000446 log->Printf ("ProcessMonitor::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
Johnny Chen30213ff2012-01-05 19:17:38 +0000447 POSIXThread::GetRegisterNameFromOffset(m_offset), data);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000448}
449
450//------------------------------------------------------------------------------
451/// @class WriteRegOperation
452/// @brief Implements ProcessMonitor::WriteRegisterValue.
453class WriteRegOperation : public Operation
454{
455public:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000456 WriteRegOperation(lldb::tid_t tid, unsigned offset,
457 const RegisterValue &value, bool &result)
458 : m_tid(tid), m_offset(offset),
459 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000460 { }
461
462 void Execute(ProcessMonitor *monitor);
463
464private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000465 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000466 uintptr_t m_offset;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000467 const RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000468 bool &m_result;
469};
470
471void
472WriteRegOperation::Execute(ProcessMonitor *monitor)
473{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000474 void* buf;
Johnny Chen30213ff2012-01-05 19:17:38 +0000475 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000476
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000477#if __WORDSIZE == 32
478 buf = (void*) m_value.GetAsUInt32();
479#else
480 buf = (void*) m_value.GetAsUInt64();
481#endif
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000482
483 if (log)
484 log->Printf ("ProcessMonitor::%s() reg %s: %p", __FUNCTION__,
Johnny Chen30213ff2012-01-05 19:17:38 +0000485 POSIXThread::GetRegisterNameFromOffset(m_offset), buf);
Daniel Maleaf0da3712012-12-18 19:50:15 +0000486 if (PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000487 m_result = false;
488 else
489 m_result = true;
490}
491
492//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000493/// @class ReadGPROperation
494/// @brief Implements ProcessMonitor::ReadGPR.
495class ReadGPROperation : public Operation
496{
497public:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000498 ReadGPROperation(lldb::tid_t tid, void *buf, bool &result)
499 : m_tid(tid), m_buf(buf), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000500 { }
501
502 void Execute(ProcessMonitor *monitor);
503
504private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000505 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000506 void *m_buf;
507 bool &m_result;
508};
509
510void
511ReadGPROperation::Execute(ProcessMonitor *monitor)
512{
Daniel Maleaf0da3712012-12-18 19:50:15 +0000513 if (PTRACE(PTRACE_GETREGS, m_tid, NULL, m_buf) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000514 m_result = false;
515 else
516 m_result = true;
517}
518
519//------------------------------------------------------------------------------
520/// @class ReadFPROperation
521/// @brief Implements ProcessMonitor::ReadFPR.
522class ReadFPROperation : public Operation
523{
524public:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000525 ReadFPROperation(lldb::tid_t tid, void *buf, bool &result)
526 : m_tid(tid), m_buf(buf), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000527 { }
528
529 void Execute(ProcessMonitor *monitor);
530
531private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000532 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000533 void *m_buf;
534 bool &m_result;
535};
536
537void
538ReadFPROperation::Execute(ProcessMonitor *monitor)
539{
Daniel Maleaf0da3712012-12-18 19:50:15 +0000540 if (PTRACE(PTRACE_GETFPREGS, m_tid, NULL, m_buf) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000541 m_result = false;
542 else
543 m_result = true;
544}
545
546//------------------------------------------------------------------------------
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000547/// @class WriteGPROperation
548/// @brief Implements ProcessMonitor::WriteGPR.
549class WriteGPROperation : public Operation
550{
551public:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000552 WriteGPROperation(lldb::tid_t tid, void *buf, bool &result)
553 : m_tid(tid), m_buf(buf), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000554 { }
555
556 void Execute(ProcessMonitor *monitor);
557
558private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000559 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000560 void *m_buf;
561 bool &m_result;
562};
563
564void
565WriteGPROperation::Execute(ProcessMonitor *monitor)
566{
Daniel Maleaf0da3712012-12-18 19:50:15 +0000567 if (PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000568 m_result = false;
569 else
570 m_result = true;
571}
572
573//------------------------------------------------------------------------------
574/// @class WriteFPROperation
575/// @brief Implements ProcessMonitor::WriteFPR.
576class WriteFPROperation : public Operation
577{
578public:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000579 WriteFPROperation(lldb::tid_t tid, void *buf, bool &result)
580 : m_tid(tid), m_buf(buf), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000581 { }
582
583 void Execute(ProcessMonitor *monitor);
584
585private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000586 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000587 void *m_buf;
588 bool &m_result;
589};
590
591void
592WriteFPROperation::Execute(ProcessMonitor *monitor)
593{
Daniel Maleaf0da3712012-12-18 19:50:15 +0000594 if (PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000595 m_result = false;
596 else
597 m_result = true;
598}
599
600//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000601/// @class ResumeOperation
602/// @brief Implements ProcessMonitor::Resume.
603class ResumeOperation : public Operation
604{
605public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000606 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
607 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000608
609 void Execute(ProcessMonitor *monitor);
610
611private:
612 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000613 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000614 bool &m_result;
615};
616
617void
618ResumeOperation::Execute(ProcessMonitor *monitor)
619{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000620 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000621
622 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
623 data = m_signo;
624
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000625 if (PTRACE(PTRACE_CONT, m_tid, NULL, (void*)data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000626 m_result = false;
627 else
628 m_result = true;
629}
630
631//------------------------------------------------------------------------------
632/// @class ResumeOperation
633/// @brief Implements ProcessMonitor::SingleStep.
634class SingleStepOperation : public Operation
635{
636public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000637 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
638 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000639
640 void Execute(ProcessMonitor *monitor);
641
642private:
643 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000644 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000645 bool &m_result;
646};
647
648void
649SingleStepOperation::Execute(ProcessMonitor *monitor)
650{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000651 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000652
653 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
654 data = m_signo;
655
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000656 if (PTRACE(PTRACE_SINGLESTEP, m_tid, NULL, (void*)data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000657 m_result = false;
658 else
659 m_result = true;
660}
661
662//------------------------------------------------------------------------------
663/// @class SiginfoOperation
664/// @brief Implements ProcessMonitor::GetSignalInfo.
665class SiginfoOperation : public Operation
666{
667public:
Daniel Maleaa35970a2012-11-23 18:09:58 +0000668 SiginfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
669 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000670
671 void Execute(ProcessMonitor *monitor);
672
673private:
674 lldb::tid_t m_tid;
675 void *m_info;
676 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000677 int &m_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000678};
679
680void
681SiginfoOperation::Execute(ProcessMonitor *monitor)
682{
Daniel Maleaa35970a2012-11-23 18:09:58 +0000683 if (PTRACE(PTRACE_GETSIGINFO, m_tid, NULL, m_info)) {
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000684 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000685 m_err = errno;
686 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000687 else
688 m_result = true;
689}
690
691//------------------------------------------------------------------------------
692/// @class EventMessageOperation
693/// @brief Implements ProcessMonitor::GetEventMessage.
694class EventMessageOperation : public Operation
695{
696public:
697 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
698 : m_tid(tid), m_message(message), m_result(result) { }
699
700 void Execute(ProcessMonitor *monitor);
701
702private:
703 lldb::tid_t m_tid;
704 unsigned long *m_message;
705 bool &m_result;
706};
707
708void
709EventMessageOperation::Execute(ProcessMonitor *monitor)
710{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000711 if (PTRACE(PTRACE_GETEVENTMSG, m_tid, NULL, m_message))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000712 m_result = false;
713 else
714 m_result = true;
715}
716
717//------------------------------------------------------------------------------
718/// @class KillOperation
719/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
720class KillOperation : public Operation
721{
722public:
723 KillOperation(bool &result) : m_result(result) { }
724
725 void Execute(ProcessMonitor *monitor);
726
727private:
728 bool &m_result;
729};
730
731void
732KillOperation::Execute(ProcessMonitor *monitor)
733{
734 lldb::pid_t pid = monitor->GetPID();
735
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000736 if (PTRACE(PTRACE_KILL, pid, NULL, NULL))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000737 m_result = false;
738 else
739 m_result = true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000740}
741
Greg Clayton28041352011-11-29 20:50:10 +0000742//------------------------------------------------------------------------------
743/// @class KillOperation
744/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
745class DetachOperation : public Operation
746{
747public:
748 DetachOperation(Error &result) : m_error(result) { }
749
750 void Execute(ProcessMonitor *monitor);
751
752private:
753 Error &m_error;
754};
755
756void
757DetachOperation::Execute(ProcessMonitor *monitor)
758{
759 lldb::pid_t pid = monitor->GetPID();
760
761 if (ptrace(PT_DETACH, pid, NULL, 0) < 0)
762 m_error.SetErrorToErrno();
Greg Clayton542e4072012-09-07 17:49:29 +0000763
Greg Clayton28041352011-11-29 20:50:10 +0000764}
765
Johnny Chen25e68e32011-06-14 19:19:50 +0000766ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
767 : m_monitor(monitor)
768{
769 sem_init(&m_semaphore, 0, 0);
770}
771
772ProcessMonitor::OperationArgs::~OperationArgs()
773{
774 sem_destroy(&m_semaphore);
775}
776
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000777ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
778 lldb_private::Module *module,
779 char const **argv,
780 char const **envp,
781 const char *stdin_path,
782 const char *stdout_path,
783 const char *stderr_path)
Johnny Chen25e68e32011-06-14 19:19:50 +0000784 : OperationArgs(monitor),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000785 m_module(module),
786 m_argv(argv),
787 m_envp(envp),
788 m_stdin_path(stdin_path),
789 m_stdout_path(stdout_path),
Johnny Chen25e68e32011-06-14 19:19:50 +0000790 m_stderr_path(stderr_path) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000791
792ProcessMonitor::LaunchArgs::~LaunchArgs()
Johnny Chen25e68e32011-06-14 19:19:50 +0000793{ }
794
795ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
796 lldb::pid_t pid)
797 : OperationArgs(monitor), m_pid(pid) { }
798
799ProcessMonitor::AttachArgs::~AttachArgs()
800{ }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000801
802//------------------------------------------------------------------------------
803/// The basic design of the ProcessMonitor is built around two threads.
804///
805/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
806/// for changes in the debugee state. When a change is detected a
807/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
808/// "drives" state changes in the debugger.
809///
810/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000811/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000812/// operations such as register reads/writes, stepping, etc. See the comments
813/// on the Operation class for more info as to why this is needed.
Johnny Chen30213ff2012-01-05 19:17:38 +0000814ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000815 Module *module,
816 const char *argv[],
817 const char *envp[],
818 const char *stdin_path,
819 const char *stdout_path,
820 const char *stderr_path,
821 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000822 : m_process(static_cast<ProcessLinux *>(process)),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000823 m_operation_thread(LLDB_INVALID_HOST_THREAD),
824 m_pid(LLDB_INVALID_PROCESS_ID),
825 m_terminal_fd(-1),
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000826 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000827 m_client_fd(-1),
828 m_server_fd(-1)
829{
Stephen Wilson57740ec2011-01-15 00:12:41 +0000830 std::auto_ptr<LaunchArgs> args;
831
832 args.reset(new LaunchArgs(this, module, argv, envp,
833 stdin_path, stdout_path, stderr_path));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000834
835 // Server/client descriptors.
836 if (!EnableIPC())
837 {
838 error.SetErrorToGenericError();
839 error.SetErrorString("Monitor failed to initialize.");
840 }
841
Johnny Chen25e68e32011-06-14 19:19:50 +0000842 StartLaunchOpThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000843 if (!error.Success())
844 return;
845
846WAIT_AGAIN:
847 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000848 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000849 {
850 if (errno == EINTR)
851 goto WAIT_AGAIN;
852 else
853 {
854 error.SetErrorToErrno();
855 return;
856 }
857 }
858
859 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000860 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000861 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000862 StopOpThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000863 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000864 return;
865 }
866
867 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000868 m_monitor_thread = Host::StartMonitoringChildProcess(
869 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Stephen Wilsond4182f42011-02-09 20:10:35 +0000870 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000871 {
872 error.SetErrorToGenericError();
873 error.SetErrorString("Process launch failed.");
874 return;
875 }
876}
877
Johnny Chen30213ff2012-01-05 19:17:38 +0000878ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen25e68e32011-06-14 19:19:50 +0000879 lldb::pid_t pid,
880 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000881 : m_process(static_cast<ProcessLinux *>(process)),
Johnny Chen25e68e32011-06-14 19:19:50 +0000882 m_operation_thread(LLDB_INVALID_HOST_THREAD),
883 m_pid(LLDB_INVALID_PROCESS_ID),
884 m_terminal_fd(-1),
885 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
886 m_client_fd(-1),
887 m_server_fd(-1)
888{
889 std::auto_ptr<AttachArgs> args;
890
891 args.reset(new AttachArgs(this, pid));
892
893 // Server/client descriptors.
894 if (!EnableIPC())
895 {
896 error.SetErrorToGenericError();
897 error.SetErrorString("Monitor failed to initialize.");
898 }
899
900 StartAttachOpThread(args.get(), error);
901 if (!error.Success())
902 return;
903
904WAIT_AGAIN:
905 // Wait for the operation thread to initialize.
906 if (sem_wait(&args->m_semaphore))
907 {
908 if (errno == EINTR)
909 goto WAIT_AGAIN;
910 else
911 {
912 error.SetErrorToErrno();
913 return;
914 }
915 }
916
Greg Clayton743ecf42012-10-16 20:20:18 +0000917 // Check that the attach was a success.
Johnny Chen25e68e32011-06-14 19:19:50 +0000918 if (!args->m_error.Success())
919 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000920 StopOpThread();
Johnny Chen25e68e32011-06-14 19:19:50 +0000921 error = args->m_error;
922 return;
923 }
924
925 // Finally, start monitoring the child process for change in state.
926 m_monitor_thread = Host::StartMonitoringChildProcess(
927 ProcessMonitor::MonitorCallback, this, GetPID(), true);
928 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
929 {
930 error.SetErrorToGenericError();
931 error.SetErrorString("Process attach failed.");
932 return;
933 }
934}
935
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000936ProcessMonitor::~ProcessMonitor()
937{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000938 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000939}
940
941//------------------------------------------------------------------------------
942// Thread setup and tear down.
943void
Johnny Chen25e68e32011-06-14 19:19:50 +0000944ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000945{
946 static const char *g_thread_name = "lldb.process.linux.operation";
947
Stephen Wilsond4182f42011-02-09 20:10:35 +0000948 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000949 return;
950
951 m_operation_thread =
Johnny Chen25e68e32011-06-14 19:19:50 +0000952 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000953}
954
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000955void *
Johnny Chen25e68e32011-06-14 19:19:50 +0000956ProcessMonitor::LaunchOpThread(void *arg)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000957{
958 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
959
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +0000960 if (!Launch(args)) {
961 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000962 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +0000963 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000964
Stephen Wilson570243b2011-01-19 01:37:06 +0000965 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000966 return NULL;
967}
968
969bool
970ProcessMonitor::Launch(LaunchArgs *args)
971{
972 ProcessMonitor *monitor = args->m_monitor;
973 ProcessLinux &process = monitor->GetProcess();
974 const char **argv = args->m_argv;
975 const char **envp = args->m_envp;
976 const char *stdin_path = args->m_stdin_path;
977 const char *stdout_path = args->m_stdout_path;
978 const char *stderr_path = args->m_stderr_path;
979
980 lldb_utility::PseudoTerminal terminal;
981 const size_t err_len = 1024;
982 char err_str[err_len];
983 lldb::pid_t pid;
984
985 lldb::ThreadSP inferior;
Johnny Chen30213ff2012-01-05 19:17:38 +0000986 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000987
Stephen Wilson57740ec2011-01-15 00:12:41 +0000988 // Propagate the environment if one is not supplied.
989 if (envp == NULL || envp[0] == NULL)
990 envp = const_cast<const char **>(environ);
991
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000992 // Pseudo terminal setup.
993 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
994 {
995 args->m_error.SetErrorToGenericError();
996 args->m_error.SetErrorString("Could not open controlling TTY.");
997 goto FINISH;
998 }
999
Daniel Maleaa85e6b62012-12-07 22:21:08 +00001000 if ((pid = terminal.Fork(err_str, err_len)) == -1)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001001 {
1002 args->m_error.SetErrorToGenericError();
1003 args->m_error.SetErrorString("Process fork failed.");
1004 goto FINISH;
1005 }
1006
Peter Collingbourne6a520222011-06-14 03:55:58 +00001007 // Recognized child exit status codes.
1008 enum {
1009 ePtraceFailed = 1,
1010 eDupStdinFailed,
1011 eDupStdoutFailed,
1012 eDupStderrFailed,
1013 eExecFailed
1014 };
1015
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001016 // Child process.
1017 if (pid == 0)
1018 {
1019 // Trace this process.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001020 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL) < 0)
Peter Collingbourne6a520222011-06-14 03:55:58 +00001021 exit(ePtraceFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001022
1023 // Do not inherit setgid powers.
1024 setgid(getgid());
1025
1026 // Let us have our own process group.
1027 setpgid(0, 0);
1028
Greg Clayton710dd5a2011-01-08 20:28:42 +00001029 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001030 //
1031 // FIXME: If two or more of the paths are the same we needlessly open
1032 // the same file multiple times.
1033 if (stdin_path != NULL && stdin_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001034 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001035 exit(eDupStdinFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001036
1037 if (stdout_path != NULL && stdout_path[0])
1038 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001039 exit(eDupStdoutFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001040
1041 if (stderr_path != NULL && stderr_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001042 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001043 exit(eDupStderrFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001044
1045 // Execute. We should never return.
1046 execve(argv[0],
1047 const_cast<char *const *>(argv),
1048 const_cast<char *const *>(envp));
Peter Collingbourne6a520222011-06-14 03:55:58 +00001049 exit(eExecFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001050 }
1051
1052 // Wait for the child process to to trap on its call to execve.
Peter Collingbourne6a520222011-06-14 03:55:58 +00001053 pid_t wpid;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001054 int status;
Peter Collingbourne6a520222011-06-14 03:55:58 +00001055 if ((wpid = waitpid(pid, &status, 0)) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001056 {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001057 args->m_error.SetErrorToErrno();
1058 goto FINISH;
1059 }
Peter Collingbourne6a520222011-06-14 03:55:58 +00001060 else if (WIFEXITED(status))
1061 {
1062 // open, dup or execve likely failed for some reason.
1063 args->m_error.SetErrorToGenericError();
1064 switch (WEXITSTATUS(status))
1065 {
Greg Clayton542e4072012-09-07 17:49:29 +00001066 case ePtraceFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001067 args->m_error.SetErrorString("Child ptrace failed.");
1068 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001069 case eDupStdinFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001070 args->m_error.SetErrorString("Child open stdin failed.");
1071 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001072 case eDupStdoutFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001073 args->m_error.SetErrorString("Child open stdout failed.");
1074 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001075 case eDupStderrFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001076 args->m_error.SetErrorString("Child open stderr failed.");
1077 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001078 case eExecFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001079 args->m_error.SetErrorString("Child exec failed.");
1080 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001081 default:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001082 args->m_error.SetErrorString("Child returned unknown exit status.");
1083 break;
1084 }
1085 goto FINISH;
1086 }
1087 assert(WIFSTOPPED(status) && wpid == pid &&
1088 "Could not sync with inferior process.");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001089
1090 // Have the child raise an event on exit. This is used to keep the child in
1091 // limbo until it is destroyed.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001092 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)PTRACE_O_TRACEEXIT) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001093 {
1094 args->m_error.SetErrorToErrno();
1095 goto FINISH;
1096 }
1097
1098 // Release the master terminal descriptor and pass it off to the
1099 // ProcessMonitor instance. Similarly stash the inferior pid.
1100 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1101 monitor->m_pid = pid;
1102
Stephen Wilson26977162011-03-23 02:14:42 +00001103 // Set the terminal fd to be in non blocking mode (it simplifies the
1104 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1105 // descriptor to read from).
1106 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1107 goto FINISH;
1108
Johnny Chen30213ff2012-01-05 19:17:38 +00001109 // Update the process thread list with this new thread.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001110 // FIXME: should we be letting UpdateThreadList handle this?
1111 // FIXME: by using pids instead of tids, we can only support one thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001112 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001113 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001114 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001115 process.GetThreadList().AddThread(inferior);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001116
1117 // Let our process instance know the thread has stopped.
1118 process.SendMessage(ProcessMessage::Trace(pid));
1119
1120FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001121 return args->m_error.Success();
1122}
1123
1124bool
1125ProcessMonitor::EnableIPC()
1126{
1127 int fd[2];
1128
1129 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
1130 return false;
1131
1132 m_client_fd = fd[0];
1133 m_server_fd = fd[1];
1134 return true;
1135}
1136
Johnny Chen25e68e32011-06-14 19:19:50 +00001137void
1138ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1139{
1140 static const char *g_thread_name = "lldb.process.linux.operation";
1141
1142 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1143 return;
1144
1145 m_operation_thread =
1146 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1147}
1148
Johnny Chen25e68e32011-06-14 19:19:50 +00001149void *
1150ProcessMonitor::AttachOpThread(void *arg)
1151{
1152 AttachArgs *args = static_cast<AttachArgs*>(arg);
1153
Greg Clayton743ecf42012-10-16 20:20:18 +00001154 if (!Attach(args)) {
1155 sem_post(&args->m_semaphore);
Johnny Chen25e68e32011-06-14 19:19:50 +00001156 return NULL;
Greg Clayton743ecf42012-10-16 20:20:18 +00001157 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001158
1159 ServeOperation(args);
1160 return NULL;
1161}
1162
1163bool
1164ProcessMonitor::Attach(AttachArgs *args)
1165{
1166 lldb::pid_t pid = args->m_pid;
1167
1168 ProcessMonitor *monitor = args->m_monitor;
1169 ProcessLinux &process = monitor->GetProcess();
Johnny Chen25e68e32011-06-14 19:19:50 +00001170 lldb::ThreadSP inferior;
Johnny Chen30213ff2012-01-05 19:17:38 +00001171 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen25e68e32011-06-14 19:19:50 +00001172
1173 if (pid <= 1)
1174 {
1175 args->m_error.SetErrorToGenericError();
1176 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1177 goto FINISH;
1178 }
1179
1180 // Attach to the requested process.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001181 if (PTRACE(PTRACE_ATTACH, pid, NULL, NULL) < 0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001182 {
1183 args->m_error.SetErrorToErrno();
1184 goto FINISH;
1185 }
1186
1187 int status;
1188 if ((status = waitpid(pid, NULL, 0)) < 0)
1189 {
1190 args->m_error.SetErrorToErrno();
1191 goto FINISH;
1192 }
1193
Greg Clayton926cce72012-10-12 16:10:12 +00001194 monitor->m_pid = pid;
1195
Johnny Chen30213ff2012-01-05 19:17:38 +00001196 // Update the process thread list with the attached thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001197 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001198 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001199 log->Printf ("ProcessMonitor::%s() adding tid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen25e68e32011-06-14 19:19:50 +00001200 process.GetThreadList().AddThread(inferior);
Johnny Chen25e68e32011-06-14 19:19:50 +00001201
1202 // Let our process instance know the thread has stopped.
1203 process.SendMessage(ProcessMessage::Trace(pid));
1204
1205 FINISH:
1206 return args->m_error.Success();
1207}
1208
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001209bool
1210ProcessMonitor::MonitorCallback(void *callback_baton,
1211 lldb::pid_t pid,
Peter Collingbourne2c67b9a2011-11-21 00:10:19 +00001212 bool exited,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001213 int signal,
1214 int status)
1215{
1216 ProcessMessage message;
1217 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
1218 ProcessLinux *process = monitor->m_process;
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001219 assert(process);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001220 bool stop_monitoring;
1221 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001222 int ptrace_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001223
Daniel Maleaa35970a2012-11-23 18:09:58 +00001224 if (!monitor->GetSignalInfo(pid, &info, ptrace_err)) {
1225 if (ptrace_err == EINVAL) {
1226 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1227 if (!monitor->Resume(pid, SIGSTOP)) {
1228 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1229 }
1230 stop_monitoring = false;
1231 } else {
1232 // ptrace(GETSIGINFO) failed (but not due to group-stop). Most likely,
1233 // this means the child pid is gone (or not being debugged) therefore
1234 // stop the monitor thread.
1235 stop_monitoring = true;
1236 }
1237 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00001238 else {
1239 switch (info.si_signo)
1240 {
1241 case SIGTRAP:
1242 message = MonitorSIGTRAP(monitor, &info, pid);
1243 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001244
Stephen Wilson84ffe702011-03-30 15:55:52 +00001245 default:
1246 message = MonitorSignal(monitor, &info, pid);
1247 break;
1248 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001249
Stephen Wilson84ffe702011-03-30 15:55:52 +00001250 process->SendMessage(message);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001251 stop_monitoring = !process->IsAlive();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001252 }
1253
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001254 return stop_monitoring;
1255}
1256
1257ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +00001258ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001259 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001260{
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001261 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001262
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001263 assert(monitor);
1264 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001265
Stephen Wilson84ffe702011-03-30 15:55:52 +00001266 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001267 {
1268 default:
1269 assert(false && "Unexpected SIGTRAP code!");
1270 break;
1271
1272 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1273 {
1274 // The inferior process is about to exit. Maintain the process in a
1275 // state of "limbo" until we are explicitly commanded to detach,
1276 // destroy, resume, etc.
1277 unsigned long data = 0;
1278 if (!monitor->GetEventMessage(pid, &data))
1279 data = -1;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001280 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001281 break;
1282 }
1283
1284 case 0:
1285 case TRAP_TRACE:
1286 message = ProcessMessage::Trace(pid);
1287 break;
1288
1289 case SI_KERNEL:
1290 case TRAP_BRKPT:
1291 message = ProcessMessage::Break(pid);
1292 break;
1293 }
1294
1295 return message;
1296}
1297
Stephen Wilson84ffe702011-03-30 15:55:52 +00001298ProcessMessage
1299ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001300 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001301{
1302 ProcessMessage message;
1303 int signo = info->si_signo;
1304
1305 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1306 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1307 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1308 //
1309 // IOW, user generated signals never generate what we consider to be a
1310 // "crash".
1311 //
1312 // Similarly, ACK signals generated by this monitor.
1313 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1314 {
1315 if (info->si_pid == getpid())
1316 return ProcessMessage::SignalDelivered(pid, signo);
1317 else
1318 return ProcessMessage::Signal(pid, signo);
1319 }
1320
1321 if (signo == SIGSEGV) {
1322 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1323 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1324 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1325 }
1326
1327 if (signo == SIGILL) {
1328 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1329 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1330 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1331 }
1332
1333 if (signo == SIGFPE) {
1334 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1335 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1336 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1337 }
1338
1339 if (signo == SIGBUS) {
1340 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1341 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1342 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1343 }
1344
1345 // Everything else is "normal" and does not require any special action on
1346 // our part.
1347 return ProcessMessage::Signal(pid, signo);
1348}
1349
1350ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001351ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001352{
1353 ProcessMessage::CrashReason reason;
1354 assert(info->si_signo == SIGSEGV);
1355
1356 reason = ProcessMessage::eInvalidCrashReason;
1357
Greg Clayton542e4072012-09-07 17:49:29 +00001358 switch (info->si_code)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001359 {
1360 default:
1361 assert(false && "unexpected si_code for SIGSEGV");
1362 break;
1363 case SEGV_MAPERR:
1364 reason = ProcessMessage::eInvalidAddress;
1365 break;
1366 case SEGV_ACCERR:
1367 reason = ProcessMessage::ePrivilegedAddress;
1368 break;
1369 }
Greg Clayton542e4072012-09-07 17:49:29 +00001370
Stephen Wilson84ffe702011-03-30 15:55:52 +00001371 return reason;
1372}
1373
1374ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001375ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001376{
1377 ProcessMessage::CrashReason reason;
1378 assert(info->si_signo == SIGILL);
1379
1380 reason = ProcessMessage::eInvalidCrashReason;
1381
1382 switch (info->si_code)
1383 {
1384 default:
1385 assert(false && "unexpected si_code for SIGILL");
1386 break;
1387 case ILL_ILLOPC:
1388 reason = ProcessMessage::eIllegalOpcode;
1389 break;
1390 case ILL_ILLOPN:
1391 reason = ProcessMessage::eIllegalOperand;
1392 break;
1393 case ILL_ILLADR:
1394 reason = ProcessMessage::eIllegalAddressingMode;
1395 break;
1396 case ILL_ILLTRP:
1397 reason = ProcessMessage::eIllegalTrap;
1398 break;
1399 case ILL_PRVOPC:
1400 reason = ProcessMessage::ePrivilegedOpcode;
1401 break;
1402 case ILL_PRVREG:
1403 reason = ProcessMessage::ePrivilegedRegister;
1404 break;
1405 case ILL_COPROC:
1406 reason = ProcessMessage::eCoprocessorError;
1407 break;
1408 case ILL_BADSTK:
1409 reason = ProcessMessage::eInternalStackError;
1410 break;
1411 }
1412
1413 return reason;
1414}
1415
1416ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001417ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001418{
1419 ProcessMessage::CrashReason reason;
1420 assert(info->si_signo == SIGFPE);
1421
1422 reason = ProcessMessage::eInvalidCrashReason;
1423
1424 switch (info->si_code)
1425 {
1426 default:
1427 assert(false && "unexpected si_code for SIGFPE");
1428 break;
1429 case FPE_INTDIV:
1430 reason = ProcessMessage::eIntegerDivideByZero;
1431 break;
1432 case FPE_INTOVF:
1433 reason = ProcessMessage::eIntegerOverflow;
1434 break;
1435 case FPE_FLTDIV:
1436 reason = ProcessMessage::eFloatDivideByZero;
1437 break;
1438 case FPE_FLTOVF:
1439 reason = ProcessMessage::eFloatOverflow;
1440 break;
1441 case FPE_FLTUND:
1442 reason = ProcessMessage::eFloatUnderflow;
1443 break;
1444 case FPE_FLTRES:
1445 reason = ProcessMessage::eFloatInexactResult;
1446 break;
1447 case FPE_FLTINV:
1448 reason = ProcessMessage::eFloatInvalidOperation;
1449 break;
1450 case FPE_FLTSUB:
1451 reason = ProcessMessage::eFloatSubscriptRange;
1452 break;
1453 }
1454
1455 return reason;
1456}
1457
1458ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001459ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001460{
1461 ProcessMessage::CrashReason reason;
1462 assert(info->si_signo == SIGBUS);
1463
1464 reason = ProcessMessage::eInvalidCrashReason;
1465
1466 switch (info->si_code)
1467 {
1468 default:
1469 assert(false && "unexpected si_code for SIGBUS");
1470 break;
1471 case BUS_ADRALN:
1472 reason = ProcessMessage::eIllegalAlignment;
1473 break;
1474 case BUS_ADRERR:
1475 reason = ProcessMessage::eIllegalAddress;
1476 break;
1477 case BUS_OBJERR:
1478 reason = ProcessMessage::eHardwareError;
1479 break;
1480 }
1481
1482 return reason;
1483}
1484
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001485void
Johnny Chen25e68e32011-06-14 19:19:50 +00001486ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001487{
1488 int status;
1489 pollfd fdset;
Johnny Chen25e68e32011-06-14 19:19:50 +00001490
Stephen Wilson570243b2011-01-19 01:37:06 +00001491 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001492
1493 fdset.fd = monitor->m_server_fd;
1494 fdset.events = POLLIN | POLLPRI;
1495 fdset.revents = 0;
1496
Stephen Wilson570243b2011-01-19 01:37:06 +00001497 // We are finised with the arguments and are ready to go. Sync with the
1498 // parent thread and start serving operations on the inferior.
1499 sem_post(&args->m_semaphore);
1500
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001501 for (;;)
1502 {
1503 if ((status = poll(&fdset, 1, -1)) < 0)
1504 {
1505 switch (errno)
1506 {
1507 default:
1508 assert(false && "Unexpected poll() failure!");
1509 continue;
1510
1511 case EINTR: continue; // Just poll again.
1512 case EBADF: return; // Connection terminated.
1513 }
1514 }
1515
1516 assert(status == 1 && "Too many descriptors!");
1517
1518 if (fdset.revents & POLLIN)
1519 {
1520 Operation *op = NULL;
1521
1522 READ_AGAIN:
1523 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1524 {
1525 // There is only one acceptable failure.
1526 assert(errno == EINTR);
1527 goto READ_AGAIN;
1528 }
1529
1530 assert(status == sizeof(op));
1531 op->Execute(monitor);
1532 write(fdset.fd, &op, sizeof(op));
1533 }
1534 }
1535}
1536
1537void
1538ProcessMonitor::DoOperation(Operation *op)
1539{
1540 int status;
1541 Operation *ack = NULL;
1542 Mutex::Locker lock(m_server_mutex);
1543
1544 // FIXME: Do proper error checking here.
1545 write(m_client_fd, &op, sizeof(op));
1546
1547READ_AGAIN:
1548 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1549 {
1550 // If interrupted by a signal handler try again. Otherwise the monitor
1551 // thread probably died and we have a stale file descriptor -- abort the
1552 // operation.
1553 if (errno == EINTR)
1554 goto READ_AGAIN;
1555 return;
1556 }
1557
1558 assert(status == sizeof(ack));
1559 assert(ack == op && "Invalid monitor thread response!");
1560}
1561
1562size_t
1563ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1564 Error &error)
1565{
1566 size_t result;
1567 ReadOperation op(vm_addr, buf, size, error, result);
1568 DoOperation(&op);
1569 return result;
1570}
1571
1572size_t
1573ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1574 lldb_private::Error &error)
1575{
1576 size_t result;
1577 WriteOperation op(vm_addr, buf, size, error, result);
1578 DoOperation(&op);
1579 return result;
1580}
1581
1582bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001583ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001584{
1585 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001586 ReadRegOperation op(tid, offset, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001587 DoOperation(&op);
1588 return result;
1589}
1590
1591bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001592ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001593{
1594 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001595 WriteRegOperation op(tid, offset, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001596 DoOperation(&op);
1597 return result;
1598}
1599
1600bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001601ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001602{
1603 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001604 ReadGPROperation op(tid, buf, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001605 DoOperation(&op);
1606 return result;
1607}
1608
1609bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001610ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001611{
1612 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001613 ReadFPROperation op(tid, buf, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001614 DoOperation(&op);
1615 return result;
1616}
1617
1618bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001619ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001620{
1621 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001622 WriteGPROperation op(tid, buf, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001623 DoOperation(&op);
1624 return result;
1625}
1626
1627bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001628ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001629{
1630 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001631 WriteFPROperation op(tid, buf, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001632 DoOperation(&op);
1633 return result;
1634}
1635
1636bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001637ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001638{
1639 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001640 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001641 DoOperation(&op);
1642 return result;
1643}
1644
1645bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001646ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001647{
1648 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001649 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001650 DoOperation(&op);
1651 return result;
1652}
1653
1654bool
1655ProcessMonitor::BringProcessIntoLimbo()
1656{
1657 bool result;
1658 KillOperation op(result);
1659 DoOperation(&op);
1660 return result;
1661}
1662
1663bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00001664ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001665{
1666 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001667 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001668 DoOperation(&op);
1669 return result;
1670}
1671
1672bool
1673ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1674{
1675 bool result;
1676 EventMessageOperation op(tid, message, result);
1677 DoOperation(&op);
1678 return result;
1679}
1680
Greg Clayton743ecf42012-10-16 20:20:18 +00001681lldb_private::Error
Stephen Wilson84ffe702011-03-30 15:55:52 +00001682ProcessMonitor::Detach()
1683{
Greg Clayton28041352011-11-29 20:50:10 +00001684 lldb_private::Error error;
Greg Clayton743ecf42012-10-16 20:20:18 +00001685 if (m_pid != LLDB_INVALID_PROCESS_ID) {
1686 DetachOperation op(error);
1687 DoOperation(&op);
1688 }
Greg Clayton743ecf42012-10-16 20:20:18 +00001689 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00001690}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001691
1692bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001693ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1694{
Peter Collingbourne62343202011-06-14 03:55:54 +00001695 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001696
1697 if (target_fd == -1)
1698 return false;
1699
Peter Collingbourne62343202011-06-14 03:55:54 +00001700 return (dup2(target_fd, fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001701}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001702
1703void
1704ProcessMonitor::StopMonitoringChildProcess()
1705{
1706 lldb::thread_result_t thread_result;
1707
Stephen Wilsond4182f42011-02-09 20:10:35 +00001708 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001709 {
1710 Host::ThreadCancel(m_monitor_thread, NULL);
1711 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1712 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1713 }
1714}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001715
1716void
1717ProcessMonitor::StopMonitor()
1718{
1719 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00001720 StopOpThread();
Stephen Wilson84ffe702011-03-30 15:55:52 +00001721 CloseFD(m_terminal_fd);
1722 CloseFD(m_client_fd);
1723 CloseFD(m_server_fd);
1724}
1725
1726void
Greg Clayton743ecf42012-10-16 20:20:18 +00001727ProcessMonitor::StopOpThread()
1728{
1729 lldb::thread_result_t result;
1730
1731 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1732 return;
1733
1734 Host::ThreadCancel(m_operation_thread, NULL);
1735 Host::ThreadJoin(m_operation_thread, &result, NULL);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001736 m_operation_thread = LLDB_INVALID_HOST_THREAD;
Greg Clayton743ecf42012-10-16 20:20:18 +00001737}
1738
1739void
Stephen Wilson84ffe702011-03-30 15:55:52 +00001740ProcessMonitor::CloseFD(int &fd)
1741{
1742 if (fd != -1)
1743 {
1744 close(fd);
1745 fd = -1;
1746 }
1747}