blob: f36a9eef732f66ef87ae3eb9a972033adbc48028 [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,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000783 const char *stderr_path,
784 const char *working_dir)
Johnny Chen25e68e32011-06-14 19:19:50 +0000785 : OperationArgs(monitor),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000786 m_module(module),
787 m_argv(argv),
788 m_envp(envp),
789 m_stdin_path(stdin_path),
790 m_stdout_path(stdout_path),
Daniel Malea6217d2a2013-01-08 14:49:22 +0000791 m_stderr_path(stderr_path),
792 m_working_dir(working_dir) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000793
794ProcessMonitor::LaunchArgs::~LaunchArgs()
Johnny Chen25e68e32011-06-14 19:19:50 +0000795{ }
796
797ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
798 lldb::pid_t pid)
799 : OperationArgs(monitor), m_pid(pid) { }
800
801ProcessMonitor::AttachArgs::~AttachArgs()
802{ }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000803
804//------------------------------------------------------------------------------
805/// The basic design of the ProcessMonitor is built around two threads.
806///
807/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
808/// for changes in the debugee state. When a change is detected a
809/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
810/// "drives" state changes in the debugger.
811///
812/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000813/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000814/// operations such as register reads/writes, stepping, etc. See the comments
815/// on the Operation class for more info as to why this is needed.
Johnny Chen30213ff2012-01-05 19:17:38 +0000816ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000817 Module *module,
818 const char *argv[],
819 const char *envp[],
820 const char *stdin_path,
821 const char *stdout_path,
822 const char *stderr_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000823 const char *working_dir,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000824 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000825 : m_process(static_cast<ProcessLinux *>(process)),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000826 m_operation_thread(LLDB_INVALID_HOST_THREAD),
827 m_pid(LLDB_INVALID_PROCESS_ID),
828 m_terminal_fd(-1),
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000829 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000830 m_client_fd(-1),
831 m_server_fd(-1)
832{
Stephen Wilson57740ec2011-01-15 00:12:41 +0000833 std::auto_ptr<LaunchArgs> args;
834
835 args.reset(new LaunchArgs(this, module, argv, envp,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000836 stdin_path, stdout_path, stderr_path, working_dir));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000837
838 // Server/client descriptors.
839 if (!EnableIPC())
840 {
841 error.SetErrorToGenericError();
842 error.SetErrorString("Monitor failed to initialize.");
843 }
844
Johnny Chen25e68e32011-06-14 19:19:50 +0000845 StartLaunchOpThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000846 if (!error.Success())
847 return;
848
849WAIT_AGAIN:
850 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000851 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000852 {
853 if (errno == EINTR)
854 goto WAIT_AGAIN;
855 else
856 {
857 error.SetErrorToErrno();
858 return;
859 }
860 }
861
862 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000863 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000864 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000865 StopOpThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000866 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000867 return;
868 }
869
870 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000871 m_monitor_thread = Host::StartMonitoringChildProcess(
872 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Stephen Wilsond4182f42011-02-09 20:10:35 +0000873 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000874 {
875 error.SetErrorToGenericError();
876 error.SetErrorString("Process launch failed.");
877 return;
878 }
879}
880
Johnny Chen30213ff2012-01-05 19:17:38 +0000881ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen25e68e32011-06-14 19:19:50 +0000882 lldb::pid_t pid,
883 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000884 : m_process(static_cast<ProcessLinux *>(process)),
Johnny Chen25e68e32011-06-14 19:19:50 +0000885 m_operation_thread(LLDB_INVALID_HOST_THREAD),
886 m_pid(LLDB_INVALID_PROCESS_ID),
887 m_terminal_fd(-1),
888 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
889 m_client_fd(-1),
890 m_server_fd(-1)
891{
892 std::auto_ptr<AttachArgs> args;
893
894 args.reset(new AttachArgs(this, pid));
895
896 // Server/client descriptors.
897 if (!EnableIPC())
898 {
899 error.SetErrorToGenericError();
900 error.SetErrorString("Monitor failed to initialize.");
901 }
902
903 StartAttachOpThread(args.get(), error);
904 if (!error.Success())
905 return;
906
907WAIT_AGAIN:
908 // Wait for the operation thread to initialize.
909 if (sem_wait(&args->m_semaphore))
910 {
911 if (errno == EINTR)
912 goto WAIT_AGAIN;
913 else
914 {
915 error.SetErrorToErrno();
916 return;
917 }
918 }
919
Greg Clayton743ecf42012-10-16 20:20:18 +0000920 // Check that the attach was a success.
Johnny Chen25e68e32011-06-14 19:19:50 +0000921 if (!args->m_error.Success())
922 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000923 StopOpThread();
Johnny Chen25e68e32011-06-14 19:19:50 +0000924 error = args->m_error;
925 return;
926 }
927
928 // Finally, start monitoring the child process for change in state.
929 m_monitor_thread = Host::StartMonitoringChildProcess(
930 ProcessMonitor::MonitorCallback, this, GetPID(), true);
931 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
932 {
933 error.SetErrorToGenericError();
934 error.SetErrorString("Process attach failed.");
935 return;
936 }
937}
938
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000939ProcessMonitor::~ProcessMonitor()
940{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000941 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000942}
943
944//------------------------------------------------------------------------------
945// Thread setup and tear down.
946void
Johnny Chen25e68e32011-06-14 19:19:50 +0000947ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000948{
949 static const char *g_thread_name = "lldb.process.linux.operation";
950
Stephen Wilsond4182f42011-02-09 20:10:35 +0000951 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000952 return;
953
954 m_operation_thread =
Johnny Chen25e68e32011-06-14 19:19:50 +0000955 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000956}
957
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000958void *
Johnny Chen25e68e32011-06-14 19:19:50 +0000959ProcessMonitor::LaunchOpThread(void *arg)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000960{
961 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
962
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +0000963 if (!Launch(args)) {
964 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000965 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +0000966 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000967
Stephen Wilson570243b2011-01-19 01:37:06 +0000968 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000969 return NULL;
970}
971
972bool
973ProcessMonitor::Launch(LaunchArgs *args)
974{
975 ProcessMonitor *monitor = args->m_monitor;
976 ProcessLinux &process = monitor->GetProcess();
977 const char **argv = args->m_argv;
978 const char **envp = args->m_envp;
979 const char *stdin_path = args->m_stdin_path;
980 const char *stdout_path = args->m_stdout_path;
981 const char *stderr_path = args->m_stderr_path;
Daniel Malea6217d2a2013-01-08 14:49:22 +0000982 const char *working_dir = args->m_working_dir;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000983
984 lldb_utility::PseudoTerminal terminal;
985 const size_t err_len = 1024;
986 char err_str[err_len];
987 lldb::pid_t pid;
Matt Kopec650648f2013-01-08 16:30:18 +0000988 long ptrace_opts = 0;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000989
990 lldb::ThreadSP inferior;
Johnny Chen30213ff2012-01-05 19:17:38 +0000991 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000992
Stephen Wilson57740ec2011-01-15 00:12:41 +0000993 // Propagate the environment if one is not supplied.
994 if (envp == NULL || envp[0] == NULL)
995 envp = const_cast<const char **>(environ);
996
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000997 // Pseudo terminal setup.
998 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
999 {
1000 args->m_error.SetErrorToGenericError();
1001 args->m_error.SetErrorString("Could not open controlling TTY.");
1002 goto FINISH;
1003 }
1004
Daniel Maleaa85e6b62012-12-07 22:21:08 +00001005 if ((pid = terminal.Fork(err_str, err_len)) == -1)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001006 {
1007 args->m_error.SetErrorToGenericError();
1008 args->m_error.SetErrorString("Process fork failed.");
1009 goto FINISH;
1010 }
1011
Peter Collingbourne6a520222011-06-14 03:55:58 +00001012 // Recognized child exit status codes.
1013 enum {
1014 ePtraceFailed = 1,
1015 eDupStdinFailed,
1016 eDupStdoutFailed,
1017 eDupStderrFailed,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001018 eChdirFailed,
Peter Collingbourne6a520222011-06-14 03:55:58 +00001019 eExecFailed
1020 };
1021
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001022 // Child process.
1023 if (pid == 0)
1024 {
1025 // Trace this process.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001026 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL) < 0)
Peter Collingbourne6a520222011-06-14 03:55:58 +00001027 exit(ePtraceFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001028
1029 // Do not inherit setgid powers.
1030 setgid(getgid());
1031
1032 // Let us have our own process group.
1033 setpgid(0, 0);
1034
Greg Clayton710dd5a2011-01-08 20:28:42 +00001035 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001036 //
1037 // FIXME: If two or more of the paths are the same we needlessly open
1038 // the same file multiple times.
1039 if (stdin_path != NULL && stdin_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001040 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001041 exit(eDupStdinFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001042
1043 if (stdout_path != NULL && stdout_path[0])
1044 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001045 exit(eDupStdoutFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001046
1047 if (stderr_path != NULL && stderr_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001048 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001049 exit(eDupStderrFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001050
Daniel Malea6217d2a2013-01-08 14:49:22 +00001051 // Change working directory
1052 if (working_dir != NULL && working_dir[0])
1053 if (0 != ::chdir(working_dir))
1054 exit(eChdirFailed);
1055
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001056 // Execute. We should never return.
1057 execve(argv[0],
1058 const_cast<char *const *>(argv),
1059 const_cast<char *const *>(envp));
Peter Collingbourne6a520222011-06-14 03:55:58 +00001060 exit(eExecFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001061 }
1062
1063 // Wait for the child process to to trap on its call to execve.
Peter Collingbourne6a520222011-06-14 03:55:58 +00001064 pid_t wpid;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001065 int status;
Peter Collingbourne6a520222011-06-14 03:55:58 +00001066 if ((wpid = waitpid(pid, &status, 0)) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001067 {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001068 args->m_error.SetErrorToErrno();
1069 goto FINISH;
1070 }
Peter Collingbourne6a520222011-06-14 03:55:58 +00001071 else if (WIFEXITED(status))
1072 {
1073 // open, dup or execve likely failed for some reason.
1074 args->m_error.SetErrorToGenericError();
1075 switch (WEXITSTATUS(status))
1076 {
Greg Clayton542e4072012-09-07 17:49:29 +00001077 case ePtraceFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001078 args->m_error.SetErrorString("Child ptrace failed.");
1079 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001080 case eDupStdinFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001081 args->m_error.SetErrorString("Child open stdin failed.");
1082 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001083 case eDupStdoutFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001084 args->m_error.SetErrorString("Child open stdout failed.");
1085 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001086 case eDupStderrFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001087 args->m_error.SetErrorString("Child open stderr failed.");
1088 break;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001089 case eChdirFailed:
1090 args->m_error.SetErrorString("Child failed to set working directory.");
1091 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001092 case eExecFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001093 args->m_error.SetErrorString("Child exec failed.");
1094 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001095 default:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001096 args->m_error.SetErrorString("Child returned unknown exit status.");
1097 break;
1098 }
1099 goto FINISH;
1100 }
1101 assert(WIFSTOPPED(status) && wpid == pid &&
1102 "Could not sync with inferior process.");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001103
1104 // Have the child raise an event on exit. This is used to keep the child in
1105 // limbo until it is destroyed.
Matt Kopec650648f2013-01-08 16:30:18 +00001106 ptrace_opts |= PTRACE_O_TRACEEXIT;
1107
1108 // Have the tracer trace threads which spawn in the inferior process.
1109 ptrace_opts |= PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE;
1110
1111 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)ptrace_opts) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001112 {
1113 args->m_error.SetErrorToErrno();
1114 goto FINISH;
1115 }
1116
1117 // Release the master terminal descriptor and pass it off to the
1118 // ProcessMonitor instance. Similarly stash the inferior pid.
1119 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1120 monitor->m_pid = pid;
1121
Stephen Wilson26977162011-03-23 02:14:42 +00001122 // Set the terminal fd to be in non blocking mode (it simplifies the
1123 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1124 // descriptor to read from).
1125 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1126 goto FINISH;
1127
Johnny Chen30213ff2012-01-05 19:17:38 +00001128 // Update the process thread list with this new thread.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001129 // FIXME: should we be letting UpdateThreadList handle this?
1130 // FIXME: by using pids instead of tids, we can only support one thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001131 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001132 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001133 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001134 process.GetThreadList().AddThread(inferior);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001135
1136 // Let our process instance know the thread has stopped.
1137 process.SendMessage(ProcessMessage::Trace(pid));
1138
1139FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001140 return args->m_error.Success();
1141}
1142
1143bool
1144ProcessMonitor::EnableIPC()
1145{
1146 int fd[2];
1147
1148 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
1149 return false;
1150
1151 m_client_fd = fd[0];
1152 m_server_fd = fd[1];
1153 return true;
1154}
1155
Johnny Chen25e68e32011-06-14 19:19:50 +00001156void
1157ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1158{
1159 static const char *g_thread_name = "lldb.process.linux.operation";
1160
1161 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1162 return;
1163
1164 m_operation_thread =
1165 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1166}
1167
Johnny Chen25e68e32011-06-14 19:19:50 +00001168void *
1169ProcessMonitor::AttachOpThread(void *arg)
1170{
1171 AttachArgs *args = static_cast<AttachArgs*>(arg);
1172
Greg Clayton743ecf42012-10-16 20:20:18 +00001173 if (!Attach(args)) {
1174 sem_post(&args->m_semaphore);
Johnny Chen25e68e32011-06-14 19:19:50 +00001175 return NULL;
Greg Clayton743ecf42012-10-16 20:20:18 +00001176 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001177
1178 ServeOperation(args);
1179 return NULL;
1180}
1181
1182bool
1183ProcessMonitor::Attach(AttachArgs *args)
1184{
1185 lldb::pid_t pid = args->m_pid;
1186
1187 ProcessMonitor *monitor = args->m_monitor;
1188 ProcessLinux &process = monitor->GetProcess();
Johnny Chen25e68e32011-06-14 19:19:50 +00001189 lldb::ThreadSP inferior;
Johnny Chen30213ff2012-01-05 19:17:38 +00001190 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen25e68e32011-06-14 19:19:50 +00001191
1192 if (pid <= 1)
1193 {
1194 args->m_error.SetErrorToGenericError();
1195 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1196 goto FINISH;
1197 }
1198
1199 // Attach to the requested process.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001200 if (PTRACE(PTRACE_ATTACH, pid, NULL, NULL) < 0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001201 {
1202 args->m_error.SetErrorToErrno();
1203 goto FINISH;
1204 }
1205
1206 int status;
1207 if ((status = waitpid(pid, NULL, 0)) < 0)
1208 {
1209 args->m_error.SetErrorToErrno();
1210 goto FINISH;
1211 }
1212
Greg Clayton926cce72012-10-12 16:10:12 +00001213 monitor->m_pid = pid;
1214
Johnny Chen30213ff2012-01-05 19:17:38 +00001215 // Update the process thread list with the attached thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001216 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001217 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001218 log->Printf ("ProcessMonitor::%s() adding tid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen25e68e32011-06-14 19:19:50 +00001219 process.GetThreadList().AddThread(inferior);
Johnny Chen25e68e32011-06-14 19:19:50 +00001220
1221 // Let our process instance know the thread has stopped.
1222 process.SendMessage(ProcessMessage::Trace(pid));
1223
1224 FINISH:
1225 return args->m_error.Success();
1226}
1227
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001228bool
1229ProcessMonitor::MonitorCallback(void *callback_baton,
1230 lldb::pid_t pid,
Peter Collingbourne2c67b9a2011-11-21 00:10:19 +00001231 bool exited,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001232 int signal,
1233 int status)
1234{
1235 ProcessMessage message;
1236 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
1237 ProcessLinux *process = monitor->m_process;
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001238 assert(process);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001239 bool stop_monitoring;
1240 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001241 int ptrace_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001242
Daniel Maleaa35970a2012-11-23 18:09:58 +00001243 if (!monitor->GetSignalInfo(pid, &info, ptrace_err)) {
1244 if (ptrace_err == EINVAL) {
1245 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1246 if (!monitor->Resume(pid, SIGSTOP)) {
1247 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1248 }
1249 stop_monitoring = false;
1250 } else {
1251 // ptrace(GETSIGINFO) failed (but not due to group-stop). Most likely,
1252 // this means the child pid is gone (or not being debugged) therefore
1253 // stop the monitor thread.
1254 stop_monitoring = true;
1255 }
1256 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00001257 else {
1258 switch (info.si_signo)
1259 {
1260 case SIGTRAP:
1261 message = MonitorSIGTRAP(monitor, &info, pid);
1262 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001263
Stephen Wilson84ffe702011-03-30 15:55:52 +00001264 default:
1265 message = MonitorSignal(monitor, &info, pid);
1266 break;
1267 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001268
Stephen Wilson84ffe702011-03-30 15:55:52 +00001269 process->SendMessage(message);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001270 stop_monitoring = !process->IsAlive();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001271 }
1272
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001273 return stop_monitoring;
1274}
1275
1276ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +00001277ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001278 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001279{
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001280 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001281
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001282 assert(monitor);
1283 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001284
Stephen Wilson84ffe702011-03-30 15:55:52 +00001285 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001286 {
1287 default:
1288 assert(false && "Unexpected SIGTRAP code!");
1289 break;
1290
Matt Kopec650648f2013-01-08 16:30:18 +00001291 case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1292 case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1293 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1294 {
1295 unsigned long tid = 0;
1296 if (!monitor->GetEventMessage(pid, &tid))
1297 tid = -1;
1298 message = ProcessMessage::NewThread(pid, tid);
1299 break;
1300 }
1301
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001302 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1303 {
1304 // The inferior process is about to exit. Maintain the process in a
1305 // state of "limbo" until we are explicitly commanded to detach,
1306 // destroy, resume, etc.
1307 unsigned long data = 0;
1308 if (!monitor->GetEventMessage(pid, &data))
1309 data = -1;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001310 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001311 break;
1312 }
1313
1314 case 0:
1315 case TRAP_TRACE:
1316 message = ProcessMessage::Trace(pid);
1317 break;
1318
1319 case SI_KERNEL:
1320 case TRAP_BRKPT:
1321 message = ProcessMessage::Break(pid);
1322 break;
1323 }
1324
1325 return message;
1326}
1327
Stephen Wilson84ffe702011-03-30 15:55:52 +00001328ProcessMessage
1329ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001330 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001331{
1332 ProcessMessage message;
1333 int signo = info->si_signo;
1334
1335 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1336 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1337 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1338 //
1339 // IOW, user generated signals never generate what we consider to be a
1340 // "crash".
1341 //
1342 // Similarly, ACK signals generated by this monitor.
1343 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1344 {
1345 if (info->si_pid == getpid())
1346 return ProcessMessage::SignalDelivered(pid, signo);
1347 else
1348 return ProcessMessage::Signal(pid, signo);
1349 }
1350
1351 if (signo == SIGSEGV) {
1352 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1353 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1354 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1355 }
1356
1357 if (signo == SIGILL) {
1358 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1359 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1360 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1361 }
1362
1363 if (signo == SIGFPE) {
1364 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1365 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1366 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1367 }
1368
1369 if (signo == SIGBUS) {
1370 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1371 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1372 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1373 }
1374
1375 // Everything else is "normal" and does not require any special action on
1376 // our part.
1377 return ProcessMessage::Signal(pid, signo);
1378}
1379
1380ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001381ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001382{
1383 ProcessMessage::CrashReason reason;
1384 assert(info->si_signo == SIGSEGV);
1385
1386 reason = ProcessMessage::eInvalidCrashReason;
1387
Greg Clayton542e4072012-09-07 17:49:29 +00001388 switch (info->si_code)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001389 {
1390 default:
1391 assert(false && "unexpected si_code for SIGSEGV");
1392 break;
1393 case SEGV_MAPERR:
1394 reason = ProcessMessage::eInvalidAddress;
1395 break;
1396 case SEGV_ACCERR:
1397 reason = ProcessMessage::ePrivilegedAddress;
1398 break;
1399 }
Greg Clayton542e4072012-09-07 17:49:29 +00001400
Stephen Wilson84ffe702011-03-30 15:55:52 +00001401 return reason;
1402}
1403
1404ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001405ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001406{
1407 ProcessMessage::CrashReason reason;
1408 assert(info->si_signo == SIGILL);
1409
1410 reason = ProcessMessage::eInvalidCrashReason;
1411
1412 switch (info->si_code)
1413 {
1414 default:
1415 assert(false && "unexpected si_code for SIGILL");
1416 break;
1417 case ILL_ILLOPC:
1418 reason = ProcessMessage::eIllegalOpcode;
1419 break;
1420 case ILL_ILLOPN:
1421 reason = ProcessMessage::eIllegalOperand;
1422 break;
1423 case ILL_ILLADR:
1424 reason = ProcessMessage::eIllegalAddressingMode;
1425 break;
1426 case ILL_ILLTRP:
1427 reason = ProcessMessage::eIllegalTrap;
1428 break;
1429 case ILL_PRVOPC:
1430 reason = ProcessMessage::ePrivilegedOpcode;
1431 break;
1432 case ILL_PRVREG:
1433 reason = ProcessMessage::ePrivilegedRegister;
1434 break;
1435 case ILL_COPROC:
1436 reason = ProcessMessage::eCoprocessorError;
1437 break;
1438 case ILL_BADSTK:
1439 reason = ProcessMessage::eInternalStackError;
1440 break;
1441 }
1442
1443 return reason;
1444}
1445
1446ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001447ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001448{
1449 ProcessMessage::CrashReason reason;
1450 assert(info->si_signo == SIGFPE);
1451
1452 reason = ProcessMessage::eInvalidCrashReason;
1453
1454 switch (info->si_code)
1455 {
1456 default:
1457 assert(false && "unexpected si_code for SIGFPE");
1458 break;
1459 case FPE_INTDIV:
1460 reason = ProcessMessage::eIntegerDivideByZero;
1461 break;
1462 case FPE_INTOVF:
1463 reason = ProcessMessage::eIntegerOverflow;
1464 break;
1465 case FPE_FLTDIV:
1466 reason = ProcessMessage::eFloatDivideByZero;
1467 break;
1468 case FPE_FLTOVF:
1469 reason = ProcessMessage::eFloatOverflow;
1470 break;
1471 case FPE_FLTUND:
1472 reason = ProcessMessage::eFloatUnderflow;
1473 break;
1474 case FPE_FLTRES:
1475 reason = ProcessMessage::eFloatInexactResult;
1476 break;
1477 case FPE_FLTINV:
1478 reason = ProcessMessage::eFloatInvalidOperation;
1479 break;
1480 case FPE_FLTSUB:
1481 reason = ProcessMessage::eFloatSubscriptRange;
1482 break;
1483 }
1484
1485 return reason;
1486}
1487
1488ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001489ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001490{
1491 ProcessMessage::CrashReason reason;
1492 assert(info->si_signo == SIGBUS);
1493
1494 reason = ProcessMessage::eInvalidCrashReason;
1495
1496 switch (info->si_code)
1497 {
1498 default:
1499 assert(false && "unexpected si_code for SIGBUS");
1500 break;
1501 case BUS_ADRALN:
1502 reason = ProcessMessage::eIllegalAlignment;
1503 break;
1504 case BUS_ADRERR:
1505 reason = ProcessMessage::eIllegalAddress;
1506 break;
1507 case BUS_OBJERR:
1508 reason = ProcessMessage::eHardwareError;
1509 break;
1510 }
1511
1512 return reason;
1513}
1514
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001515void
Johnny Chen25e68e32011-06-14 19:19:50 +00001516ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001517{
1518 int status;
1519 pollfd fdset;
Johnny Chen25e68e32011-06-14 19:19:50 +00001520
Stephen Wilson570243b2011-01-19 01:37:06 +00001521 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001522
1523 fdset.fd = monitor->m_server_fd;
1524 fdset.events = POLLIN | POLLPRI;
1525 fdset.revents = 0;
1526
Stephen Wilson570243b2011-01-19 01:37:06 +00001527 // We are finised with the arguments and are ready to go. Sync with the
1528 // parent thread and start serving operations on the inferior.
1529 sem_post(&args->m_semaphore);
1530
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001531 for (;;)
1532 {
1533 if ((status = poll(&fdset, 1, -1)) < 0)
1534 {
1535 switch (errno)
1536 {
1537 default:
1538 assert(false && "Unexpected poll() failure!");
1539 continue;
1540
1541 case EINTR: continue; // Just poll again.
1542 case EBADF: return; // Connection terminated.
1543 }
1544 }
1545
1546 assert(status == 1 && "Too many descriptors!");
1547
1548 if (fdset.revents & POLLIN)
1549 {
1550 Operation *op = NULL;
1551
1552 READ_AGAIN:
1553 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1554 {
1555 // There is only one acceptable failure.
1556 assert(errno == EINTR);
1557 goto READ_AGAIN;
1558 }
1559
1560 assert(status == sizeof(op));
1561 op->Execute(monitor);
1562 write(fdset.fd, &op, sizeof(op));
1563 }
1564 }
1565}
1566
1567void
1568ProcessMonitor::DoOperation(Operation *op)
1569{
1570 int status;
1571 Operation *ack = NULL;
1572 Mutex::Locker lock(m_server_mutex);
1573
1574 // FIXME: Do proper error checking here.
1575 write(m_client_fd, &op, sizeof(op));
1576
1577READ_AGAIN:
1578 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1579 {
1580 // If interrupted by a signal handler try again. Otherwise the monitor
1581 // thread probably died and we have a stale file descriptor -- abort the
1582 // operation.
1583 if (errno == EINTR)
1584 goto READ_AGAIN;
1585 return;
1586 }
1587
1588 assert(status == sizeof(ack));
1589 assert(ack == op && "Invalid monitor thread response!");
1590}
1591
1592size_t
1593ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1594 Error &error)
1595{
1596 size_t result;
1597 ReadOperation op(vm_addr, buf, size, error, result);
1598 DoOperation(&op);
1599 return result;
1600}
1601
1602size_t
1603ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1604 lldb_private::Error &error)
1605{
1606 size_t result;
1607 WriteOperation op(vm_addr, buf, size, error, result);
1608 DoOperation(&op);
1609 return result;
1610}
1611
1612bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001613ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001614{
1615 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001616 ReadRegOperation op(tid, offset, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001617 DoOperation(&op);
1618 return result;
1619}
1620
1621bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001622ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001623{
1624 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001625 WriteRegOperation op(tid, offset, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001626 DoOperation(&op);
1627 return result;
1628}
1629
1630bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001631ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001632{
1633 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001634 ReadGPROperation op(tid, buf, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001635 DoOperation(&op);
1636 return result;
1637}
1638
1639bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001640ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001641{
1642 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001643 ReadFPROperation op(tid, buf, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001644 DoOperation(&op);
1645 return result;
1646}
1647
1648bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001649ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001650{
1651 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001652 WriteGPROperation op(tid, buf, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001653 DoOperation(&op);
1654 return result;
1655}
1656
1657bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001658ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001659{
1660 bool result;
Daniel Maleaf0da3712012-12-18 19:50:15 +00001661 WriteFPROperation op(tid, buf, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001662 DoOperation(&op);
1663 return result;
1664}
1665
1666bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001667ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001668{
1669 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001670 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001671 DoOperation(&op);
1672 return result;
1673}
1674
1675bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001676ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001677{
1678 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001679 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001680 DoOperation(&op);
1681 return result;
1682}
1683
1684bool
1685ProcessMonitor::BringProcessIntoLimbo()
1686{
1687 bool result;
1688 KillOperation op(result);
1689 DoOperation(&op);
1690 return result;
1691}
1692
1693bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00001694ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001695{
1696 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001697 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001698 DoOperation(&op);
1699 return result;
1700}
1701
1702bool
1703ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1704{
1705 bool result;
1706 EventMessageOperation op(tid, message, result);
1707 DoOperation(&op);
1708 return result;
1709}
1710
Greg Clayton743ecf42012-10-16 20:20:18 +00001711lldb_private::Error
Stephen Wilson84ffe702011-03-30 15:55:52 +00001712ProcessMonitor::Detach()
1713{
Greg Clayton28041352011-11-29 20:50:10 +00001714 lldb_private::Error error;
Greg Clayton743ecf42012-10-16 20:20:18 +00001715 if (m_pid != LLDB_INVALID_PROCESS_ID) {
1716 DetachOperation op(error);
1717 DoOperation(&op);
1718 }
Greg Clayton743ecf42012-10-16 20:20:18 +00001719 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00001720}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001721
1722bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001723ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1724{
Peter Collingbourne62343202011-06-14 03:55:54 +00001725 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001726
1727 if (target_fd == -1)
1728 return false;
1729
Peter Collingbourne62343202011-06-14 03:55:54 +00001730 return (dup2(target_fd, fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001731}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001732
1733void
1734ProcessMonitor::StopMonitoringChildProcess()
1735{
1736 lldb::thread_result_t thread_result;
1737
Stephen Wilsond4182f42011-02-09 20:10:35 +00001738 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001739 {
1740 Host::ThreadCancel(m_monitor_thread, NULL);
1741 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1742 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1743 }
1744}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001745
1746void
1747ProcessMonitor::StopMonitor()
1748{
1749 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00001750 StopOpThread();
Stephen Wilson84ffe702011-03-30 15:55:52 +00001751 CloseFD(m_terminal_fd);
1752 CloseFD(m_client_fd);
1753 CloseFD(m_server_fd);
1754}
1755
1756void
Greg Clayton743ecf42012-10-16 20:20:18 +00001757ProcessMonitor::StopOpThread()
1758{
1759 lldb::thread_result_t result;
1760
1761 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1762 return;
1763
1764 Host::ThreadCancel(m_operation_thread, NULL);
1765 Host::ThreadJoin(m_operation_thread, &result, NULL);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001766 m_operation_thread = LLDB_INVALID_HOST_THREAD;
Greg Clayton743ecf42012-10-16 20:20:18 +00001767}
1768
1769void
Stephen Wilson84ffe702011-03-30 15:55:52 +00001770ProcessMonitor::CloseFD(int &fd)
1771{
1772 if (fd != -1)
1773 {
1774 close(fd);
1775 fd = -1;
1776 }
1777}