blob: 483834045cc8c0061c9270a9484576261b22ead9 [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
203 if (log)
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000204 memset(dst, 0, sizeof(unsigned char));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000205 for (unsigned i = 0; i < remainder; ++i)
206 dst[i] = ((data >> i*8) & 0xFF);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000207
Johnny Chen30213ff2012-01-05 19:17:38 +0000208 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
209 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
210 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
211 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000212 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
213 (void*)vm_addr, *(unsigned long*)dst, (unsigned long)data);
214
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000215 vm_addr += word_size;
216 dst += word_size;
217 }
218
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000219 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000220 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000221 return bytes_read;
222}
223
224static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000225DoWriteMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000226 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
227{
Greg Clayton542e4072012-09-07 17:49:29 +0000228 // ptrace word size is determined by the host, not the child
229 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000230 const unsigned char *src = static_cast<const unsigned char*>(buf);
231 size_t bytes_written = 0;
232 size_t remainder;
233
Johnny Chen30213ff2012-01-05 19:17:38 +0000234 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000235 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000236 ProcessPOSIXLog::IncNestLevel();
237 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000238 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000239 pid, word_size, (void*)vm_addr, buf, size);
240
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000241 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
242 {
243 remainder = size - bytes_written;
244 remainder = remainder > word_size ? word_size : remainder;
245
246 if (remainder == word_size)
247 {
248 unsigned long data = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000249 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000250 for (unsigned i = 0; i < word_size; ++i)
251 data |= (unsigned long)src[i] << i*8;
252
Johnny Chen30213ff2012-01-05 19:17:38 +0000253 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
254 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
255 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
256 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000257 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
258 (void*)vm_addr, *(unsigned long*)src, data);
259
260 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000261 {
262 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000263 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000264 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000265 return bytes_written;
266 }
267 }
268 else
269 {
270 unsigned char buff[8];
Greg Clayton542e4072012-09-07 17:49:29 +0000271 if (DoReadMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000272 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000273 {
274 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000275 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000276 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000277 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000278
279 memcpy(buff, src, remainder);
280
Greg Clayton542e4072012-09-07 17:49:29 +0000281 if (DoWriteMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000282 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000283 {
284 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000285 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000286 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000287 }
288
Johnny Chen30213ff2012-01-05 19:17:38 +0000289 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
290 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
291 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
292 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000293 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
294 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000295 }
296
297 vm_addr += word_size;
298 src += word_size;
299 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000300 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000301 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000302 return bytes_written;
303}
304
Stephen Wilson26977162011-03-23 02:14:42 +0000305// Simple helper function to ensure flags are enabled on the given file
306// descriptor.
307static bool
308EnsureFDFlags(int fd, int flags, Error &error)
309{
310 int status;
311
312 if ((status = fcntl(fd, F_GETFL)) == -1)
313 {
314 error.SetErrorToErrno();
315 return false;
316 }
317
318 if (fcntl(fd, F_SETFL, status | flags) == -1)
319 {
320 error.SetErrorToErrno();
321 return false;
322 }
323
324 return true;
325}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000326
327//------------------------------------------------------------------------------
328/// @class Operation
329/// @brief Represents a ProcessMonitor operation.
330///
331/// Under Linux, it is not possible to ptrace() from any other thread but the
332/// one that spawned or attached to the process from the start. Therefore, when
333/// a ProcessMonitor is asked to deliver or change the state of an inferior
334/// process the operation must be "funneled" to a specific thread to perform the
335/// task. The Operation class provides an abstract base for all services the
336/// ProcessMonitor must perform via the single virtual function Execute, thus
337/// encapsulating the code that needs to run in the privileged context.
338class Operation
339{
340public:
341 virtual void Execute(ProcessMonitor *monitor) = 0;
342};
343
344//------------------------------------------------------------------------------
345/// @class ReadOperation
346/// @brief Implements ProcessMonitor::ReadMemory.
347class ReadOperation : public Operation
348{
349public:
350 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
351 Error &error, size_t &result)
352 : m_addr(addr), m_buff(buff), m_size(size),
353 m_error(error), m_result(result)
354 { }
355
356 void Execute(ProcessMonitor *monitor);
357
358private:
359 lldb::addr_t m_addr;
360 void *m_buff;
361 size_t m_size;
362 Error &m_error;
363 size_t &m_result;
364};
365
366void
367ReadOperation::Execute(ProcessMonitor *monitor)
368{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000369 lldb::pid_t pid = monitor->GetPID();
370
Greg Clayton542e4072012-09-07 17:49:29 +0000371 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000372}
373
374//------------------------------------------------------------------------------
375/// @class ReadOperation
376/// @brief Implements ProcessMonitor::WriteMemory.
377class WriteOperation : public Operation
378{
379public:
380 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
381 Error &error, size_t &result)
382 : m_addr(addr), m_buff(buff), m_size(size),
383 m_error(error), m_result(result)
384 { }
385
386 void Execute(ProcessMonitor *monitor);
387
388private:
389 lldb::addr_t m_addr;
390 const void *m_buff;
391 size_t m_size;
392 Error &m_error;
393 size_t &m_result;
394};
395
396void
397WriteOperation::Execute(ProcessMonitor *monitor)
398{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000399 lldb::pid_t pid = monitor->GetPID();
400
Greg Clayton542e4072012-09-07 17:49:29 +0000401 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000402}
403
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000404
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000405//------------------------------------------------------------------------------
406/// @class ReadRegOperation
407/// @brief Implements ProcessMonitor::ReadRegisterValue.
408class ReadRegOperation : public Operation
409{
410public:
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000411 ReadRegOperation(unsigned offset, RegisterValue &value, bool &result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000412 : m_offset(offset), m_value(value), m_result(result)
413 { }
414
415 void Execute(ProcessMonitor *monitor);
416
417private:
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000418 uintptr_t m_offset;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000419 RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000420 bool &m_result;
421};
422
423void
424ReadRegOperation::Execute(ProcessMonitor *monitor)
425{
426 lldb::pid_t pid = monitor->GetPID();
Johnny Chen30213ff2012-01-05 19:17:38 +0000427 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000428
429 // Set errno to zero so that we can detect a failed peek.
430 errno = 0;
Greg Clayton386ff182011-11-05 01:09:16 +0000431 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, pid, (void*)m_offset, NULL);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000432 if (data == -1UL && errno)
433 m_result = false;
434 else
435 {
436 m_value = data;
437 m_result = true;
438 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000439 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000440 log->Printf ("ProcessMonitor::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
Johnny Chen30213ff2012-01-05 19:17:38 +0000441 POSIXThread::GetRegisterNameFromOffset(m_offset), data);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000442}
443
444//------------------------------------------------------------------------------
445/// @class WriteRegOperation
446/// @brief Implements ProcessMonitor::WriteRegisterValue.
447class WriteRegOperation : public Operation
448{
449public:
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000450 WriteRegOperation(unsigned offset, const RegisterValue &value, bool &result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000451 : m_offset(offset), m_value(value), m_result(result)
452 { }
453
454 void Execute(ProcessMonitor *monitor);
455
456private:
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000457 uintptr_t m_offset;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000458 const RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000459 bool &m_result;
460};
461
462void
463WriteRegOperation::Execute(ProcessMonitor *monitor)
464{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000465 void* buf;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000466 lldb::pid_t pid = monitor->GetPID();
Johnny Chen30213ff2012-01-05 19:17:38 +0000467 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000468
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000469#if __WORDSIZE == 32
470 buf = (void*) m_value.GetAsUInt32();
471#else
472 buf = (void*) m_value.GetAsUInt64();
473#endif
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000474
475 if (log)
476 log->Printf ("ProcessMonitor::%s() reg %s: %p", __FUNCTION__,
Johnny Chen30213ff2012-01-05 19:17:38 +0000477 POSIXThread::GetRegisterNameFromOffset(m_offset), buf);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000478 if (PTRACE(PTRACE_POKEUSER, pid, (void*)m_offset, buf))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000479 m_result = false;
480 else
481 m_result = true;
482}
483
484//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000485/// @class ReadGPROperation
486/// @brief Implements ProcessMonitor::ReadGPR.
487class ReadGPROperation : public Operation
488{
489public:
490 ReadGPROperation(void *buf, bool &result)
491 : m_buf(buf), m_result(result)
492 { }
493
494 void Execute(ProcessMonitor *monitor);
495
496private:
497 void *m_buf;
498 bool &m_result;
499};
500
501void
502ReadGPROperation::Execute(ProcessMonitor *monitor)
503{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000504 if (PTRACE(PTRACE_GETREGS, monitor->GetPID(), NULL, m_buf) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000505 m_result = false;
506 else
507 m_result = true;
508}
509
510//------------------------------------------------------------------------------
511/// @class ReadFPROperation
512/// @brief Implements ProcessMonitor::ReadFPR.
513class ReadFPROperation : public Operation
514{
515public:
516 ReadFPROperation(void *buf, bool &result)
517 : m_buf(buf), m_result(result)
518 { }
519
520 void Execute(ProcessMonitor *monitor);
521
522private:
523 void *m_buf;
524 bool &m_result;
525};
526
527void
528ReadFPROperation::Execute(ProcessMonitor *monitor)
529{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000530 if (PTRACE(PTRACE_GETFPREGS, monitor->GetPID(), NULL, m_buf) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000531 m_result = false;
532 else
533 m_result = true;
534}
535
536//------------------------------------------------------------------------------
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000537/// @class WriteGPROperation
538/// @brief Implements ProcessMonitor::WriteGPR.
539class WriteGPROperation : public Operation
540{
541public:
542 WriteGPROperation(void *buf, bool &result)
543 : m_buf(buf), m_result(result)
544 { }
545
546 void Execute(ProcessMonitor *monitor);
547
548private:
549 void *m_buf;
550 bool &m_result;
551};
552
553void
554WriteGPROperation::Execute(ProcessMonitor *monitor)
555{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000556 if (PTRACE(PTRACE_SETREGS, monitor->GetPID(), NULL, m_buf) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000557 m_result = false;
558 else
559 m_result = true;
560}
561
562//------------------------------------------------------------------------------
563/// @class WriteFPROperation
564/// @brief Implements ProcessMonitor::WriteFPR.
565class WriteFPROperation : public Operation
566{
567public:
568 WriteFPROperation(void *buf, bool &result)
569 : m_buf(buf), m_result(result)
570 { }
571
572 void Execute(ProcessMonitor *monitor);
573
574private:
575 void *m_buf;
576 bool &m_result;
577};
578
579void
580WriteFPROperation::Execute(ProcessMonitor *monitor)
581{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000582 if (PTRACE(PTRACE_SETFPREGS, monitor->GetPID(), NULL, m_buf) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000583 m_result = false;
584 else
585 m_result = true;
586}
587
588//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000589/// @class ResumeOperation
590/// @brief Implements ProcessMonitor::Resume.
591class ResumeOperation : public Operation
592{
593public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000594 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
595 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000596
597 void Execute(ProcessMonitor *monitor);
598
599private:
600 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000601 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000602 bool &m_result;
603};
604
605void
606ResumeOperation::Execute(ProcessMonitor *monitor)
607{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000608 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000609
610 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
611 data = m_signo;
612
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000613 if (PTRACE(PTRACE_CONT, m_tid, NULL, (void*)data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000614 m_result = false;
615 else
616 m_result = true;
617}
618
619//------------------------------------------------------------------------------
620/// @class ResumeOperation
621/// @brief Implements ProcessMonitor::SingleStep.
622class SingleStepOperation : public Operation
623{
624public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000625 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
626 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000627
628 void Execute(ProcessMonitor *monitor);
629
630private:
631 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000632 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000633 bool &m_result;
634};
635
636void
637SingleStepOperation::Execute(ProcessMonitor *monitor)
638{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000639 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000640
641 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
642 data = m_signo;
643
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000644 if (PTRACE(PTRACE_SINGLESTEP, m_tid, NULL, (void*)data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000645 m_result = false;
646 else
647 m_result = true;
648}
649
650//------------------------------------------------------------------------------
651/// @class SiginfoOperation
652/// @brief Implements ProcessMonitor::GetSignalInfo.
653class SiginfoOperation : public Operation
654{
655public:
Daniel Maleaa35970a2012-11-23 18:09:58 +0000656 SiginfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
657 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000658
659 void Execute(ProcessMonitor *monitor);
660
661private:
662 lldb::tid_t m_tid;
663 void *m_info;
664 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000665 int &m_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000666};
667
668void
669SiginfoOperation::Execute(ProcessMonitor *monitor)
670{
Daniel Maleaa35970a2012-11-23 18:09:58 +0000671 if (PTRACE(PTRACE_GETSIGINFO, m_tid, NULL, m_info)) {
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000672 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000673 m_err = errno;
674 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000675 else
676 m_result = true;
677}
678
679//------------------------------------------------------------------------------
680/// @class EventMessageOperation
681/// @brief Implements ProcessMonitor::GetEventMessage.
682class EventMessageOperation : public Operation
683{
684public:
685 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
686 : m_tid(tid), m_message(message), m_result(result) { }
687
688 void Execute(ProcessMonitor *monitor);
689
690private:
691 lldb::tid_t m_tid;
692 unsigned long *m_message;
693 bool &m_result;
694};
695
696void
697EventMessageOperation::Execute(ProcessMonitor *monitor)
698{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000699 if (PTRACE(PTRACE_GETEVENTMSG, m_tid, NULL, m_message))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000700 m_result = false;
701 else
702 m_result = true;
703}
704
705//------------------------------------------------------------------------------
706/// @class KillOperation
707/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
708class KillOperation : public Operation
709{
710public:
711 KillOperation(bool &result) : m_result(result) { }
712
713 void Execute(ProcessMonitor *monitor);
714
715private:
716 bool &m_result;
717};
718
719void
720KillOperation::Execute(ProcessMonitor *monitor)
721{
722 lldb::pid_t pid = monitor->GetPID();
723
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000724 if (PTRACE(PTRACE_KILL, pid, NULL, NULL))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000725 m_result = false;
726 else
727 m_result = true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000728}
729
Greg Clayton28041352011-11-29 20:50:10 +0000730//------------------------------------------------------------------------------
731/// @class KillOperation
732/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
733class DetachOperation : public Operation
734{
735public:
736 DetachOperation(Error &result) : m_error(result) { }
737
738 void Execute(ProcessMonitor *monitor);
739
740private:
741 Error &m_error;
742};
743
744void
745DetachOperation::Execute(ProcessMonitor *monitor)
746{
747 lldb::pid_t pid = monitor->GetPID();
748
749 if (ptrace(PT_DETACH, pid, NULL, 0) < 0)
750 m_error.SetErrorToErrno();
Greg Clayton542e4072012-09-07 17:49:29 +0000751
Greg Clayton28041352011-11-29 20:50:10 +0000752}
753
Johnny Chen25e68e32011-06-14 19:19:50 +0000754ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
755 : m_monitor(monitor)
756{
757 sem_init(&m_semaphore, 0, 0);
758}
759
760ProcessMonitor::OperationArgs::~OperationArgs()
761{
762 sem_destroy(&m_semaphore);
763}
764
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000765ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
766 lldb_private::Module *module,
767 char const **argv,
768 char const **envp,
769 const char *stdin_path,
770 const char *stdout_path,
771 const char *stderr_path)
Johnny Chen25e68e32011-06-14 19:19:50 +0000772 : OperationArgs(monitor),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000773 m_module(module),
774 m_argv(argv),
775 m_envp(envp),
776 m_stdin_path(stdin_path),
777 m_stdout_path(stdout_path),
Johnny Chen25e68e32011-06-14 19:19:50 +0000778 m_stderr_path(stderr_path) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000779
780ProcessMonitor::LaunchArgs::~LaunchArgs()
Johnny Chen25e68e32011-06-14 19:19:50 +0000781{ }
782
783ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
784 lldb::pid_t pid)
785 : OperationArgs(monitor), m_pid(pid) { }
786
787ProcessMonitor::AttachArgs::~AttachArgs()
788{ }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000789
790//------------------------------------------------------------------------------
791/// The basic design of the ProcessMonitor is built around two threads.
792///
793/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
794/// for changes in the debugee state. When a change is detected a
795/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
796/// "drives" state changes in the debugger.
797///
798/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000799/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000800/// operations such as register reads/writes, stepping, etc. See the comments
801/// on the Operation class for more info as to why this is needed.
Johnny Chen30213ff2012-01-05 19:17:38 +0000802ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000803 Module *module,
804 const char *argv[],
805 const char *envp[],
806 const char *stdin_path,
807 const char *stdout_path,
808 const char *stderr_path,
809 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000810 : m_process(static_cast<ProcessLinux *>(process)),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000811 m_operation_thread(LLDB_INVALID_HOST_THREAD),
812 m_pid(LLDB_INVALID_PROCESS_ID),
813 m_terminal_fd(-1),
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000814 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000815 m_client_fd(-1),
816 m_server_fd(-1)
817{
Stephen Wilson57740ec2011-01-15 00:12:41 +0000818 std::auto_ptr<LaunchArgs> args;
819
820 args.reset(new LaunchArgs(this, module, argv, envp,
821 stdin_path, stdout_path, stderr_path));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000822
823 // Server/client descriptors.
824 if (!EnableIPC())
825 {
826 error.SetErrorToGenericError();
827 error.SetErrorString("Monitor failed to initialize.");
828 }
829
Johnny Chen25e68e32011-06-14 19:19:50 +0000830 StartLaunchOpThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000831 if (!error.Success())
832 return;
833
834WAIT_AGAIN:
835 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000836 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000837 {
838 if (errno == EINTR)
839 goto WAIT_AGAIN;
840 else
841 {
842 error.SetErrorToErrno();
843 return;
844 }
845 }
846
847 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000848 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000849 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000850 StopOpThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000851 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000852 return;
853 }
854
855 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000856 m_monitor_thread = Host::StartMonitoringChildProcess(
857 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Stephen Wilsond4182f42011-02-09 20:10:35 +0000858 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000859 {
860 error.SetErrorToGenericError();
861 error.SetErrorString("Process launch failed.");
862 return;
863 }
864}
865
Johnny Chen30213ff2012-01-05 19:17:38 +0000866ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen25e68e32011-06-14 19:19:50 +0000867 lldb::pid_t pid,
868 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000869 : m_process(static_cast<ProcessLinux *>(process)),
Johnny Chen25e68e32011-06-14 19:19:50 +0000870 m_operation_thread(LLDB_INVALID_HOST_THREAD),
871 m_pid(LLDB_INVALID_PROCESS_ID),
872 m_terminal_fd(-1),
873 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
874 m_client_fd(-1),
875 m_server_fd(-1)
876{
877 std::auto_ptr<AttachArgs> args;
878
879 args.reset(new AttachArgs(this, pid));
880
881 // Server/client descriptors.
882 if (!EnableIPC())
883 {
884 error.SetErrorToGenericError();
885 error.SetErrorString("Monitor failed to initialize.");
886 }
887
888 StartAttachOpThread(args.get(), error);
889 if (!error.Success())
890 return;
891
892WAIT_AGAIN:
893 // Wait for the operation thread to initialize.
894 if (sem_wait(&args->m_semaphore))
895 {
896 if (errno == EINTR)
897 goto WAIT_AGAIN;
898 else
899 {
900 error.SetErrorToErrno();
901 return;
902 }
903 }
904
Greg Clayton743ecf42012-10-16 20:20:18 +0000905 // Check that the attach was a success.
Johnny Chen25e68e32011-06-14 19:19:50 +0000906 if (!args->m_error.Success())
907 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000908 StopOpThread();
Johnny Chen25e68e32011-06-14 19:19:50 +0000909 error = args->m_error;
910 return;
911 }
912
913 // Finally, start monitoring the child process for change in state.
914 m_monitor_thread = Host::StartMonitoringChildProcess(
915 ProcessMonitor::MonitorCallback, this, GetPID(), true);
916 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
917 {
918 error.SetErrorToGenericError();
919 error.SetErrorString("Process attach failed.");
920 return;
921 }
922}
923
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000924ProcessMonitor::~ProcessMonitor()
925{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000926 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000927}
928
929//------------------------------------------------------------------------------
930// Thread setup and tear down.
931void
Johnny Chen25e68e32011-06-14 19:19:50 +0000932ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000933{
934 static const char *g_thread_name = "lldb.process.linux.operation";
935
Stephen Wilsond4182f42011-02-09 20:10:35 +0000936 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000937 return;
938
939 m_operation_thread =
Johnny Chen25e68e32011-06-14 19:19:50 +0000940 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000941}
942
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000943void *
Johnny Chen25e68e32011-06-14 19:19:50 +0000944ProcessMonitor::LaunchOpThread(void *arg)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000945{
946 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
947
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +0000948 if (!Launch(args)) {
949 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000950 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +0000951 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000952
Stephen Wilson570243b2011-01-19 01:37:06 +0000953 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000954 return NULL;
955}
956
957bool
958ProcessMonitor::Launch(LaunchArgs *args)
959{
960 ProcessMonitor *monitor = args->m_monitor;
961 ProcessLinux &process = monitor->GetProcess();
962 const char **argv = args->m_argv;
963 const char **envp = args->m_envp;
964 const char *stdin_path = args->m_stdin_path;
965 const char *stdout_path = args->m_stdout_path;
966 const char *stderr_path = args->m_stderr_path;
967
968 lldb_utility::PseudoTerminal terminal;
969 const size_t err_len = 1024;
970 char err_str[err_len];
971 lldb::pid_t pid;
972
973 lldb::ThreadSP inferior;
Johnny Chen30213ff2012-01-05 19:17:38 +0000974 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000975
Stephen Wilson57740ec2011-01-15 00:12:41 +0000976 // Propagate the environment if one is not supplied.
977 if (envp == NULL || envp[0] == NULL)
978 envp = const_cast<const char **>(environ);
979
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000980 // Pseudo terminal setup.
981 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
982 {
983 args->m_error.SetErrorToGenericError();
984 args->m_error.SetErrorString("Could not open controlling TTY.");
985 goto FINISH;
986 }
987
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000988 if ((pid = terminal.Fork(err_str, err_len)) == -1)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000989 {
990 args->m_error.SetErrorToGenericError();
991 args->m_error.SetErrorString("Process fork failed.");
992 goto FINISH;
993 }
994
Peter Collingbourne6a520222011-06-14 03:55:58 +0000995 // Recognized child exit status codes.
996 enum {
997 ePtraceFailed = 1,
998 eDupStdinFailed,
999 eDupStdoutFailed,
1000 eDupStderrFailed,
1001 eExecFailed
1002 };
1003
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001004 // Child process.
1005 if (pid == 0)
1006 {
1007 // Trace this process.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001008 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL) < 0)
Peter Collingbourne6a520222011-06-14 03:55:58 +00001009 exit(ePtraceFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001010
1011 // Do not inherit setgid powers.
1012 setgid(getgid());
1013
1014 // Let us have our own process group.
1015 setpgid(0, 0);
1016
Greg Clayton710dd5a2011-01-08 20:28:42 +00001017 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001018 //
1019 // FIXME: If two or more of the paths are the same we needlessly open
1020 // the same file multiple times.
1021 if (stdin_path != NULL && stdin_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001022 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001023 exit(eDupStdinFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001024
1025 if (stdout_path != NULL && stdout_path[0])
1026 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001027 exit(eDupStdoutFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001028
1029 if (stderr_path != NULL && stderr_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001030 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001031 exit(eDupStderrFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001032
1033 // Execute. We should never return.
1034 execve(argv[0],
1035 const_cast<char *const *>(argv),
1036 const_cast<char *const *>(envp));
Peter Collingbourne6a520222011-06-14 03:55:58 +00001037 exit(eExecFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001038 }
1039
1040 // Wait for the child process to to trap on its call to execve.
Peter Collingbourne6a520222011-06-14 03:55:58 +00001041 pid_t wpid;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001042 int status;
Peter Collingbourne6a520222011-06-14 03:55:58 +00001043 if ((wpid = waitpid(pid, &status, 0)) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001044 {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001045 args->m_error.SetErrorToErrno();
1046 goto FINISH;
1047 }
Peter Collingbourne6a520222011-06-14 03:55:58 +00001048 else if (WIFEXITED(status))
1049 {
1050 // open, dup or execve likely failed for some reason.
1051 args->m_error.SetErrorToGenericError();
1052 switch (WEXITSTATUS(status))
1053 {
Greg Clayton542e4072012-09-07 17:49:29 +00001054 case ePtraceFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001055 args->m_error.SetErrorString("Child ptrace failed.");
1056 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001057 case eDupStdinFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001058 args->m_error.SetErrorString("Child open stdin failed.");
1059 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001060 case eDupStdoutFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001061 args->m_error.SetErrorString("Child open stdout failed.");
1062 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001063 case eDupStderrFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001064 args->m_error.SetErrorString("Child open stderr failed.");
1065 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001066 case eExecFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001067 args->m_error.SetErrorString("Child exec failed.");
1068 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001069 default:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001070 args->m_error.SetErrorString("Child returned unknown exit status.");
1071 break;
1072 }
1073 goto FINISH;
1074 }
1075 assert(WIFSTOPPED(status) && wpid == pid &&
1076 "Could not sync with inferior process.");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001077
1078 // Have the child raise an event on exit. This is used to keep the child in
1079 // limbo until it is destroyed.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001080 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)PTRACE_O_TRACEEXIT) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001081 {
1082 args->m_error.SetErrorToErrno();
1083 goto FINISH;
1084 }
1085
1086 // Release the master terminal descriptor and pass it off to the
1087 // ProcessMonitor instance. Similarly stash the inferior pid.
1088 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1089 monitor->m_pid = pid;
1090
Stephen Wilson26977162011-03-23 02:14:42 +00001091 // Set the terminal fd to be in non blocking mode (it simplifies the
1092 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1093 // descriptor to read from).
1094 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1095 goto FINISH;
1096
Johnny Chen30213ff2012-01-05 19:17:38 +00001097 // Update the process thread list with this new thread.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001098 // FIXME: should we be letting UpdateThreadList handle this?
1099 // FIXME: by using pids instead of tids, we can only support one thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001100 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001101 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001102 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001103 process.GetThreadList().AddThread(inferior);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001104
1105 // Let our process instance know the thread has stopped.
1106 process.SendMessage(ProcessMessage::Trace(pid));
1107
1108FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001109 return args->m_error.Success();
1110}
1111
1112bool
1113ProcessMonitor::EnableIPC()
1114{
1115 int fd[2];
1116
1117 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
1118 return false;
1119
1120 m_client_fd = fd[0];
1121 m_server_fd = fd[1];
1122 return true;
1123}
1124
Johnny Chen25e68e32011-06-14 19:19:50 +00001125void
1126ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1127{
1128 static const char *g_thread_name = "lldb.process.linux.operation";
1129
1130 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1131 return;
1132
1133 m_operation_thread =
1134 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1135}
1136
Johnny Chen25e68e32011-06-14 19:19:50 +00001137void *
1138ProcessMonitor::AttachOpThread(void *arg)
1139{
1140 AttachArgs *args = static_cast<AttachArgs*>(arg);
1141
Greg Clayton743ecf42012-10-16 20:20:18 +00001142 if (!Attach(args)) {
1143 sem_post(&args->m_semaphore);
Johnny Chen25e68e32011-06-14 19:19:50 +00001144 return NULL;
Greg Clayton743ecf42012-10-16 20:20:18 +00001145 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001146
1147 ServeOperation(args);
1148 return NULL;
1149}
1150
1151bool
1152ProcessMonitor::Attach(AttachArgs *args)
1153{
1154 lldb::pid_t pid = args->m_pid;
1155
1156 ProcessMonitor *monitor = args->m_monitor;
1157 ProcessLinux &process = monitor->GetProcess();
Johnny Chen25e68e32011-06-14 19:19:50 +00001158 lldb::ThreadSP inferior;
Johnny Chen30213ff2012-01-05 19:17:38 +00001159 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen25e68e32011-06-14 19:19:50 +00001160
1161 if (pid <= 1)
1162 {
1163 args->m_error.SetErrorToGenericError();
1164 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1165 goto FINISH;
1166 }
1167
1168 // Attach to the requested process.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001169 if (PTRACE(PTRACE_ATTACH, pid, NULL, NULL) < 0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001170 {
1171 args->m_error.SetErrorToErrno();
1172 goto FINISH;
1173 }
1174
1175 int status;
1176 if ((status = waitpid(pid, NULL, 0)) < 0)
1177 {
1178 args->m_error.SetErrorToErrno();
1179 goto FINISH;
1180 }
1181
Greg Clayton926cce72012-10-12 16:10:12 +00001182 monitor->m_pid = pid;
1183
Johnny Chen30213ff2012-01-05 19:17:38 +00001184 // Update the process thread list with the attached thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001185 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001186 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001187 log->Printf ("ProcessMonitor::%s() adding tid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen25e68e32011-06-14 19:19:50 +00001188 process.GetThreadList().AddThread(inferior);
Johnny Chen25e68e32011-06-14 19:19:50 +00001189
1190 // Let our process instance know the thread has stopped.
1191 process.SendMessage(ProcessMessage::Trace(pid));
1192
1193 FINISH:
1194 return args->m_error.Success();
1195}
1196
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001197bool
1198ProcessMonitor::MonitorCallback(void *callback_baton,
1199 lldb::pid_t pid,
Peter Collingbourne2c67b9a2011-11-21 00:10:19 +00001200 bool exited,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001201 int signal,
1202 int status)
1203{
1204 ProcessMessage message;
1205 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
1206 ProcessLinux *process = monitor->m_process;
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001207 assert(process);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001208 bool stop_monitoring;
1209 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001210 int ptrace_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001211
Daniel Maleaa35970a2012-11-23 18:09:58 +00001212 if (!monitor->GetSignalInfo(pid, &info, ptrace_err)) {
1213 if (ptrace_err == EINVAL) {
1214 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1215 if (!monitor->Resume(pid, SIGSTOP)) {
1216 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1217 }
1218 stop_monitoring = false;
1219 } else {
1220 // ptrace(GETSIGINFO) failed (but not due to group-stop). Most likely,
1221 // this means the child pid is gone (or not being debugged) therefore
1222 // stop the monitor thread.
1223 stop_monitoring = true;
1224 }
1225 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00001226 else {
1227 switch (info.si_signo)
1228 {
1229 case SIGTRAP:
1230 message = MonitorSIGTRAP(monitor, &info, pid);
1231 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001232
Stephen Wilson84ffe702011-03-30 15:55:52 +00001233 default:
1234 message = MonitorSignal(monitor, &info, pid);
1235 break;
1236 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001237
Stephen Wilson84ffe702011-03-30 15:55:52 +00001238 process->SendMessage(message);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001239 stop_monitoring = !process->IsAlive();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001240 }
1241
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001242 return stop_monitoring;
1243}
1244
1245ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +00001246ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001247 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001248{
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001249 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001250
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001251 assert(monitor);
1252 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001253
Stephen Wilson84ffe702011-03-30 15:55:52 +00001254 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001255 {
1256 default:
1257 assert(false && "Unexpected SIGTRAP code!");
1258 break;
1259
1260 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1261 {
1262 // The inferior process is about to exit. Maintain the process in a
1263 // state of "limbo" until we are explicitly commanded to detach,
1264 // destroy, resume, etc.
1265 unsigned long data = 0;
1266 if (!monitor->GetEventMessage(pid, &data))
1267 data = -1;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001268 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001269 break;
1270 }
1271
1272 case 0:
1273 case TRAP_TRACE:
1274 message = ProcessMessage::Trace(pid);
1275 break;
1276
1277 case SI_KERNEL:
1278 case TRAP_BRKPT:
1279 message = ProcessMessage::Break(pid);
1280 break;
1281 }
1282
1283 return message;
1284}
1285
Stephen Wilson84ffe702011-03-30 15:55:52 +00001286ProcessMessage
1287ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001288 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001289{
1290 ProcessMessage message;
1291 int signo = info->si_signo;
1292
1293 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1294 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1295 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1296 //
1297 // IOW, user generated signals never generate what we consider to be a
1298 // "crash".
1299 //
1300 // Similarly, ACK signals generated by this monitor.
1301 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1302 {
1303 if (info->si_pid == getpid())
1304 return ProcessMessage::SignalDelivered(pid, signo);
1305 else
1306 return ProcessMessage::Signal(pid, signo);
1307 }
1308
1309 if (signo == SIGSEGV) {
1310 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1311 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1312 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1313 }
1314
1315 if (signo == SIGILL) {
1316 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1317 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1318 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1319 }
1320
1321 if (signo == SIGFPE) {
1322 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1323 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1324 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1325 }
1326
1327 if (signo == SIGBUS) {
1328 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1329 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1330 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1331 }
1332
1333 // Everything else is "normal" and does not require any special action on
1334 // our part.
1335 return ProcessMessage::Signal(pid, signo);
1336}
1337
1338ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001339ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001340{
1341 ProcessMessage::CrashReason reason;
1342 assert(info->si_signo == SIGSEGV);
1343
1344 reason = ProcessMessage::eInvalidCrashReason;
1345
Greg Clayton542e4072012-09-07 17:49:29 +00001346 switch (info->si_code)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001347 {
1348 default:
1349 assert(false && "unexpected si_code for SIGSEGV");
1350 break;
1351 case SEGV_MAPERR:
1352 reason = ProcessMessage::eInvalidAddress;
1353 break;
1354 case SEGV_ACCERR:
1355 reason = ProcessMessage::ePrivilegedAddress;
1356 break;
1357 }
Greg Clayton542e4072012-09-07 17:49:29 +00001358
Stephen Wilson84ffe702011-03-30 15:55:52 +00001359 return reason;
1360}
1361
1362ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001363ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001364{
1365 ProcessMessage::CrashReason reason;
1366 assert(info->si_signo == SIGILL);
1367
1368 reason = ProcessMessage::eInvalidCrashReason;
1369
1370 switch (info->si_code)
1371 {
1372 default:
1373 assert(false && "unexpected si_code for SIGILL");
1374 break;
1375 case ILL_ILLOPC:
1376 reason = ProcessMessage::eIllegalOpcode;
1377 break;
1378 case ILL_ILLOPN:
1379 reason = ProcessMessage::eIllegalOperand;
1380 break;
1381 case ILL_ILLADR:
1382 reason = ProcessMessage::eIllegalAddressingMode;
1383 break;
1384 case ILL_ILLTRP:
1385 reason = ProcessMessage::eIllegalTrap;
1386 break;
1387 case ILL_PRVOPC:
1388 reason = ProcessMessage::ePrivilegedOpcode;
1389 break;
1390 case ILL_PRVREG:
1391 reason = ProcessMessage::ePrivilegedRegister;
1392 break;
1393 case ILL_COPROC:
1394 reason = ProcessMessage::eCoprocessorError;
1395 break;
1396 case ILL_BADSTK:
1397 reason = ProcessMessage::eInternalStackError;
1398 break;
1399 }
1400
1401 return reason;
1402}
1403
1404ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001405ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001406{
1407 ProcessMessage::CrashReason reason;
1408 assert(info->si_signo == SIGFPE);
1409
1410 reason = ProcessMessage::eInvalidCrashReason;
1411
1412 switch (info->si_code)
1413 {
1414 default:
1415 assert(false && "unexpected si_code for SIGFPE");
1416 break;
1417 case FPE_INTDIV:
1418 reason = ProcessMessage::eIntegerDivideByZero;
1419 break;
1420 case FPE_INTOVF:
1421 reason = ProcessMessage::eIntegerOverflow;
1422 break;
1423 case FPE_FLTDIV:
1424 reason = ProcessMessage::eFloatDivideByZero;
1425 break;
1426 case FPE_FLTOVF:
1427 reason = ProcessMessage::eFloatOverflow;
1428 break;
1429 case FPE_FLTUND:
1430 reason = ProcessMessage::eFloatUnderflow;
1431 break;
1432 case FPE_FLTRES:
1433 reason = ProcessMessage::eFloatInexactResult;
1434 break;
1435 case FPE_FLTINV:
1436 reason = ProcessMessage::eFloatInvalidOperation;
1437 break;
1438 case FPE_FLTSUB:
1439 reason = ProcessMessage::eFloatSubscriptRange;
1440 break;
1441 }
1442
1443 return reason;
1444}
1445
1446ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001447ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001448{
1449 ProcessMessage::CrashReason reason;
1450 assert(info->si_signo == SIGBUS);
1451
1452 reason = ProcessMessage::eInvalidCrashReason;
1453
1454 switch (info->si_code)
1455 {
1456 default:
1457 assert(false && "unexpected si_code for SIGBUS");
1458 break;
1459 case BUS_ADRALN:
1460 reason = ProcessMessage::eIllegalAlignment;
1461 break;
1462 case BUS_ADRERR:
1463 reason = ProcessMessage::eIllegalAddress;
1464 break;
1465 case BUS_OBJERR:
1466 reason = ProcessMessage::eHardwareError;
1467 break;
1468 }
1469
1470 return reason;
1471}
1472
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001473void
Johnny Chen25e68e32011-06-14 19:19:50 +00001474ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001475{
1476 int status;
1477 pollfd fdset;
Johnny Chen25e68e32011-06-14 19:19:50 +00001478
Stephen Wilson570243b2011-01-19 01:37:06 +00001479 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001480
1481 fdset.fd = monitor->m_server_fd;
1482 fdset.events = POLLIN | POLLPRI;
1483 fdset.revents = 0;
1484
Stephen Wilson570243b2011-01-19 01:37:06 +00001485 // We are finised with the arguments and are ready to go. Sync with the
1486 // parent thread and start serving operations on the inferior.
1487 sem_post(&args->m_semaphore);
1488
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001489 for (;;)
1490 {
1491 if ((status = poll(&fdset, 1, -1)) < 0)
1492 {
1493 switch (errno)
1494 {
1495 default:
1496 assert(false && "Unexpected poll() failure!");
1497 continue;
1498
1499 case EINTR: continue; // Just poll again.
1500 case EBADF: return; // Connection terminated.
1501 }
1502 }
1503
1504 assert(status == 1 && "Too many descriptors!");
1505
1506 if (fdset.revents & POLLIN)
1507 {
1508 Operation *op = NULL;
1509
1510 READ_AGAIN:
1511 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1512 {
1513 // There is only one acceptable failure.
1514 assert(errno == EINTR);
1515 goto READ_AGAIN;
1516 }
1517
1518 assert(status == sizeof(op));
1519 op->Execute(monitor);
1520 write(fdset.fd, &op, sizeof(op));
1521 }
1522 }
1523}
1524
1525void
1526ProcessMonitor::DoOperation(Operation *op)
1527{
1528 int status;
1529 Operation *ack = NULL;
1530 Mutex::Locker lock(m_server_mutex);
1531
1532 // FIXME: Do proper error checking here.
1533 write(m_client_fd, &op, sizeof(op));
1534
1535READ_AGAIN:
1536 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1537 {
1538 // If interrupted by a signal handler try again. Otherwise the monitor
1539 // thread probably died and we have a stale file descriptor -- abort the
1540 // operation.
1541 if (errno == EINTR)
1542 goto READ_AGAIN;
1543 return;
1544 }
1545
1546 assert(status == sizeof(ack));
1547 assert(ack == op && "Invalid monitor thread response!");
1548}
1549
1550size_t
1551ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1552 Error &error)
1553{
1554 size_t result;
1555 ReadOperation op(vm_addr, buf, size, error, result);
1556 DoOperation(&op);
1557 return result;
1558}
1559
1560size_t
1561ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1562 lldb_private::Error &error)
1563{
1564 size_t result;
1565 WriteOperation op(vm_addr, buf, size, error, result);
1566 DoOperation(&op);
1567 return result;
1568}
1569
1570bool
Johnny Chen30213ff2012-01-05 19:17:38 +00001571ProcessMonitor::ReadRegisterValue(unsigned offset, unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001572{
1573 bool result;
1574 ReadRegOperation op(offset, value, result);
1575 DoOperation(&op);
1576 return result;
1577}
1578
1579bool
Johnny Chen13e8e1c2011-05-13 21:29:50 +00001580ProcessMonitor::WriteRegisterValue(unsigned offset, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001581{
1582 bool result;
1583 WriteRegOperation op(offset, value, result);
1584 DoOperation(&op);
1585 return result;
1586}
1587
1588bool
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001589ProcessMonitor::ReadGPR(void *buf)
1590{
1591 bool result;
1592 ReadGPROperation op(buf, result);
1593 DoOperation(&op);
1594 return result;
1595}
1596
1597bool
1598ProcessMonitor::ReadFPR(void *buf)
1599{
1600 bool result;
1601 ReadFPROperation op(buf, result);
1602 DoOperation(&op);
1603 return result;
1604}
1605
1606bool
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001607ProcessMonitor::WriteGPR(void *buf)
1608{
1609 bool result;
1610 WriteGPROperation op(buf, result);
1611 DoOperation(&op);
1612 return result;
1613}
1614
1615bool
1616ProcessMonitor::WriteFPR(void *buf)
1617{
1618 bool result;
1619 WriteFPROperation op(buf, result);
1620 DoOperation(&op);
1621 return result;
1622}
1623
1624bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001625ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001626{
1627 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001628 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001629 DoOperation(&op);
1630 return result;
1631}
1632
1633bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001634ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001635{
1636 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001637 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001638 DoOperation(&op);
1639 return result;
1640}
1641
1642bool
1643ProcessMonitor::BringProcessIntoLimbo()
1644{
1645 bool result;
1646 KillOperation op(result);
1647 DoOperation(&op);
1648 return result;
1649}
1650
1651bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00001652ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001653{
1654 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001655 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001656 DoOperation(&op);
1657 return result;
1658}
1659
1660bool
1661ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1662{
1663 bool result;
1664 EventMessageOperation op(tid, message, result);
1665 DoOperation(&op);
1666 return result;
1667}
1668
Greg Clayton743ecf42012-10-16 20:20:18 +00001669lldb_private::Error
Stephen Wilson84ffe702011-03-30 15:55:52 +00001670ProcessMonitor::Detach()
1671{
Greg Clayton28041352011-11-29 20:50:10 +00001672 lldb_private::Error error;
Greg Clayton743ecf42012-10-16 20:20:18 +00001673 if (m_pid != LLDB_INVALID_PROCESS_ID) {
1674 DetachOperation op(error);
1675 DoOperation(&op);
1676 }
Greg Clayton743ecf42012-10-16 20:20:18 +00001677 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00001678}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001679
1680bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001681ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1682{
Peter Collingbourne62343202011-06-14 03:55:54 +00001683 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001684
1685 if (target_fd == -1)
1686 return false;
1687
Peter Collingbourne62343202011-06-14 03:55:54 +00001688 return (dup2(target_fd, fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001689}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001690
1691void
1692ProcessMonitor::StopMonitoringChildProcess()
1693{
1694 lldb::thread_result_t thread_result;
1695
Stephen Wilsond4182f42011-02-09 20:10:35 +00001696 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001697 {
1698 Host::ThreadCancel(m_monitor_thread, NULL);
1699 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1700 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1701 }
1702}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001703
1704void
1705ProcessMonitor::StopMonitor()
1706{
1707 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00001708 StopOpThread();
Stephen Wilson84ffe702011-03-30 15:55:52 +00001709 CloseFD(m_terminal_fd);
1710 CloseFD(m_client_fd);
1711 CloseFD(m_server_fd);
1712}
1713
1714void
Greg Clayton743ecf42012-10-16 20:20:18 +00001715ProcessMonitor::StopOpThread()
1716{
1717 lldb::thread_result_t result;
1718
1719 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1720 return;
1721
1722 Host::ThreadCancel(m_operation_thread, NULL);
1723 Host::ThreadJoin(m_operation_thread, &result, NULL);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001724 m_operation_thread = LLDB_INVALID_HOST_THREAD;
Greg Clayton743ecf42012-10-16 20:20:18 +00001725}
1726
1727void
Stephen Wilson84ffe702011-03-30 15:55:52 +00001728ProcessMonitor::CloseFD(int &fd)
1729{
1730 if (fd != -1)
1731 {
1732 close(fd);
1733 fd = -1;
1734 }
1735}