blob: 35d12abb448fe1ab988ee5aadf507086c3fb2059 [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>
16#include <unistd.h>
17#include <sys/ptrace.h>
18#include <sys/socket.h>
19#include <sys/types.h>
Benjamin Kramerc2b5c672012-04-07 09:13:49 +000020#include <sys/user.h>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000021#include <sys/wait.h>
22
23// C++ Includes
24// Other libraries and framework includes
Johnny Chen0d5f2d42011-10-18 18:09:30 +000025#include "lldb/Core/Debugger.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000026#include "lldb/Core/Error.h"
Johnny Chen13e8e1c2011-05-13 21:29:50 +000027#include "lldb/Core/RegisterValue.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000028#include "lldb/Core/Scalar.h"
29#include "lldb/Host/Host.h"
30#include "lldb/Target/Thread.h"
31#include "lldb/Target/RegisterContext.h"
32#include "lldb/Utility/PseudoTerminal.h"
33
Johnny Chen30213ff2012-01-05 19:17:38 +000034#include "POSIXThread.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000035#include "ProcessLinux.h"
Johnny Chen30213ff2012-01-05 19:17:38 +000036#include "ProcessPOSIXLog.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000037#include "ProcessMonitor.h"
38
39
Greg Clayton386ff182011-11-05 01:09:16 +000040#define DEBUG_PTRACE_MAXBYTES 20
41
Stephen Wilsone6f9f662010-07-24 02:19:04 +000042using namespace lldb_private;
43
Johnny Chen0d5f2d42011-10-18 18:09:30 +000044// FIXME: this code is host-dependent with respect to types and
45// endianness and needs to be fixed. For example, lldb::addr_t is
46// hard-coded to uint64_t, but on a 32-bit Linux host, ptrace requires
47// 32-bit pointer arguments. This code uses casts to work around the
48// problem.
49
50// We disable the tracing of ptrace calls for integration builds to
51// avoid the additional indirection and checks.
52#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
53
Greg Clayton386ff182011-11-05 01:09:16 +000054static void
55DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
56{
57 uint8_t *ptr = (uint8_t *)bytes;
58 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
59 for(uint32_t i=0; i<loop_count; i++)
60 {
61 s.Printf ("[%x]", *ptr);
62 ptr++;
63 }
64}
65
66static void PtraceDisplayBytes(__ptrace_request &req, void *data)
67{
68 StreamString buf;
Johnny Chen30213ff2012-01-05 19:17:38 +000069 LogSP verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
70 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
Greg Clayton386ff182011-11-05 01:09:16 +000071
72 if (verbose_log)
73 {
74 switch(req)
75 {
76 case PTRACE_POKETEXT:
77 {
78 DisplayBytes(buf, &data, 8);
79 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
80 break;
81 }
Greg Clayton542e4072012-09-07 17:49:29 +000082 case PTRACE_POKEDATA:
Greg Clayton386ff182011-11-05 01:09:16 +000083 {
84 DisplayBytes(buf, &data, 8);
85 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
86 break;
87 }
Greg Clayton542e4072012-09-07 17:49:29 +000088 case PTRACE_POKEUSER:
Greg Clayton386ff182011-11-05 01:09:16 +000089 {
90 DisplayBytes(buf, &data, 8);
91 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
92 break;
93 }
Greg Clayton542e4072012-09-07 17:49:29 +000094 case PTRACE_SETREGS:
Greg Clayton386ff182011-11-05 01:09:16 +000095 {
96 DisplayBytes(buf, data, sizeof(user_regs_struct));
97 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
98 break;
99 }
100 case PTRACE_SETFPREGS:
101 {
102 DisplayBytes(buf, data, sizeof(user_fpregs_struct));
103 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
104 break;
105 }
Greg Clayton542e4072012-09-07 17:49:29 +0000106 case PTRACE_SETSIGINFO:
Greg Clayton386ff182011-11-05 01:09:16 +0000107 {
108 DisplayBytes(buf, data, sizeof(siginfo_t));
109 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
110 break;
111 }
112 default:
113 {
114 }
115 }
116 }
117}
118
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000119// Wrapper for ptrace to catch errors and log calls.
120extern long
121PtraceWrapper(__ptrace_request req, pid_t pid, void *addr, void *data,
122 const char* reqName, const char* file, int line)
123{
Greg Clayton386ff182011-11-05 01:09:16 +0000124 long int result;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000125
Johnny Chen30213ff2012-01-05 19:17:38 +0000126 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
Greg Clayton386ff182011-11-05 01:09:16 +0000127
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000128 if (log)
129 log->Printf("ptrace(%s, %u, %p, %p) called from file %s line %d",
130 reqName, pid, addr, data, file, line);
Greg Clayton542e4072012-09-07 17:49:29 +0000131
Greg Clayton386ff182011-11-05 01:09:16 +0000132 PtraceDisplayBytes(req, data);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000133
134 errno = 0;
135 result = ptrace(req, pid, addr, data);
136
Greg Clayton386ff182011-11-05 01:09:16 +0000137 PtraceDisplayBytes(req, data);
138
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000139 if (log && (result == -1 || errno != 0))
140 {
141 const char* str;
142 switch (errno)
143 {
144 case ESRCH: str = "ESRCH"; break;
145 case EINVAL: str = "EINVAL"; break;
146 case EBUSY: str = "EBUSY"; break;
147 case EPERM: str = "EPERM"; break;
148 default: str = "<unknown>";
149 }
150 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
151 }
152
153 return result;
154}
155
156#define PTRACE(req, pid, addr, data) \
157 PtraceWrapper((req), (pid), (addr), (data), #req, __FILE__, __LINE__)
158#else
159#define PTRACE ptrace
160#endif
161
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000162//------------------------------------------------------------------------------
163// Static implementations of ProcessMonitor::ReadMemory and
164// ProcessMonitor::WriteMemory. This enables mutual recursion between these
165// functions without needed to go thru the thread funnel.
166
167static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000168DoReadMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000169 lldb::addr_t vm_addr, void *buf, size_t size, Error &error)
170{
Greg Clayton542e4072012-09-07 17:49:29 +0000171 // ptrace word size is determined by the host, not the child
172 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000173 unsigned char *dst = static_cast<unsigned char*>(buf);
174 size_t bytes_read;
175 size_t remainder;
176 long data;
177
Johnny Chen30213ff2012-01-05 19:17:38 +0000178 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000179 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000180 ProcessPOSIXLog::IncNestLevel();
181 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000182 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000183 pid, word_size, (void*)vm_addr, buf, size);
184
185 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000186 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
187 {
188 errno = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000189 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, NULL);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000190 if (data == -1L && errno)
191 {
192 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000193 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000194 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000195 return bytes_read;
196 }
197
198 remainder = size - bytes_read;
199 remainder = remainder > word_size ? word_size : remainder;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000200
201 // Copy the data into our buffer
202 if (log)
203 memset(dst, 0, sizeof(dst));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000204 for (unsigned i = 0; i < remainder; ++i)
205 dst[i] = ((data >> i*8) & 0xFF);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000206
Johnny Chen30213ff2012-01-05 19:17:38 +0000207 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
208 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
209 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
210 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000211 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
212 (void*)vm_addr, *(unsigned long*)dst, (unsigned long)data);
213
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000214 vm_addr += word_size;
215 dst += word_size;
216 }
217
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000218 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000219 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000220 return bytes_read;
221}
222
223static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000224DoWriteMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000225 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
226{
Greg Clayton542e4072012-09-07 17:49:29 +0000227 // ptrace word size is determined by the host, not the child
228 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000229 const unsigned char *src = static_cast<const unsigned char*>(buf);
230 size_t bytes_written = 0;
231 size_t remainder;
232
Johnny Chen30213ff2012-01-05 19:17:38 +0000233 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000234 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000235 ProcessPOSIXLog::IncNestLevel();
236 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000237 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000238 pid, word_size, (void*)vm_addr, buf, size);
239
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000240 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
241 {
242 remainder = size - bytes_written;
243 remainder = remainder > word_size ? word_size : remainder;
244
245 if (remainder == word_size)
246 {
247 unsigned long data = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000248 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000249 for (unsigned i = 0; i < word_size; ++i)
250 data |= (unsigned long)src[i] << i*8;
251
Johnny Chen30213ff2012-01-05 19:17:38 +0000252 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
253 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
254 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
255 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000256 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
257 (void*)vm_addr, *(unsigned long*)src, data);
258
259 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000260 {
261 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000262 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000263 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000264 return bytes_written;
265 }
266 }
267 else
268 {
269 unsigned char buff[8];
Greg Clayton542e4072012-09-07 17:49:29 +0000270 if (DoReadMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000271 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000272 {
273 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000274 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000275 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000276 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000277
278 memcpy(buff, src, remainder);
279
Greg Clayton542e4072012-09-07 17:49:29 +0000280 if (DoWriteMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000281 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000282 {
283 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000284 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000285 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000286 }
287
Johnny Chen30213ff2012-01-05 19:17:38 +0000288 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
289 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
290 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
291 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000292 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
293 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000294 }
295
296 vm_addr += word_size;
297 src += word_size;
298 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000299 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000300 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000301 return bytes_written;
302}
303
Stephen Wilson26977162011-03-23 02:14:42 +0000304// Simple helper function to ensure flags are enabled on the given file
305// descriptor.
306static bool
307EnsureFDFlags(int fd, int flags, Error &error)
308{
309 int status;
310
311 if ((status = fcntl(fd, F_GETFL)) == -1)
312 {
313 error.SetErrorToErrno();
314 return false;
315 }
316
317 if (fcntl(fd, F_SETFL, status | flags) == -1)
318 {
319 error.SetErrorToErrno();
320 return false;
321 }
322
323 return true;
324}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000325
326//------------------------------------------------------------------------------
327/// @class Operation
328/// @brief Represents a ProcessMonitor operation.
329///
330/// Under Linux, it is not possible to ptrace() from any other thread but the
331/// one that spawned or attached to the process from the start. Therefore, when
332/// a ProcessMonitor is asked to deliver or change the state of an inferior
333/// process the operation must be "funneled" to a specific thread to perform the
334/// task. The Operation class provides an abstract base for all services the
335/// ProcessMonitor must perform via the single virtual function Execute, thus
336/// encapsulating the code that needs to run in the privileged context.
337class Operation
338{
339public:
340 virtual void Execute(ProcessMonitor *monitor) = 0;
341};
342
343//------------------------------------------------------------------------------
344/// @class ReadOperation
345/// @brief Implements ProcessMonitor::ReadMemory.
346class ReadOperation : public Operation
347{
348public:
349 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
350 Error &error, size_t &result)
351 : m_addr(addr), m_buff(buff), m_size(size),
352 m_error(error), m_result(result)
353 { }
354
355 void Execute(ProcessMonitor *monitor);
356
357private:
358 lldb::addr_t m_addr;
359 void *m_buff;
360 size_t m_size;
361 Error &m_error;
362 size_t &m_result;
363};
364
365void
366ReadOperation::Execute(ProcessMonitor *monitor)
367{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000368 lldb::pid_t pid = monitor->GetPID();
369
Greg Clayton542e4072012-09-07 17:49:29 +0000370 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000371}
372
373//------------------------------------------------------------------------------
374/// @class ReadOperation
375/// @brief Implements ProcessMonitor::WriteMemory.
376class WriteOperation : public Operation
377{
378public:
379 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
380 Error &error, size_t &result)
381 : m_addr(addr), m_buff(buff), m_size(size),
382 m_error(error), m_result(result)
383 { }
384
385 void Execute(ProcessMonitor *monitor);
386
387private:
388 lldb::addr_t m_addr;
389 const void *m_buff;
390 size_t m_size;
391 Error &m_error;
392 size_t &m_result;
393};
394
395void
396WriteOperation::Execute(ProcessMonitor *monitor)
397{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000398 lldb::pid_t pid = monitor->GetPID();
399
Greg Clayton542e4072012-09-07 17:49:29 +0000400 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000401}
402
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000403
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000404//------------------------------------------------------------------------------
405/// @class ReadRegOperation
406/// @brief Implements ProcessMonitor::ReadRegisterValue.
407class ReadRegOperation : public Operation
408{
409public:
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000410 ReadRegOperation(unsigned offset, RegisterValue &value, bool &result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000411 : m_offset(offset), m_value(value), m_result(result)
412 { }
413
414 void Execute(ProcessMonitor *monitor);
415
416private:
417 unsigned m_offset;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000418 RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000419 bool &m_result;
420};
421
422void
423ReadRegOperation::Execute(ProcessMonitor *monitor)
424{
425 lldb::pid_t pid = monitor->GetPID();
Johnny Chen30213ff2012-01-05 19:17:38 +0000426 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000427
428 // Set errno to zero so that we can detect a failed peek.
429 errno = 0;
Greg Clayton386ff182011-11-05 01:09:16 +0000430 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, pid, (void*)m_offset, NULL);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000431 if (data == -1UL && errno)
432 m_result = false;
433 else
434 {
435 m_value = data;
436 m_result = true;
437 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000438 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000439 log->Printf ("ProcessMonitor::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
Johnny Chen30213ff2012-01-05 19:17:38 +0000440 POSIXThread::GetRegisterNameFromOffset(m_offset), data);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000441}
442
443//------------------------------------------------------------------------------
444/// @class WriteRegOperation
445/// @brief Implements ProcessMonitor::WriteRegisterValue.
446class WriteRegOperation : public Operation
447{
448public:
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000449 WriteRegOperation(unsigned offset, const RegisterValue &value, bool &result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000450 : m_offset(offset), m_value(value), m_result(result)
451 { }
452
453 void Execute(ProcessMonitor *monitor);
454
455private:
456 unsigned m_offset;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000457 const RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000458 bool &m_result;
459};
460
461void
462WriteRegOperation::Execute(ProcessMonitor *monitor)
463{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000464 void* buf;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000465 lldb::pid_t pid = monitor->GetPID();
Johnny Chen30213ff2012-01-05 19:17:38 +0000466 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000467
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000468 if (sizeof(void*) == sizeof(uint64_t))
469 buf = (void*) m_value.GetAsUInt64();
470 else
471 {
472 assert(sizeof(void*) == sizeof(uint32_t));
473 buf = (void*) m_value.GetAsUInt32();
474 }
475
476 if (log)
477 log->Printf ("ProcessMonitor::%s() reg %s: %p", __FUNCTION__,
Johnny Chen30213ff2012-01-05 19:17:38 +0000478 POSIXThread::GetRegisterNameFromOffset(m_offset), buf);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000479 if (PTRACE(PTRACE_POKEUSER, pid, (void*)m_offset, buf))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000480 m_result = false;
481 else
482 m_result = true;
483}
484
485//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000486/// @class ReadGPROperation
487/// @brief Implements ProcessMonitor::ReadGPR.
488class ReadGPROperation : public Operation
489{
490public:
491 ReadGPROperation(void *buf, bool &result)
492 : m_buf(buf), m_result(result)
493 { }
494
495 void Execute(ProcessMonitor *monitor);
496
497private:
498 void *m_buf;
499 bool &m_result;
500};
501
502void
503ReadGPROperation::Execute(ProcessMonitor *monitor)
504{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000505 if (PTRACE(PTRACE_GETREGS, monitor->GetPID(), NULL, m_buf) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000506 m_result = false;
507 else
508 m_result = true;
509}
510
511//------------------------------------------------------------------------------
512/// @class ReadFPROperation
513/// @brief Implements ProcessMonitor::ReadFPR.
514class ReadFPROperation : public Operation
515{
516public:
517 ReadFPROperation(void *buf, bool &result)
518 : m_buf(buf), m_result(result)
519 { }
520
521 void Execute(ProcessMonitor *monitor);
522
523private:
524 void *m_buf;
525 bool &m_result;
526};
527
528void
529ReadFPROperation::Execute(ProcessMonitor *monitor)
530{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000531 if (PTRACE(PTRACE_GETFPREGS, monitor->GetPID(), NULL, m_buf) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000532 m_result = false;
533 else
534 m_result = true;
535}
536
537//------------------------------------------------------------------------------
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000538/// @class WriteGPROperation
539/// @brief Implements ProcessMonitor::WriteGPR.
540class WriteGPROperation : public Operation
541{
542public:
543 WriteGPROperation(void *buf, bool &result)
544 : m_buf(buf), m_result(result)
545 { }
546
547 void Execute(ProcessMonitor *monitor);
548
549private:
550 void *m_buf;
551 bool &m_result;
552};
553
554void
555WriteGPROperation::Execute(ProcessMonitor *monitor)
556{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000557 if (PTRACE(PTRACE_SETREGS, monitor->GetPID(), NULL, m_buf) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000558 m_result = false;
559 else
560 m_result = true;
561}
562
563//------------------------------------------------------------------------------
564/// @class WriteFPROperation
565/// @brief Implements ProcessMonitor::WriteFPR.
566class WriteFPROperation : public Operation
567{
568public:
569 WriteFPROperation(void *buf, bool &result)
570 : m_buf(buf), m_result(result)
571 { }
572
573 void Execute(ProcessMonitor *monitor);
574
575private:
576 void *m_buf;
577 bool &m_result;
578};
579
580void
581WriteFPROperation::Execute(ProcessMonitor *monitor)
582{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000583 if (PTRACE(PTRACE_SETFPREGS, monitor->GetPID(), NULL, m_buf) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000584 m_result = false;
585 else
586 m_result = true;
587}
588
589//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000590/// @class ResumeOperation
591/// @brief Implements ProcessMonitor::Resume.
592class ResumeOperation : public Operation
593{
594public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000595 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
596 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000597
598 void Execute(ProcessMonitor *monitor);
599
600private:
601 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000602 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000603 bool &m_result;
604};
605
606void
607ResumeOperation::Execute(ProcessMonitor *monitor)
608{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000609 int data = 0;
610
611 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
612 data = m_signo;
613
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000614 if (PTRACE(PTRACE_CONT, m_tid, NULL, (void*)data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000615 m_result = false;
616 else
617 m_result = true;
618}
619
620//------------------------------------------------------------------------------
621/// @class ResumeOperation
622/// @brief Implements ProcessMonitor::SingleStep.
623class SingleStepOperation : public Operation
624{
625public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000626 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
627 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000628
629 void Execute(ProcessMonitor *monitor);
630
631private:
632 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000633 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000634 bool &m_result;
635};
636
637void
638SingleStepOperation::Execute(ProcessMonitor *monitor)
639{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000640 int data = 0;
641
642 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
643 data = m_signo;
644
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000645 if (PTRACE(PTRACE_SINGLESTEP, m_tid, NULL, (void*)data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000646 m_result = false;
647 else
648 m_result = true;
649}
650
651//------------------------------------------------------------------------------
652/// @class SiginfoOperation
653/// @brief Implements ProcessMonitor::GetSignalInfo.
654class SiginfoOperation : public Operation
655{
656public:
Daniel Maleaa35970a2012-11-23 18:09:58 +0000657 SiginfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
658 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000659
660 void Execute(ProcessMonitor *monitor);
661
662private:
663 lldb::tid_t m_tid;
664 void *m_info;
665 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000666 int &m_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000667};
668
669void
670SiginfoOperation::Execute(ProcessMonitor *monitor)
671{
Daniel Maleaa35970a2012-11-23 18:09:58 +0000672 if (PTRACE(PTRACE_GETSIGINFO, m_tid, NULL, m_info)) {
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000673 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000674 m_err = errno;
675 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000676 else
677 m_result = true;
678}
679
680//------------------------------------------------------------------------------
681/// @class EventMessageOperation
682/// @brief Implements ProcessMonitor::GetEventMessage.
683class EventMessageOperation : public Operation
684{
685public:
686 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
687 : m_tid(tid), m_message(message), m_result(result) { }
688
689 void Execute(ProcessMonitor *monitor);
690
691private:
692 lldb::tid_t m_tid;
693 unsigned long *m_message;
694 bool &m_result;
695};
696
697void
698EventMessageOperation::Execute(ProcessMonitor *monitor)
699{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000700 if (PTRACE(PTRACE_GETEVENTMSG, m_tid, NULL, m_message))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000701 m_result = false;
702 else
703 m_result = true;
704}
705
706//------------------------------------------------------------------------------
707/// @class KillOperation
708/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
709class KillOperation : public Operation
710{
711public:
712 KillOperation(bool &result) : m_result(result) { }
713
714 void Execute(ProcessMonitor *monitor);
715
716private:
717 bool &m_result;
718};
719
720void
721KillOperation::Execute(ProcessMonitor *monitor)
722{
723 lldb::pid_t pid = monitor->GetPID();
724
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000725 if (PTRACE(PTRACE_KILL, pid, NULL, NULL))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000726 m_result = false;
727 else
728 m_result = true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000729}
730
Greg Clayton28041352011-11-29 20:50:10 +0000731//------------------------------------------------------------------------------
732/// @class KillOperation
733/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
734class DetachOperation : public Operation
735{
736public:
737 DetachOperation(Error &result) : m_error(result) { }
738
739 void Execute(ProcessMonitor *monitor);
740
741private:
742 Error &m_error;
743};
744
745void
746DetachOperation::Execute(ProcessMonitor *monitor)
747{
748 lldb::pid_t pid = monitor->GetPID();
749
750 if (ptrace(PT_DETACH, pid, NULL, 0) < 0)
751 m_error.SetErrorToErrno();
Greg Clayton542e4072012-09-07 17:49:29 +0000752
Greg Clayton28041352011-11-29 20:50:10 +0000753}
754
Johnny Chen25e68e32011-06-14 19:19:50 +0000755ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
756 : m_monitor(monitor)
757{
758 sem_init(&m_semaphore, 0, 0);
759}
760
761ProcessMonitor::OperationArgs::~OperationArgs()
762{
763 sem_destroy(&m_semaphore);
764}
765
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000766ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
767 lldb_private::Module *module,
768 char const **argv,
769 char const **envp,
770 const char *stdin_path,
771 const char *stdout_path,
772 const char *stderr_path)
Johnny Chen25e68e32011-06-14 19:19:50 +0000773 : OperationArgs(monitor),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000774 m_module(module),
775 m_argv(argv),
776 m_envp(envp),
777 m_stdin_path(stdin_path),
778 m_stdout_path(stdout_path),
Johnny Chen25e68e32011-06-14 19:19:50 +0000779 m_stderr_path(stderr_path) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000780
781ProcessMonitor::LaunchArgs::~LaunchArgs()
Johnny Chen25e68e32011-06-14 19:19:50 +0000782{ }
783
784ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
785 lldb::pid_t pid)
786 : OperationArgs(monitor), m_pid(pid) { }
787
788ProcessMonitor::AttachArgs::~AttachArgs()
789{ }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000790
791//------------------------------------------------------------------------------
792/// The basic design of the ProcessMonitor is built around two threads.
793///
794/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
795/// for changes in the debugee state. When a change is detected a
796/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
797/// "drives" state changes in the debugger.
798///
799/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000800/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000801/// operations such as register reads/writes, stepping, etc. See the comments
802/// on the Operation class for more info as to why this is needed.
Johnny Chen30213ff2012-01-05 19:17:38 +0000803ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000804 Module *module,
805 const char *argv[],
806 const char *envp[],
807 const char *stdin_path,
808 const char *stdout_path,
809 const char *stderr_path,
810 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000811 : m_process(static_cast<ProcessLinux *>(process)),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000812 m_operation_thread(LLDB_INVALID_HOST_THREAD),
813 m_pid(LLDB_INVALID_PROCESS_ID),
814 m_terminal_fd(-1),
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000815 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000816 m_client_fd(-1),
817 m_server_fd(-1)
818{
Stephen Wilson57740ec2011-01-15 00:12:41 +0000819 std::auto_ptr<LaunchArgs> args;
820
821 args.reset(new LaunchArgs(this, module, argv, envp,
822 stdin_path, stdout_path, stderr_path));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000823
824 // Server/client descriptors.
825 if (!EnableIPC())
826 {
827 error.SetErrorToGenericError();
828 error.SetErrorString("Monitor failed to initialize.");
829 }
830
Johnny Chen25e68e32011-06-14 19:19:50 +0000831 StartLaunchOpThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000832 if (!error.Success())
833 return;
834
835WAIT_AGAIN:
836 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000837 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000838 {
839 if (errno == EINTR)
840 goto WAIT_AGAIN;
841 else
842 {
843 error.SetErrorToErrno();
844 return;
845 }
846 }
847
848 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000849 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000850 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000851 StopOpThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000852 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000853 return;
854 }
855
856 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000857 m_monitor_thread = Host::StartMonitoringChildProcess(
858 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Stephen Wilsond4182f42011-02-09 20:10:35 +0000859 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000860 {
861 error.SetErrorToGenericError();
862 error.SetErrorString("Process launch failed.");
863 return;
864 }
865}
866
Johnny Chen30213ff2012-01-05 19:17:38 +0000867ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen25e68e32011-06-14 19:19:50 +0000868 lldb::pid_t pid,
869 lldb_private::Error &error)
Johnny Chen30213ff2012-01-05 19:17:38 +0000870 : m_process(static_cast<ProcessLinux *>(process)),
Johnny Chen25e68e32011-06-14 19:19:50 +0000871 m_operation_thread(LLDB_INVALID_HOST_THREAD),
872 m_pid(LLDB_INVALID_PROCESS_ID),
873 m_terminal_fd(-1),
874 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
875 m_client_fd(-1),
876 m_server_fd(-1)
877{
878 std::auto_ptr<AttachArgs> args;
879
880 args.reset(new AttachArgs(this, pid));
881
882 // Server/client descriptors.
883 if (!EnableIPC())
884 {
885 error.SetErrorToGenericError();
886 error.SetErrorString("Monitor failed to initialize.");
887 }
888
889 StartAttachOpThread(args.get(), error);
890 if (!error.Success())
891 return;
892
893WAIT_AGAIN:
894 // Wait for the operation thread to initialize.
895 if (sem_wait(&args->m_semaphore))
896 {
897 if (errno == EINTR)
898 goto WAIT_AGAIN;
899 else
900 {
901 error.SetErrorToErrno();
902 return;
903 }
904 }
905
Greg Clayton743ecf42012-10-16 20:20:18 +0000906 // Check that the attach was a success.
Johnny Chen25e68e32011-06-14 19:19:50 +0000907 if (!args->m_error.Success())
908 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000909 StopOpThread();
Johnny Chen25e68e32011-06-14 19:19:50 +0000910 error = args->m_error;
911 return;
912 }
913
914 // Finally, start monitoring the child process for change in state.
915 m_monitor_thread = Host::StartMonitoringChildProcess(
916 ProcessMonitor::MonitorCallback, this, GetPID(), true);
917 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
918 {
919 error.SetErrorToGenericError();
920 error.SetErrorString("Process attach failed.");
921 return;
922 }
923}
924
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000925ProcessMonitor::~ProcessMonitor()
926{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000927 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000928}
929
930//------------------------------------------------------------------------------
931// Thread setup and tear down.
932void
Johnny Chen25e68e32011-06-14 19:19:50 +0000933ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000934{
935 static const char *g_thread_name = "lldb.process.linux.operation";
936
Stephen Wilsond4182f42011-02-09 20:10:35 +0000937 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000938 return;
939
940 m_operation_thread =
Johnny Chen25e68e32011-06-14 19:19:50 +0000941 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000942}
943
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000944void *
Johnny Chen25e68e32011-06-14 19:19:50 +0000945ProcessMonitor::LaunchOpThread(void *arg)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000946{
947 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
948
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +0000949 if (!Launch(args)) {
950 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000951 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +0000952 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000953
Stephen Wilson570243b2011-01-19 01:37:06 +0000954 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000955 return NULL;
956}
957
958bool
959ProcessMonitor::Launch(LaunchArgs *args)
960{
961 ProcessMonitor *monitor = args->m_monitor;
962 ProcessLinux &process = monitor->GetProcess();
963 const char **argv = args->m_argv;
964 const char **envp = args->m_envp;
965 const char *stdin_path = args->m_stdin_path;
966 const char *stdout_path = args->m_stdout_path;
967 const char *stderr_path = args->m_stderr_path;
968
969 lldb_utility::PseudoTerminal terminal;
970 const size_t err_len = 1024;
971 char err_str[err_len];
972 lldb::pid_t pid;
973
974 lldb::ThreadSP inferior;
Johnny Chen30213ff2012-01-05 19:17:38 +0000975 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000976
Stephen Wilson57740ec2011-01-15 00:12:41 +0000977 // Propagate the environment if one is not supplied.
978 if (envp == NULL || envp[0] == NULL)
979 envp = const_cast<const char **>(environ);
980
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000981 // Pseudo terminal setup.
982 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
983 {
984 args->m_error.SetErrorToGenericError();
985 args->m_error.SetErrorString("Could not open controlling TTY.");
986 goto FINISH;
987 }
988
989 if ((pid = terminal.Fork(err_str, err_len)) < 0)
990 {
991 args->m_error.SetErrorToGenericError();
992 args->m_error.SetErrorString("Process fork failed.");
993 goto FINISH;
994 }
995
Peter Collingbourne6a520222011-06-14 03:55:58 +0000996 // Recognized child exit status codes.
997 enum {
998 ePtraceFailed = 1,
999 eDupStdinFailed,
1000 eDupStdoutFailed,
1001 eDupStderrFailed,
1002 eExecFailed
1003 };
1004
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001005 // Child process.
1006 if (pid == 0)
1007 {
1008 // Trace this process.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001009 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL) < 0)
Peter Collingbourne6a520222011-06-14 03:55:58 +00001010 exit(ePtraceFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001011
1012 // Do not inherit setgid powers.
1013 setgid(getgid());
1014
1015 // Let us have our own process group.
1016 setpgid(0, 0);
1017
Greg Clayton710dd5a2011-01-08 20:28:42 +00001018 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001019 //
1020 // FIXME: If two or more of the paths are the same we needlessly open
1021 // the same file multiple times.
1022 if (stdin_path != NULL && stdin_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001023 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001024 exit(eDupStdinFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001025
1026 if (stdout_path != NULL && stdout_path[0])
1027 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001028 exit(eDupStdoutFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001029
1030 if (stderr_path != NULL && stderr_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001031 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001032 exit(eDupStderrFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001033
1034 // Execute. We should never return.
1035 execve(argv[0],
1036 const_cast<char *const *>(argv),
1037 const_cast<char *const *>(envp));
Peter Collingbourne6a520222011-06-14 03:55:58 +00001038 exit(eExecFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001039 }
1040
1041 // Wait for the child process to to trap on its call to execve.
Peter Collingbourne6a520222011-06-14 03:55:58 +00001042 pid_t wpid;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001043 int status;
Peter Collingbourne6a520222011-06-14 03:55:58 +00001044 if ((wpid = waitpid(pid, &status, 0)) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001045 {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001046 args->m_error.SetErrorToErrno();
1047 goto FINISH;
1048 }
Peter Collingbourne6a520222011-06-14 03:55:58 +00001049 else if (WIFEXITED(status))
1050 {
1051 // open, dup or execve likely failed for some reason.
1052 args->m_error.SetErrorToGenericError();
1053 switch (WEXITSTATUS(status))
1054 {
Greg Clayton542e4072012-09-07 17:49:29 +00001055 case ePtraceFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001056 args->m_error.SetErrorString("Child ptrace failed.");
1057 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001058 case eDupStdinFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001059 args->m_error.SetErrorString("Child open stdin failed.");
1060 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001061 case eDupStdoutFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001062 args->m_error.SetErrorString("Child open stdout failed.");
1063 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001064 case eDupStderrFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001065 args->m_error.SetErrorString("Child open stderr failed.");
1066 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001067 case eExecFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001068 args->m_error.SetErrorString("Child exec failed.");
1069 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001070 default:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001071 args->m_error.SetErrorString("Child returned unknown exit status.");
1072 break;
1073 }
1074 goto FINISH;
1075 }
1076 assert(WIFSTOPPED(status) && wpid == pid &&
1077 "Could not sync with inferior process.");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001078
1079 // Have the child raise an event on exit. This is used to keep the child in
1080 // limbo until it is destroyed.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001081 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)PTRACE_O_TRACEEXIT) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001082 {
1083 args->m_error.SetErrorToErrno();
1084 goto FINISH;
1085 }
1086
1087 // Release the master terminal descriptor and pass it off to the
1088 // ProcessMonitor instance. Similarly stash the inferior pid.
1089 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1090 monitor->m_pid = pid;
1091
Stephen Wilson26977162011-03-23 02:14:42 +00001092 // Set the terminal fd to be in non blocking mode (it simplifies the
1093 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1094 // descriptor to read from).
1095 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1096 goto FINISH;
1097
Johnny Chen30213ff2012-01-05 19:17:38 +00001098 // Update the process thread list with this new thread.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001099 // FIXME: should we be letting UpdateThreadList handle this?
1100 // FIXME: by using pids instead of tids, we can only support one thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001101 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001102 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001103 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001104 process.GetThreadList().AddThread(inferior);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001105
1106 // Let our process instance know the thread has stopped.
1107 process.SendMessage(ProcessMessage::Trace(pid));
1108
1109FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001110 return args->m_error.Success();
1111}
1112
1113bool
1114ProcessMonitor::EnableIPC()
1115{
1116 int fd[2];
1117
1118 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
1119 return false;
1120
1121 m_client_fd = fd[0];
1122 m_server_fd = fd[1];
1123 return true;
1124}
1125
Johnny Chen25e68e32011-06-14 19:19:50 +00001126void
1127ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1128{
1129 static const char *g_thread_name = "lldb.process.linux.operation";
1130
1131 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1132 return;
1133
1134 m_operation_thread =
1135 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1136}
1137
Johnny Chen25e68e32011-06-14 19:19:50 +00001138void *
1139ProcessMonitor::AttachOpThread(void *arg)
1140{
1141 AttachArgs *args = static_cast<AttachArgs*>(arg);
1142
Greg Clayton743ecf42012-10-16 20:20:18 +00001143 if (!Attach(args)) {
1144 sem_post(&args->m_semaphore);
Johnny Chen25e68e32011-06-14 19:19:50 +00001145 return NULL;
Greg Clayton743ecf42012-10-16 20:20:18 +00001146 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001147
1148 ServeOperation(args);
1149 return NULL;
1150}
1151
1152bool
1153ProcessMonitor::Attach(AttachArgs *args)
1154{
1155 lldb::pid_t pid = args->m_pid;
1156
1157 ProcessMonitor *monitor = args->m_monitor;
1158 ProcessLinux &process = monitor->GetProcess();
Johnny Chen25e68e32011-06-14 19:19:50 +00001159 lldb::ThreadSP inferior;
Johnny Chen30213ff2012-01-05 19:17:38 +00001160 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen25e68e32011-06-14 19:19:50 +00001161
1162 if (pid <= 1)
1163 {
1164 args->m_error.SetErrorToGenericError();
1165 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1166 goto FINISH;
1167 }
1168
1169 // Attach to the requested process.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001170 if (PTRACE(PTRACE_ATTACH, pid, NULL, NULL) < 0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001171 {
1172 args->m_error.SetErrorToErrno();
1173 goto FINISH;
1174 }
1175
1176 int status;
1177 if ((status = waitpid(pid, NULL, 0)) < 0)
1178 {
1179 args->m_error.SetErrorToErrno();
1180 goto FINISH;
1181 }
1182
Greg Clayton926cce72012-10-12 16:10:12 +00001183 monitor->m_pid = pid;
1184
Johnny Chen30213ff2012-01-05 19:17:38 +00001185 // Update the process thread list with the attached thread.
Greg Claytondf3df252012-10-12 16:23:23 +00001186 inferior.reset(new POSIXThread(process, pid));
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001187 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001188 log->Printf ("ProcessMonitor::%s() adding tid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen25e68e32011-06-14 19:19:50 +00001189 process.GetThreadList().AddThread(inferior);
Johnny Chen25e68e32011-06-14 19:19:50 +00001190
1191 // Let our process instance know the thread has stopped.
1192 process.SendMessage(ProcessMessage::Trace(pid));
1193
1194 FINISH:
1195 return args->m_error.Success();
1196}
1197
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001198bool
1199ProcessMonitor::MonitorCallback(void *callback_baton,
1200 lldb::pid_t pid,
Peter Collingbourne2c67b9a2011-11-21 00:10:19 +00001201 bool exited,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001202 int signal,
1203 int status)
1204{
1205 ProcessMessage message;
1206 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
1207 ProcessLinux *process = monitor->m_process;
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001208 assert(process);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001209 bool stop_monitoring;
1210 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001211 int ptrace_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001212
Daniel Maleaa35970a2012-11-23 18:09:58 +00001213 if (!monitor->GetSignalInfo(pid, &info, ptrace_err)) {
1214 if (ptrace_err == EINVAL) {
1215 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1216 if (!monitor->Resume(pid, SIGSTOP)) {
1217 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1218 }
1219 stop_monitoring = false;
1220 } else {
1221 // ptrace(GETSIGINFO) failed (but not due to group-stop). Most likely,
1222 // this means the child pid is gone (or not being debugged) therefore
1223 // stop the monitor thread.
1224 stop_monitoring = true;
1225 }
1226 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00001227 else {
1228 switch (info.si_signo)
1229 {
1230 case SIGTRAP:
1231 message = MonitorSIGTRAP(monitor, &info, pid);
1232 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001233
Stephen Wilson84ffe702011-03-30 15:55:52 +00001234 default:
1235 message = MonitorSignal(monitor, &info, pid);
1236 break;
1237 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001238
Stephen Wilson84ffe702011-03-30 15:55:52 +00001239 process->SendMessage(message);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001240 stop_monitoring = !process->IsAlive();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001241 }
1242
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001243 return stop_monitoring;
1244}
1245
1246ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +00001247ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001248 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001249{
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001250 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001251
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001252 assert(monitor);
1253 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001254
Stephen Wilson84ffe702011-03-30 15:55:52 +00001255 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001256 {
1257 default:
1258 assert(false && "Unexpected SIGTRAP code!");
1259 break;
1260
1261 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1262 {
1263 // The inferior process is about to exit. Maintain the process in a
1264 // state of "limbo" until we are explicitly commanded to detach,
1265 // destroy, resume, etc.
1266 unsigned long data = 0;
1267 if (!monitor->GetEventMessage(pid, &data))
1268 data = -1;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001269 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001270 break;
1271 }
1272
1273 case 0:
1274 case TRAP_TRACE:
1275 message = ProcessMessage::Trace(pid);
1276 break;
1277
1278 case SI_KERNEL:
1279 case TRAP_BRKPT:
1280 message = ProcessMessage::Break(pid);
1281 break;
1282 }
1283
1284 return message;
1285}
1286
Stephen Wilson84ffe702011-03-30 15:55:52 +00001287ProcessMessage
1288ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001289 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001290{
1291 ProcessMessage message;
1292 int signo = info->si_signo;
1293
1294 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1295 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1296 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1297 //
1298 // IOW, user generated signals never generate what we consider to be a
1299 // "crash".
1300 //
1301 // Similarly, ACK signals generated by this monitor.
1302 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1303 {
1304 if (info->si_pid == getpid())
1305 return ProcessMessage::SignalDelivered(pid, signo);
1306 else
1307 return ProcessMessage::Signal(pid, signo);
1308 }
1309
1310 if (signo == SIGSEGV) {
1311 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1312 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1313 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1314 }
1315
1316 if (signo == SIGILL) {
1317 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1318 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1319 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1320 }
1321
1322 if (signo == SIGFPE) {
1323 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1324 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1325 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1326 }
1327
1328 if (signo == SIGBUS) {
1329 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1330 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1331 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1332 }
1333
1334 // Everything else is "normal" and does not require any special action on
1335 // our part.
1336 return ProcessMessage::Signal(pid, signo);
1337}
1338
1339ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001340ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001341{
1342 ProcessMessage::CrashReason reason;
1343 assert(info->si_signo == SIGSEGV);
1344
1345 reason = ProcessMessage::eInvalidCrashReason;
1346
Greg Clayton542e4072012-09-07 17:49:29 +00001347 switch (info->si_code)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001348 {
1349 default:
1350 assert(false && "unexpected si_code for SIGSEGV");
1351 break;
1352 case SEGV_MAPERR:
1353 reason = ProcessMessage::eInvalidAddress;
1354 break;
1355 case SEGV_ACCERR:
1356 reason = ProcessMessage::ePrivilegedAddress;
1357 break;
1358 }
Greg Clayton542e4072012-09-07 17:49:29 +00001359
Stephen Wilson84ffe702011-03-30 15:55:52 +00001360 return reason;
1361}
1362
1363ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001364ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001365{
1366 ProcessMessage::CrashReason reason;
1367 assert(info->si_signo == SIGILL);
1368
1369 reason = ProcessMessage::eInvalidCrashReason;
1370
1371 switch (info->si_code)
1372 {
1373 default:
1374 assert(false && "unexpected si_code for SIGILL");
1375 break;
1376 case ILL_ILLOPC:
1377 reason = ProcessMessage::eIllegalOpcode;
1378 break;
1379 case ILL_ILLOPN:
1380 reason = ProcessMessage::eIllegalOperand;
1381 break;
1382 case ILL_ILLADR:
1383 reason = ProcessMessage::eIllegalAddressingMode;
1384 break;
1385 case ILL_ILLTRP:
1386 reason = ProcessMessage::eIllegalTrap;
1387 break;
1388 case ILL_PRVOPC:
1389 reason = ProcessMessage::ePrivilegedOpcode;
1390 break;
1391 case ILL_PRVREG:
1392 reason = ProcessMessage::ePrivilegedRegister;
1393 break;
1394 case ILL_COPROC:
1395 reason = ProcessMessage::eCoprocessorError;
1396 break;
1397 case ILL_BADSTK:
1398 reason = ProcessMessage::eInternalStackError;
1399 break;
1400 }
1401
1402 return reason;
1403}
1404
1405ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001406ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001407{
1408 ProcessMessage::CrashReason reason;
1409 assert(info->si_signo == SIGFPE);
1410
1411 reason = ProcessMessage::eInvalidCrashReason;
1412
1413 switch (info->si_code)
1414 {
1415 default:
1416 assert(false && "unexpected si_code for SIGFPE");
1417 break;
1418 case FPE_INTDIV:
1419 reason = ProcessMessage::eIntegerDivideByZero;
1420 break;
1421 case FPE_INTOVF:
1422 reason = ProcessMessage::eIntegerOverflow;
1423 break;
1424 case FPE_FLTDIV:
1425 reason = ProcessMessage::eFloatDivideByZero;
1426 break;
1427 case FPE_FLTOVF:
1428 reason = ProcessMessage::eFloatOverflow;
1429 break;
1430 case FPE_FLTUND:
1431 reason = ProcessMessage::eFloatUnderflow;
1432 break;
1433 case FPE_FLTRES:
1434 reason = ProcessMessage::eFloatInexactResult;
1435 break;
1436 case FPE_FLTINV:
1437 reason = ProcessMessage::eFloatInvalidOperation;
1438 break;
1439 case FPE_FLTSUB:
1440 reason = ProcessMessage::eFloatSubscriptRange;
1441 break;
1442 }
1443
1444 return reason;
1445}
1446
1447ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001448ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001449{
1450 ProcessMessage::CrashReason reason;
1451 assert(info->si_signo == SIGBUS);
1452
1453 reason = ProcessMessage::eInvalidCrashReason;
1454
1455 switch (info->si_code)
1456 {
1457 default:
1458 assert(false && "unexpected si_code for SIGBUS");
1459 break;
1460 case BUS_ADRALN:
1461 reason = ProcessMessage::eIllegalAlignment;
1462 break;
1463 case BUS_ADRERR:
1464 reason = ProcessMessage::eIllegalAddress;
1465 break;
1466 case BUS_OBJERR:
1467 reason = ProcessMessage::eHardwareError;
1468 break;
1469 }
1470
1471 return reason;
1472}
1473
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001474void
Johnny Chen25e68e32011-06-14 19:19:50 +00001475ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001476{
1477 int status;
1478 pollfd fdset;
Johnny Chen25e68e32011-06-14 19:19:50 +00001479
Stephen Wilson570243b2011-01-19 01:37:06 +00001480 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001481
1482 fdset.fd = monitor->m_server_fd;
1483 fdset.events = POLLIN | POLLPRI;
1484 fdset.revents = 0;
1485
Stephen Wilson570243b2011-01-19 01:37:06 +00001486 // We are finised with the arguments and are ready to go. Sync with the
1487 // parent thread and start serving operations on the inferior.
1488 sem_post(&args->m_semaphore);
1489
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001490 for (;;)
1491 {
1492 if ((status = poll(&fdset, 1, -1)) < 0)
1493 {
1494 switch (errno)
1495 {
1496 default:
1497 assert(false && "Unexpected poll() failure!");
1498 continue;
1499
1500 case EINTR: continue; // Just poll again.
1501 case EBADF: return; // Connection terminated.
1502 }
1503 }
1504
1505 assert(status == 1 && "Too many descriptors!");
1506
1507 if (fdset.revents & POLLIN)
1508 {
1509 Operation *op = NULL;
1510
1511 READ_AGAIN:
1512 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1513 {
1514 // There is only one acceptable failure.
1515 assert(errno == EINTR);
1516 goto READ_AGAIN;
1517 }
1518
1519 assert(status == sizeof(op));
1520 op->Execute(monitor);
1521 write(fdset.fd, &op, sizeof(op));
1522 }
1523 }
1524}
1525
1526void
1527ProcessMonitor::DoOperation(Operation *op)
1528{
1529 int status;
1530 Operation *ack = NULL;
1531 Mutex::Locker lock(m_server_mutex);
1532
1533 // FIXME: Do proper error checking here.
1534 write(m_client_fd, &op, sizeof(op));
1535
1536READ_AGAIN:
1537 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1538 {
1539 // If interrupted by a signal handler try again. Otherwise the monitor
1540 // thread probably died and we have a stale file descriptor -- abort the
1541 // operation.
1542 if (errno == EINTR)
1543 goto READ_AGAIN;
1544 return;
1545 }
1546
1547 assert(status == sizeof(ack));
1548 assert(ack == op && "Invalid monitor thread response!");
1549}
1550
1551size_t
1552ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1553 Error &error)
1554{
1555 size_t result;
1556 ReadOperation op(vm_addr, buf, size, error, result);
1557 DoOperation(&op);
1558 return result;
1559}
1560
1561size_t
1562ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1563 lldb_private::Error &error)
1564{
1565 size_t result;
1566 WriteOperation op(vm_addr, buf, size, error, result);
1567 DoOperation(&op);
1568 return result;
1569}
1570
1571bool
Johnny Chen30213ff2012-01-05 19:17:38 +00001572ProcessMonitor::ReadRegisterValue(unsigned offset, unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001573{
1574 bool result;
1575 ReadRegOperation op(offset, value, result);
1576 DoOperation(&op);
1577 return result;
1578}
1579
1580bool
Johnny Chen13e8e1c2011-05-13 21:29:50 +00001581ProcessMonitor::WriteRegisterValue(unsigned offset, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001582{
1583 bool result;
1584 WriteRegOperation op(offset, value, result);
1585 DoOperation(&op);
1586 return result;
1587}
1588
1589bool
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001590ProcessMonitor::ReadGPR(void *buf)
1591{
1592 bool result;
1593 ReadGPROperation op(buf, result);
1594 DoOperation(&op);
1595 return result;
1596}
1597
1598bool
1599ProcessMonitor::ReadFPR(void *buf)
1600{
1601 bool result;
1602 ReadFPROperation op(buf, result);
1603 DoOperation(&op);
1604 return result;
1605}
1606
1607bool
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001608ProcessMonitor::WriteGPR(void *buf)
1609{
1610 bool result;
1611 WriteGPROperation op(buf, result);
1612 DoOperation(&op);
1613 return result;
1614}
1615
1616bool
1617ProcessMonitor::WriteFPR(void *buf)
1618{
1619 bool result;
1620 WriteFPROperation op(buf, result);
1621 DoOperation(&op);
1622 return result;
1623}
1624
1625bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001626ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001627{
1628 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001629 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001630 DoOperation(&op);
1631 return result;
1632}
1633
1634bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001635ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001636{
1637 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001638 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001639 DoOperation(&op);
1640 return result;
1641}
1642
1643bool
1644ProcessMonitor::BringProcessIntoLimbo()
1645{
1646 bool result;
1647 KillOperation op(result);
1648 DoOperation(&op);
1649 return result;
1650}
1651
1652bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00001653ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001654{
1655 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001656 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001657 DoOperation(&op);
1658 return result;
1659}
1660
1661bool
1662ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1663{
1664 bool result;
1665 EventMessageOperation op(tid, message, result);
1666 DoOperation(&op);
1667 return result;
1668}
1669
Greg Clayton743ecf42012-10-16 20:20:18 +00001670lldb_private::Error
Stephen Wilson84ffe702011-03-30 15:55:52 +00001671ProcessMonitor::Detach()
1672{
Greg Clayton28041352011-11-29 20:50:10 +00001673 lldb_private::Error error;
Greg Clayton743ecf42012-10-16 20:20:18 +00001674 if (m_pid != LLDB_INVALID_PROCESS_ID) {
1675 DetachOperation op(error);
1676 DoOperation(&op);
1677 }
Greg Clayton743ecf42012-10-16 20:20:18 +00001678 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00001679}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001680
1681bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001682ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1683{
Peter Collingbourne62343202011-06-14 03:55:54 +00001684 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001685
1686 if (target_fd == -1)
1687 return false;
1688
Peter Collingbourne62343202011-06-14 03:55:54 +00001689 return (dup2(target_fd, fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001690}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001691
1692void
1693ProcessMonitor::StopMonitoringChildProcess()
1694{
1695 lldb::thread_result_t thread_result;
1696
Stephen Wilsond4182f42011-02-09 20:10:35 +00001697 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001698 {
1699 Host::ThreadCancel(m_monitor_thread, NULL);
1700 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1701 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1702 }
1703}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001704
1705void
1706ProcessMonitor::StopMonitor()
1707{
1708 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00001709 StopOpThread();
Stephen Wilson84ffe702011-03-30 15:55:52 +00001710 CloseFD(m_terminal_fd);
1711 CloseFD(m_client_fd);
1712 CloseFD(m_server_fd);
1713}
1714
1715void
Greg Clayton743ecf42012-10-16 20:20:18 +00001716ProcessMonitor::StopOpThread()
1717{
1718 lldb::thread_result_t result;
1719
1720 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1721 return;
1722
1723 Host::ThreadCancel(m_operation_thread, NULL);
1724 Host::ThreadJoin(m_operation_thread, &result, NULL);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00001725 m_operation_thread = LLDB_INVALID_HOST_THREAD;
Greg Clayton743ecf42012-10-16 20:20:18 +00001726}
1727
1728void
Stephen Wilson84ffe702011-03-30 15:55:52 +00001729ProcessMonitor::CloseFD(int &fd)
1730{
1731 if (fd != -1)
1732 {
1733 close(fd);
1734 fd = -1;
1735 }
1736}