blob: 457125aa0a973abe61d536a5714990c03ec65071 [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>
Andrew Kaylor93132f52013-05-28 23:04:25 +000020#include <sys/syscall.h>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000021#include <sys/types.h>
Richard Mitton0a558352013-10-17 21:14:00 +000022#include <sys/user.h>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000023#include <sys/wait.h>
24
25// C++ Includes
26// Other libraries and framework includes
Johnny Chen0d5f2d42011-10-18 18:09:30 +000027#include "lldb/Core/Debugger.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000028#include "lldb/Core/Error.h"
Johnny Chen13e8e1c2011-05-13 21:29:50 +000029#include "lldb/Core/RegisterValue.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000030#include "lldb/Core/Scalar.h"
31#include "lldb/Host/Host.h"
32#include "lldb/Target/Thread.h"
33#include "lldb/Target/RegisterContext.h"
34#include "lldb/Utility/PseudoTerminal.h"
35
Johnny Chen30213ff2012-01-05 19:17:38 +000036#include "POSIXThread.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000037#include "ProcessLinux.h"
Johnny Chen30213ff2012-01-05 19:17:38 +000038#include "ProcessPOSIXLog.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000039#include "ProcessMonitor.h"
40
Greg Clayton386ff182011-11-05 01:09:16 +000041#define DEBUG_PTRACE_MAXBYTES 20
42
Matt Kopec58c0b962013-03-20 20:34:35 +000043// Support ptrace extensions even when compiled without required kernel support
44#ifndef PTRACE_GETREGSET
45 #define PTRACE_GETREGSET 0x4204
46#endif
47#ifndef PTRACE_SETREGSET
48 #define PTRACE_SETREGSET 0x4205
49#endif
Richard Mitton0a558352013-10-17 21:14:00 +000050#ifndef PTRACE_GET_THREAD_AREA
51 #define PTRACE_GET_THREAD_AREA 25
52#endif
53#ifndef PTRACE_ARCH_PRCTL
54 #define PTRACE_ARCH_PRCTL 30
55#endif
56#ifndef ARCH_GET_FS
57 #define ARCH_SET_GS 0x1001
58 #define ARCH_SET_FS 0x1002
59 #define ARCH_GET_FS 0x1003
60 #define ARCH_GET_GS 0x1004
61#endif
62
Matt Kopec58c0b962013-03-20 20:34:35 +000063
Matt Kopece9ea0da2013-05-07 19:29:28 +000064// Support hardware breakpoints in case it has not been defined
65#ifndef TRAP_HWBKPT
66 #define TRAP_HWBKPT 4
67#endif
68
Andrew Kaylor93132f52013-05-28 23:04:25 +000069// Try to define a macro to encapsulate the tgkill syscall
70// fall back on kill() if tgkill isn't available
71#define tgkill(pid, tid, sig) syscall(SYS_tgkill, pid, tid, sig)
72
Stephen Wilsone6f9f662010-07-24 02:19:04 +000073using namespace lldb_private;
74
Johnny Chen0d5f2d42011-10-18 18:09:30 +000075// FIXME: this code is host-dependent with respect to types and
76// endianness and needs to be fixed. For example, lldb::addr_t is
77// hard-coded to uint64_t, but on a 32-bit Linux host, ptrace requires
78// 32-bit pointer arguments. This code uses casts to work around the
79// problem.
80
81// We disable the tracing of ptrace calls for integration builds to
82// avoid the additional indirection and checks.
83#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
84
Greg Clayton386ff182011-11-05 01:09:16 +000085static void
86DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
87{
88 uint8_t *ptr = (uint8_t *)bytes;
89 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
90 for(uint32_t i=0; i<loop_count; i++)
91 {
92 s.Printf ("[%x]", *ptr);
93 ptr++;
94 }
95}
96
Matt Kopec58c0b962013-03-20 20:34:35 +000097static void PtraceDisplayBytes(int &req, void *data, size_t data_size)
Greg Clayton386ff182011-11-05 01:09:16 +000098{
99 StreamString buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000100 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
Johnny Chen30213ff2012-01-05 19:17:38 +0000101 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
Greg Clayton386ff182011-11-05 01:09:16 +0000102
103 if (verbose_log)
104 {
105 switch(req)
106 {
107 case PTRACE_POKETEXT:
108 {
109 DisplayBytes(buf, &data, 8);
110 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
111 break;
112 }
Greg Clayton542e4072012-09-07 17:49:29 +0000113 case PTRACE_POKEDATA:
Greg Clayton386ff182011-11-05 01:09:16 +0000114 {
115 DisplayBytes(buf, &data, 8);
116 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
117 break;
118 }
Greg Clayton542e4072012-09-07 17:49:29 +0000119 case PTRACE_POKEUSER:
Greg Clayton386ff182011-11-05 01:09:16 +0000120 {
121 DisplayBytes(buf, &data, 8);
122 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
123 break;
124 }
Todd Fialad35f2b92014-06-23 15:59:04 +0000125#ifdef PT_SETREGS
Greg Clayton542e4072012-09-07 17:49:29 +0000126 case PTRACE_SETREGS:
Greg Clayton386ff182011-11-05 01:09:16 +0000127 {
Matt Kopec7de48462013-03-06 17:20:48 +0000128 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000129 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
130 break;
131 }
Todd Fialad35f2b92014-06-23 15:59:04 +0000132#endif
133#ifdef PT_SETFPREGS
Greg Clayton386ff182011-11-05 01:09:16 +0000134 case PTRACE_SETFPREGS:
135 {
Matt Kopec7de48462013-03-06 17:20:48 +0000136 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000137 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
138 break;
139 }
Todd Fialad35f2b92014-06-23 15:59:04 +0000140#endif
Greg Clayton542e4072012-09-07 17:49:29 +0000141 case PTRACE_SETSIGINFO:
Greg Clayton386ff182011-11-05 01:09:16 +0000142 {
143 DisplayBytes(buf, data, sizeof(siginfo_t));
144 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
145 break;
146 }
Matt Kopec58c0b962013-03-20 20:34:35 +0000147 case PTRACE_SETREGSET:
148 {
149 // Extract iov_base from data, which is a pointer to the struct IOVEC
150 DisplayBytes(buf, *(void **)data, data_size);
151 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
152 break;
153 }
Greg Clayton386ff182011-11-05 01:09:16 +0000154 default:
155 {
156 }
157 }
158 }
159}
160
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000161// Wrapper for ptrace to catch errors and log calls.
Ashok Thirumurthi762fbd02013-03-27 21:09:30 +0000162// Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000163extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000164PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000165 const char* reqName, const char* file, int line)
166{
Greg Clayton386ff182011-11-05 01:09:16 +0000167 long int result;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000168
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000169 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
Greg Clayton386ff182011-11-05 01:09:16 +0000170
Matt Kopec7de48462013-03-06 17:20:48 +0000171 PtraceDisplayBytes(req, data, data_size);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000172
173 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000174 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala4507f062014-02-27 20:46:12 +0000175 result = ptrace(static_cast<__ptrace_request>(req), static_cast<pid_t>(pid), *(unsigned int *)addr, data);
Matt Kopec58c0b962013-03-20 20:34:35 +0000176 else
Todd Fiala4507f062014-02-27 20:46:12 +0000177 result = ptrace(static_cast<__ptrace_request>(req), static_cast<pid_t>(pid), addr, data);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000178
Ed Mastec099c952014-02-24 14:07:45 +0000179 if (log)
180 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
181 reqName, pid, addr, data, data_size, result, file, line);
182
Matt Kopec7de48462013-03-06 17:20:48 +0000183 PtraceDisplayBytes(req, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000184
Matt Kopec7de48462013-03-06 17:20:48 +0000185 if (log && errno != 0)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000186 {
187 const char* str;
188 switch (errno)
189 {
190 case ESRCH: str = "ESRCH"; break;
191 case EINVAL: str = "EINVAL"; break;
192 case EBUSY: str = "EBUSY"; break;
193 case EPERM: str = "EPERM"; break;
194 default: str = "<unknown>";
195 }
196 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
197 }
198
199 return result;
200}
201
Matt Kopec7de48462013-03-06 17:20:48 +0000202// Wrapper for ptrace when logging is not required.
203// Sets errno to 0 prior to calling ptrace.
204extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000205PtraceWrapper(int req, pid_t pid, void *addr, void *data, size_t data_size)
Matt Kopec7de48462013-03-06 17:20:48 +0000206{
Matt Kopec58c0b962013-03-20 20:34:35 +0000207 long result = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000208 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000209 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
210 result = ptrace(static_cast<__ptrace_request>(req), pid, *(unsigned int *)addr, data);
211 else
212 result = ptrace(static_cast<__ptrace_request>(req), pid, addr, data);
Matt Kopec7de48462013-03-06 17:20:48 +0000213 return result;
214}
215
216#define PTRACE(req, pid, addr, data, data_size) \
217 PtraceWrapper((req), (pid), (addr), (data), (data_size), #req, __FILE__, __LINE__)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000218#else
Matt Kopec7de48462013-03-06 17:20:48 +0000219 PtraceWrapper((req), (pid), (addr), (data), (data_size))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000220#endif
221
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000222//------------------------------------------------------------------------------
223// Static implementations of ProcessMonitor::ReadMemory and
224// ProcessMonitor::WriteMemory. This enables mutual recursion between these
225// functions without needed to go thru the thread funnel.
226
227static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000228DoReadMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000229 lldb::addr_t vm_addr, void *buf, size_t size, Error &error)
230{
Greg Clayton542e4072012-09-07 17:49:29 +0000231 // ptrace word size is determined by the host, not the child
232 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000233 unsigned char *dst = static_cast<unsigned char*>(buf);
234 size_t bytes_read;
235 size_t remainder;
236 long data;
237
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000238 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000239 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000240 ProcessPOSIXLog::IncNestLevel();
241 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000242 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000243 pid, word_size, (void*)vm_addr, buf, size);
244
245 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000246 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
247 {
248 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000249 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, NULL, 0);
250 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000251 {
252 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000253 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000254 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000255 return bytes_read;
256 }
257
258 remainder = size - bytes_read;
259 remainder = remainder > word_size ? word_size : remainder;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000260
261 // Copy the data into our buffer
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000262 for (unsigned i = 0; i < remainder; ++i)
263 dst[i] = ((data >> i*8) & 0xFF);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000264
Johnny Chen30213ff2012-01-05 19:17:38 +0000265 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
266 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
267 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
268 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Daniel Maleac63dddd2012-12-14 21:07:07 +0000269 {
270 uintptr_t print_dst = 0;
271 // Format bytes from data by moving into print_dst for log output
272 for (unsigned i = 0; i < remainder; ++i)
273 print_dst |= (((data >> i*8) & 0xFF) << i*8);
274 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
275 (void*)vm_addr, print_dst, (unsigned long)data);
276 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000277
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000278 vm_addr += word_size;
279 dst += word_size;
280 }
281
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000282 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000283 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000284 return bytes_read;
285}
286
287static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000288DoWriteMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000289 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
290{
Greg Clayton542e4072012-09-07 17:49:29 +0000291 // ptrace word size is determined by the host, not the child
292 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000293 const unsigned char *src = static_cast<const unsigned char*>(buf);
294 size_t bytes_written = 0;
295 size_t remainder;
296
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000297 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000298 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000299 ProcessPOSIXLog::IncNestLevel();
300 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000301 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000302 pid, word_size, (void*)vm_addr, buf, size);
303
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000304 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
305 {
306 remainder = size - bytes_written;
307 remainder = remainder > word_size ? word_size : remainder;
308
309 if (remainder == word_size)
310 {
311 unsigned long data = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000312 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000313 for (unsigned i = 0; i < word_size; ++i)
314 data |= (unsigned long)src[i] << i*8;
315
Johnny Chen30213ff2012-01-05 19:17:38 +0000316 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
317 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
318 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
319 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000320 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
321 (void*)vm_addr, *(unsigned long*)src, data);
322
Matt Kopec7de48462013-03-06 17:20:48 +0000323 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000324 {
325 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000326 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000327 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000328 return bytes_written;
329 }
330 }
331 else
332 {
333 unsigned char buff[8];
Greg Clayton542e4072012-09-07 17:49:29 +0000334 if (DoReadMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000335 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000336 {
337 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000338 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000339 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000340 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000341
342 memcpy(buff, src, remainder);
343
Greg Clayton542e4072012-09-07 17:49:29 +0000344 if (DoWriteMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000345 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000346 {
347 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000348 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000349 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000350 }
351
Johnny Chen30213ff2012-01-05 19:17:38 +0000352 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
353 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
354 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
355 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000356 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
357 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000358 }
359
360 vm_addr += word_size;
361 src += word_size;
362 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000363 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000364 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000365 return bytes_written;
366}
367
Stephen Wilson26977162011-03-23 02:14:42 +0000368// Simple helper function to ensure flags are enabled on the given file
369// descriptor.
370static bool
371EnsureFDFlags(int fd, int flags, Error &error)
372{
373 int status;
374
375 if ((status = fcntl(fd, F_GETFL)) == -1)
376 {
377 error.SetErrorToErrno();
378 return false;
379 }
380
381 if (fcntl(fd, F_SETFL, status | flags) == -1)
382 {
383 error.SetErrorToErrno();
384 return false;
385 }
386
387 return true;
388}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000389
390//------------------------------------------------------------------------------
391/// @class Operation
392/// @brief Represents a ProcessMonitor operation.
393///
394/// Under Linux, it is not possible to ptrace() from any other thread but the
395/// one that spawned or attached to the process from the start. Therefore, when
396/// a ProcessMonitor is asked to deliver or change the state of an inferior
397/// process the operation must be "funneled" to a specific thread to perform the
398/// task. The Operation class provides an abstract base for all services the
399/// ProcessMonitor must perform via the single virtual function Execute, thus
400/// encapsulating the code that needs to run in the privileged context.
401class Operation
402{
403public:
Daniel Maleadd15b782013-05-13 17:32:07 +0000404 virtual ~Operation() {}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000405 virtual void Execute(ProcessMonitor *monitor) = 0;
406};
407
408//------------------------------------------------------------------------------
409/// @class ReadOperation
410/// @brief Implements ProcessMonitor::ReadMemory.
411class ReadOperation : public Operation
412{
413public:
414 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
415 Error &error, size_t &result)
416 : m_addr(addr), m_buff(buff), m_size(size),
417 m_error(error), m_result(result)
418 { }
419
420 void Execute(ProcessMonitor *monitor);
421
422private:
423 lldb::addr_t m_addr;
424 void *m_buff;
425 size_t m_size;
426 Error &m_error;
427 size_t &m_result;
428};
429
430void
431ReadOperation::Execute(ProcessMonitor *monitor)
432{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000433 lldb::pid_t pid = monitor->GetPID();
434
Greg Clayton542e4072012-09-07 17:49:29 +0000435 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000436}
437
438//------------------------------------------------------------------------------
Ed Mastea56115f2013-07-17 14:30:26 +0000439/// @class WriteOperation
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000440/// @brief Implements ProcessMonitor::WriteMemory.
441class WriteOperation : public Operation
442{
443public:
444 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
445 Error &error, size_t &result)
446 : m_addr(addr), m_buff(buff), m_size(size),
447 m_error(error), m_result(result)
448 { }
449
450 void Execute(ProcessMonitor *monitor);
451
452private:
453 lldb::addr_t m_addr;
454 const void *m_buff;
455 size_t m_size;
456 Error &m_error;
457 size_t &m_result;
458};
459
460void
461WriteOperation::Execute(ProcessMonitor *monitor)
462{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000463 lldb::pid_t pid = monitor->GetPID();
464
Greg Clayton542e4072012-09-07 17:49:29 +0000465 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000466}
467
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000468
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000469//------------------------------------------------------------------------------
470/// @class ReadRegOperation
471/// @brief Implements ProcessMonitor::ReadRegisterValue.
472class ReadRegOperation : public Operation
473{
474public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000475 ReadRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000476 RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000477 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000478 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000479 { }
480
481 void Execute(ProcessMonitor *monitor);
482
483private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000484 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000485 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000486 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000487 RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000488 bool &m_result;
489};
490
491void
492ReadRegOperation::Execute(ProcessMonitor *monitor)
493{
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000494 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000495
496 // Set errno to zero so that we can detect a failed peek.
497 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000498 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, NULL, 0);
499 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000500 m_result = false;
501 else
502 {
503 m_value = data;
504 m_result = true;
505 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000506 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000507 log->Printf ("ProcessMonitor::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000508 m_reg_name, data);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000509}
510
511//------------------------------------------------------------------------------
512/// @class WriteRegOperation
513/// @brief Implements ProcessMonitor::WriteRegisterValue.
514class WriteRegOperation : public Operation
515{
516public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000517 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000518 const RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000519 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000520 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000521 { }
522
523 void Execute(ProcessMonitor *monitor);
524
525private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000526 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000527 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000528 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000529 const RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000530 bool &m_result;
531};
532
533void
534WriteRegOperation::Execute(ProcessMonitor *monitor)
535{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000536 void* buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000537 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000538
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000539 buf = (void*) m_value.GetAsUInt64();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000540
541 if (log)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000542 log->Printf ("ProcessMonitor::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Matt Kopec7de48462013-03-06 17:20:48 +0000543 if (PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000544 m_result = false;
545 else
546 m_result = true;
547}
548
549//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000550/// @class ReadGPROperation
551/// @brief Implements ProcessMonitor::ReadGPR.
552class ReadGPROperation : public Operation
553{
554public:
Matt Kopec7de48462013-03-06 17:20:48 +0000555 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
556 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000557 { }
558
559 void Execute(ProcessMonitor *monitor);
560
561private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000562 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000563 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000564 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000565 bool &m_result;
566};
567
568void
569ReadGPROperation::Execute(ProcessMonitor *monitor)
570{
Todd Fialad35f2b92014-06-23 15:59:04 +0000571#ifdef PT_GETREGS
Matt Kopec7de48462013-03-06 17:20:48 +0000572 if (PTRACE(PTRACE_GETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000573 m_result = false;
574 else
575 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000576#else
577 m_result = false;
578#endif
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000579}
580
581//------------------------------------------------------------------------------
582/// @class ReadFPROperation
583/// @brief Implements ProcessMonitor::ReadFPR.
584class ReadFPROperation : public Operation
585{
586public:
Matt Kopec7de48462013-03-06 17:20:48 +0000587 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
588 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000589 { }
590
591 void Execute(ProcessMonitor *monitor);
592
593private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000594 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000595 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000596 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000597 bool &m_result;
598};
599
600void
601ReadFPROperation::Execute(ProcessMonitor *monitor)
602{
Todd Fialad35f2b92014-06-23 15:59:04 +0000603#ifdef PT_GETFPREGS
Matt Kopec7de48462013-03-06 17:20:48 +0000604 if (PTRACE(PTRACE_GETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000605 m_result = false;
606 else
607 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000608#else
609 m_result = false;
610#endif
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000611}
612
613//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000614/// @class ReadRegisterSetOperation
615/// @brief Implements ProcessMonitor::ReadRegisterSet.
616class ReadRegisterSetOperation : public Operation
617{
618public:
619 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
620 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
621 { }
622
623 void Execute(ProcessMonitor *monitor);
624
625private:
626 lldb::tid_t m_tid;
627 void *m_buf;
628 size_t m_buf_size;
629 const unsigned int m_regset;
630 bool &m_result;
631};
632
633void
634ReadRegisterSetOperation::Execute(ProcessMonitor *monitor)
635{
636 if (PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
637 m_result = false;
638 else
639 m_result = true;
640}
641
642//------------------------------------------------------------------------------
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000643/// @class WriteGPROperation
644/// @brief Implements ProcessMonitor::WriteGPR.
645class WriteGPROperation : public Operation
646{
647public:
Matt Kopec7de48462013-03-06 17:20:48 +0000648 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
649 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000650 { }
651
652 void Execute(ProcessMonitor *monitor);
653
654private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000655 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000656 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000657 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000658 bool &m_result;
659};
660
661void
662WriteGPROperation::Execute(ProcessMonitor *monitor)
663{
Todd Fialad35f2b92014-06-23 15:59:04 +0000664#ifdef PT_SETREGS
Matt Kopec7de48462013-03-06 17:20:48 +0000665 if (PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000666 m_result = false;
667 else
668 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000669#else
670 m_result = false;
671#endif
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000672}
673
674//------------------------------------------------------------------------------
675/// @class WriteFPROperation
676/// @brief Implements ProcessMonitor::WriteFPR.
677class WriteFPROperation : public Operation
678{
679public:
Matt Kopec7de48462013-03-06 17:20:48 +0000680 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
681 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000682 { }
683
684 void Execute(ProcessMonitor *monitor);
685
686private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000687 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000688 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000689 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000690 bool &m_result;
691};
692
693void
694WriteFPROperation::Execute(ProcessMonitor *monitor)
695{
Todd Fialad35f2b92014-06-23 15:59:04 +0000696#ifdef PT_SETFPREGS
Matt Kopec7de48462013-03-06 17:20:48 +0000697 if (PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000698 m_result = false;
699 else
700 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000701#else
702 m_result = false;
703#endif
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000704}
705
706//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000707/// @class WriteRegisterSetOperation
708/// @brief Implements ProcessMonitor::WriteRegisterSet.
709class WriteRegisterSetOperation : public Operation
710{
711public:
712 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
713 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
714 { }
715
716 void Execute(ProcessMonitor *monitor);
717
718private:
719 lldb::tid_t m_tid;
720 void *m_buf;
721 size_t m_buf_size;
722 const unsigned int m_regset;
723 bool &m_result;
724};
725
726void
727WriteRegisterSetOperation::Execute(ProcessMonitor *monitor)
728{
729 if (PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
730 m_result = false;
731 else
732 m_result = true;
733}
734
735//------------------------------------------------------------------------------
Richard Mitton0a558352013-10-17 21:14:00 +0000736/// @class ReadThreadPointerOperation
737/// @brief Implements ProcessMonitor::ReadThreadPointer.
738class ReadThreadPointerOperation : public Operation
739{
740public:
741 ReadThreadPointerOperation(lldb::tid_t tid, lldb::addr_t *addr, bool &result)
742 : m_tid(tid), m_addr(addr), m_result(result)
743 { }
744
745 void Execute(ProcessMonitor *monitor);
746
747private:
748 lldb::tid_t m_tid;
749 lldb::addr_t *m_addr;
750 bool &m_result;
751};
752
753void
754ReadThreadPointerOperation::Execute(ProcessMonitor *monitor)
755{
756 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
757 if (log)
758 log->Printf ("ProcessMonitor::%s()", __FUNCTION__);
759
760 // The process for getting the thread area on Linux is
761 // somewhat... obscure. There's several different ways depending on
762 // what arch you're on, and what kernel version you have.
763
764 const ArchSpec& arch = monitor->GetProcess().GetTarget().GetArchitecture();
765 switch(arch.GetMachine())
766 {
Todd Fiala720cd3f2014-06-16 14:49:28 +0000767#if defined(__i386__) || defined(__x86_64__)
768 // Note that struct user below has a field named i387 which is x86-specific.
769 // Therefore, this case should be compiled only for x86-based systems.
Richard Mitton0a558352013-10-17 21:14:00 +0000770 case llvm::Triple::x86:
771 {
772 // Find the GS register location for our host architecture.
773 size_t gs_user_offset = offsetof(struct user, regs);
774#ifdef __x86_64__
775 gs_user_offset += offsetof(struct user_regs_struct, gs);
776#endif
777#ifdef __i386__
778 gs_user_offset += offsetof(struct user_regs_struct, xgs);
779#endif
780
781 // Read the GS register value to get the selector.
782 errno = 0;
783 long gs = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)gs_user_offset, NULL, 0);
784 if (errno)
785 {
786 m_result = false;
787 break;
788 }
789
790 // Read the LDT base for that selector.
791 uint32_t tmp[4];
792 m_result = (PTRACE(PTRACE_GET_THREAD_AREA, m_tid, (void *)(gs >> 3), &tmp, 0) == 0);
793 *m_addr = tmp[1];
794 break;
795 }
Todd Fiala720cd3f2014-06-16 14:49:28 +0000796#endif
Richard Mitton0a558352013-10-17 21:14:00 +0000797 case llvm::Triple::x86_64:
798 // Read the FS register base.
799 m_result = (PTRACE(PTRACE_ARCH_PRCTL, m_tid, m_addr, (void *)ARCH_GET_FS, 0) == 0);
800 break;
801 default:
802 m_result = false;
803 break;
804 }
805}
806
807//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000808/// @class ResumeOperation
809/// @brief Implements ProcessMonitor::Resume.
810class ResumeOperation : public Operation
811{
812public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000813 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
814 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000815
816 void Execute(ProcessMonitor *monitor);
817
818private:
819 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000820 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000821 bool &m_result;
822};
823
824void
825ResumeOperation::Execute(ProcessMonitor *monitor)
826{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000827 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000828
829 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
830 data = m_signo;
831
Matt Kopec7de48462013-03-06 17:20:48 +0000832 if (PTRACE(PTRACE_CONT, m_tid, NULL, (void*)data, 0))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000833 {
834 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
835
836 if (log)
837 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, strerror(errno));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000838 m_result = false;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000839 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000840 else
841 m_result = true;
842}
843
844//------------------------------------------------------------------------------
Ed Maste428a6782013-06-24 15:04:47 +0000845/// @class SingleStepOperation
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000846/// @brief Implements ProcessMonitor::SingleStep.
847class SingleStepOperation : public Operation
848{
849public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000850 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
851 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000852
853 void Execute(ProcessMonitor *monitor);
854
855private:
856 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000857 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000858 bool &m_result;
859};
860
861void
862SingleStepOperation::Execute(ProcessMonitor *monitor)
863{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000864 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000865
866 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
867 data = m_signo;
868
Matt Kopec7de48462013-03-06 17:20:48 +0000869 if (PTRACE(PTRACE_SINGLESTEP, m_tid, NULL, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000870 m_result = false;
871 else
872 m_result = true;
873}
874
875//------------------------------------------------------------------------------
876/// @class SiginfoOperation
877/// @brief Implements ProcessMonitor::GetSignalInfo.
878class SiginfoOperation : public Operation
879{
880public:
Daniel Maleaa35970a2012-11-23 18:09:58 +0000881 SiginfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
882 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000883
884 void Execute(ProcessMonitor *monitor);
885
886private:
887 lldb::tid_t m_tid;
888 void *m_info;
889 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000890 int &m_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000891};
892
893void
894SiginfoOperation::Execute(ProcessMonitor *monitor)
895{
Matt Kopec7de48462013-03-06 17:20:48 +0000896 if (PTRACE(PTRACE_GETSIGINFO, m_tid, NULL, m_info, 0)) {
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000897 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000898 m_err = errno;
899 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000900 else
901 m_result = true;
902}
903
904//------------------------------------------------------------------------------
905/// @class EventMessageOperation
906/// @brief Implements ProcessMonitor::GetEventMessage.
907class EventMessageOperation : public Operation
908{
909public:
910 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
911 : m_tid(tid), m_message(message), m_result(result) { }
912
913 void Execute(ProcessMonitor *monitor);
914
915private:
916 lldb::tid_t m_tid;
917 unsigned long *m_message;
918 bool &m_result;
919};
920
921void
922EventMessageOperation::Execute(ProcessMonitor *monitor)
923{
Matt Kopec7de48462013-03-06 17:20:48 +0000924 if (PTRACE(PTRACE_GETEVENTMSG, m_tid, NULL, m_message, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000925 m_result = false;
926 else
927 m_result = true;
928}
929
930//------------------------------------------------------------------------------
Ed Maste263c9282014-03-17 17:45:53 +0000931/// @class DetachOperation
932/// @brief Implements ProcessMonitor::Detach.
Greg Clayton28041352011-11-29 20:50:10 +0000933class DetachOperation : public Operation
934{
935public:
Matt Kopec085d6ce2013-05-31 22:00:07 +0000936 DetachOperation(lldb::tid_t tid, Error &result) : m_tid(tid), m_error(result) { }
Greg Clayton28041352011-11-29 20:50:10 +0000937
938 void Execute(ProcessMonitor *monitor);
939
940private:
Matt Kopec085d6ce2013-05-31 22:00:07 +0000941 lldb::tid_t m_tid;
Greg Clayton28041352011-11-29 20:50:10 +0000942 Error &m_error;
943};
944
945void
946DetachOperation::Execute(ProcessMonitor *monitor)
947{
Matt Kopec085d6ce2013-05-31 22:00:07 +0000948 if (ptrace(PT_DETACH, m_tid, NULL, 0) < 0)
Greg Clayton28041352011-11-29 20:50:10 +0000949 m_error.SetErrorToErrno();
Greg Clayton28041352011-11-29 20:50:10 +0000950}
951
Johnny Chen25e68e32011-06-14 19:19:50 +0000952ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
953 : m_monitor(monitor)
954{
955 sem_init(&m_semaphore, 0, 0);
956}
957
958ProcessMonitor::OperationArgs::~OperationArgs()
959{
960 sem_destroy(&m_semaphore);
961}
962
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000963ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
964 lldb_private::Module *module,
965 char const **argv,
966 char const **envp,
967 const char *stdin_path,
968 const char *stdout_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000969 const char *stderr_path,
970 const char *working_dir)
Johnny Chen25e68e32011-06-14 19:19:50 +0000971 : OperationArgs(monitor),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000972 m_module(module),
973 m_argv(argv),
974 m_envp(envp),
975 m_stdin_path(stdin_path),
976 m_stdout_path(stdout_path),
Daniel Malea6217d2a2013-01-08 14:49:22 +0000977 m_stderr_path(stderr_path),
978 m_working_dir(working_dir) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000979
980ProcessMonitor::LaunchArgs::~LaunchArgs()
Johnny Chen25e68e32011-06-14 19:19:50 +0000981{ }
982
983ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
984 lldb::pid_t pid)
985 : OperationArgs(monitor), m_pid(pid) { }
986
987ProcessMonitor::AttachArgs::~AttachArgs()
988{ }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000989
990//------------------------------------------------------------------------------
991/// The basic design of the ProcessMonitor is built around two threads.
992///
993/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
994/// for changes in the debugee state. When a change is detected a
995/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
996/// "drives" state changes in the debugger.
997///
998/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000999/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001000/// operations such as register reads/writes, stepping, etc. See the comments
1001/// on the Operation class for more info as to why this is needed.
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001002ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001003 Module *module,
1004 const char *argv[],
1005 const char *envp[],
1006 const char *stdin_path,
1007 const char *stdout_path,
1008 const char *stderr_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001009 const char *working_dir,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001010 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001011 : m_process(static_cast<ProcessLinux *>(process)),
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001012 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +00001013 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001014 m_pid(LLDB_INVALID_PROCESS_ID),
1015 m_terminal_fd(-1),
Daniel Malea1efb4182013-09-16 23:12:18 +00001016 m_operation(0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001017{
Daniel Malea1efb4182013-09-16 23:12:18 +00001018 std::unique_ptr<LaunchArgs> args(new LaunchArgs(this, module, argv, envp,
1019 stdin_path, stdout_path, stderr_path,
1020 working_dir));
Stephen Wilson57740ec2011-01-15 00:12:41 +00001021
Daniel Malea1efb4182013-09-16 23:12:18 +00001022 sem_init(&m_operation_pending, 0, 0);
1023 sem_init(&m_operation_done, 0, 0);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001024
Johnny Chen25e68e32011-06-14 19:19:50 +00001025 StartLaunchOpThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001026 if (!error.Success())
1027 return;
1028
1029WAIT_AGAIN:
1030 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +00001031 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001032 {
1033 if (errno == EINTR)
1034 goto WAIT_AGAIN;
1035 else
1036 {
1037 error.SetErrorToErrno();
1038 return;
1039 }
1040 }
1041
1042 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +00001043 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001044 {
Greg Clayton743ecf42012-10-16 20:20:18 +00001045 StopOpThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +00001046 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001047 return;
1048 }
1049
1050 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +00001051 m_monitor_thread = Host::StartMonitoringChildProcess(
1052 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Stephen Wilsond4182f42011-02-09 20:10:35 +00001053 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001054 {
1055 error.SetErrorToGenericError();
1056 error.SetErrorString("Process launch failed.");
1057 return;
1058 }
1059}
1060
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001061ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen25e68e32011-06-14 19:19:50 +00001062 lldb::pid_t pid,
1063 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001064 : m_process(static_cast<ProcessLinux *>(process)),
Johnny Chen25e68e32011-06-14 19:19:50 +00001065 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +00001066 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Johnny Chen25e68e32011-06-14 19:19:50 +00001067 m_pid(LLDB_INVALID_PROCESS_ID),
1068 m_terminal_fd(-1),
Daniel Malea1efb4182013-09-16 23:12:18 +00001069 m_operation(0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001070{
Daniel Malea1efb4182013-09-16 23:12:18 +00001071 sem_init(&m_operation_pending, 0, 0);
1072 sem_init(&m_operation_done, 0, 0);
Johnny Chen25e68e32011-06-14 19:19:50 +00001073
Daniel Malea1efb4182013-09-16 23:12:18 +00001074 std::unique_ptr<AttachArgs> args(new AttachArgs(this, pid));
Johnny Chen25e68e32011-06-14 19:19:50 +00001075
1076 StartAttachOpThread(args.get(), error);
1077 if (!error.Success())
1078 return;
1079
1080WAIT_AGAIN:
1081 // Wait for the operation thread to initialize.
1082 if (sem_wait(&args->m_semaphore))
1083 {
1084 if (errno == EINTR)
1085 goto WAIT_AGAIN;
1086 else
1087 {
1088 error.SetErrorToErrno();
1089 return;
1090 }
1091 }
1092
Greg Clayton743ecf42012-10-16 20:20:18 +00001093 // Check that the attach was a success.
Johnny Chen25e68e32011-06-14 19:19:50 +00001094 if (!args->m_error.Success())
1095 {
Greg Clayton743ecf42012-10-16 20:20:18 +00001096 StopOpThread();
Johnny Chen25e68e32011-06-14 19:19:50 +00001097 error = args->m_error;
1098 return;
1099 }
1100
1101 // Finally, start monitoring the child process for change in state.
1102 m_monitor_thread = Host::StartMonitoringChildProcess(
1103 ProcessMonitor::MonitorCallback, this, GetPID(), true);
1104 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
1105 {
1106 error.SetErrorToGenericError();
1107 error.SetErrorString("Process attach failed.");
1108 return;
1109 }
1110}
1111
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001112ProcessMonitor::~ProcessMonitor()
1113{
Stephen Wilson84ffe702011-03-30 15:55:52 +00001114 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001115}
1116
1117//------------------------------------------------------------------------------
1118// Thread setup and tear down.
1119void
Johnny Chen25e68e32011-06-14 19:19:50 +00001120ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001121{
1122 static const char *g_thread_name = "lldb.process.linux.operation";
1123
Stephen Wilsond4182f42011-02-09 20:10:35 +00001124 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001125 return;
1126
1127 m_operation_thread =
Johnny Chen25e68e32011-06-14 19:19:50 +00001128 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001129}
1130
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001131void *
Johnny Chen25e68e32011-06-14 19:19:50 +00001132ProcessMonitor::LaunchOpThread(void *arg)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001133{
1134 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1135
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001136 if (!Launch(args)) {
1137 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001138 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001139 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001140
Stephen Wilson570243b2011-01-19 01:37:06 +00001141 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001142 return NULL;
1143}
1144
1145bool
1146ProcessMonitor::Launch(LaunchArgs *args)
1147{
1148 ProcessMonitor *monitor = args->m_monitor;
1149 ProcessLinux &process = monitor->GetProcess();
1150 const char **argv = args->m_argv;
1151 const char **envp = args->m_envp;
1152 const char *stdin_path = args->m_stdin_path;
1153 const char *stdout_path = args->m_stdout_path;
1154 const char *stderr_path = args->m_stderr_path;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001155 const char *working_dir = args->m_working_dir;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001156
1157 lldb_utility::PseudoTerminal terminal;
1158 const size_t err_len = 1024;
1159 char err_str[err_len];
1160 lldb::pid_t pid;
1161
1162 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001163 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001164
Stephen Wilson57740ec2011-01-15 00:12:41 +00001165 // Propagate the environment if one is not supplied.
1166 if (envp == NULL || envp[0] == NULL)
1167 envp = const_cast<const char **>(environ);
1168
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001169 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t>(-1))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001170 {
1171 args->m_error.SetErrorToGenericError();
1172 args->m_error.SetErrorString("Process fork failed.");
1173 goto FINISH;
1174 }
1175
Peter Collingbourne6a520222011-06-14 03:55:58 +00001176 // Recognized child exit status codes.
1177 enum {
1178 ePtraceFailed = 1,
1179 eDupStdinFailed,
1180 eDupStdoutFailed,
1181 eDupStderrFailed,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001182 eChdirFailed,
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001183 eExecFailed,
1184 eSetGidFailed
Peter Collingbourne6a520222011-06-14 03:55:58 +00001185 };
1186
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001187 // Child process.
1188 if (pid == 0)
1189 {
1190 // Trace this process.
Matt Kopec7de48462013-03-06 17:20:48 +00001191 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL, 0) < 0)
Peter Collingbourne6a520222011-06-14 03:55:58 +00001192 exit(ePtraceFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001193
1194 // Do not inherit setgid powers.
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001195 if (setgid(getgid()) != 0)
1196 exit(eSetGidFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001197
1198 // Let us have our own process group.
1199 setpgid(0, 0);
1200
Greg Clayton710dd5a2011-01-08 20:28:42 +00001201 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001202 //
1203 // FIXME: If two or more of the paths are the same we needlessly open
1204 // the same file multiple times.
1205 if (stdin_path != NULL && stdin_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001206 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001207 exit(eDupStdinFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001208
1209 if (stdout_path != NULL && stdout_path[0])
1210 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001211 exit(eDupStdoutFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001212
1213 if (stderr_path != NULL && stderr_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001214 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001215 exit(eDupStderrFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001216
Daniel Malea6217d2a2013-01-08 14:49:22 +00001217 // Change working directory
1218 if (working_dir != NULL && working_dir[0])
1219 if (0 != ::chdir(working_dir))
1220 exit(eChdirFailed);
1221
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001222 // Execute. We should never return.
1223 execve(argv[0],
1224 const_cast<char *const *>(argv),
1225 const_cast<char *const *>(envp));
Peter Collingbourne6a520222011-06-14 03:55:58 +00001226 exit(eExecFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001227 }
1228
1229 // Wait for the child process to to trap on its call to execve.
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001230 lldb::pid_t wpid;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001231 int status;
Peter Collingbourne6a520222011-06-14 03:55:58 +00001232 if ((wpid = waitpid(pid, &status, 0)) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001233 {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001234 args->m_error.SetErrorToErrno();
1235 goto FINISH;
1236 }
Peter Collingbourne6a520222011-06-14 03:55:58 +00001237 else if (WIFEXITED(status))
1238 {
1239 // open, dup or execve likely failed for some reason.
1240 args->m_error.SetErrorToGenericError();
1241 switch (WEXITSTATUS(status))
1242 {
Greg Clayton542e4072012-09-07 17:49:29 +00001243 case ePtraceFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001244 args->m_error.SetErrorString("Child ptrace failed.");
1245 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001246 case eDupStdinFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001247 args->m_error.SetErrorString("Child open stdin failed.");
1248 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001249 case eDupStdoutFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001250 args->m_error.SetErrorString("Child open stdout failed.");
1251 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001252 case eDupStderrFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001253 args->m_error.SetErrorString("Child open stderr failed.");
1254 break;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001255 case eChdirFailed:
1256 args->m_error.SetErrorString("Child failed to set working directory.");
1257 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001258 case eExecFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001259 args->m_error.SetErrorString("Child exec failed.");
1260 break;
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001261 case eSetGidFailed:
1262 args->m_error.SetErrorString("Child setgid failed.");
1263 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001264 default:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001265 args->m_error.SetErrorString("Child returned unknown exit status.");
1266 break;
1267 }
1268 goto FINISH;
1269 }
1270 assert(WIFSTOPPED(status) && wpid == pid &&
1271 "Could not sync with inferior process.");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001272
Matt Kopec085d6ce2013-05-31 22:00:07 +00001273 if (!SetDefaultPtraceOpts(pid))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001274 {
1275 args->m_error.SetErrorToErrno();
1276 goto FINISH;
1277 }
1278
1279 // Release the master terminal descriptor and pass it off to the
1280 // ProcessMonitor instance. Similarly stash the inferior pid.
1281 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1282 monitor->m_pid = pid;
1283
Stephen Wilson26977162011-03-23 02:14:42 +00001284 // Set the terminal fd to be in non blocking mode (it simplifies the
1285 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1286 // descriptor to read from).
1287 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1288 goto FINISH;
1289
Johnny Chen30213ff2012-01-05 19:17:38 +00001290 // Update the process thread list with this new thread.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001291 // FIXME: should we be letting UpdateThreadList handle this?
1292 // FIXME: by using pids instead of tids, we can only support one thread.
Michael Sartain9f822cd2013-07-31 23:27:46 +00001293 inferior.reset(process.CreateNewPOSIXThread(process, pid));
Matt Kopecfb6ab542013-07-10 20:53:11 +00001294
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001295 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001296 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001297 process.GetThreadList().AddThread(inferior);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001298
Matt Kopecb2910442013-07-09 15:09:45 +00001299 process.AddThreadForInitialStopIfNeeded(pid);
1300
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001301 // Let our process instance know the thread has stopped.
1302 process.SendMessage(ProcessMessage::Trace(pid));
1303
1304FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001305 return args->m_error.Success();
1306}
1307
Johnny Chen25e68e32011-06-14 19:19:50 +00001308void
1309ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1310{
1311 static const char *g_thread_name = "lldb.process.linux.operation";
1312
1313 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1314 return;
1315
1316 m_operation_thread =
1317 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1318}
1319
Johnny Chen25e68e32011-06-14 19:19:50 +00001320void *
1321ProcessMonitor::AttachOpThread(void *arg)
1322{
1323 AttachArgs *args = static_cast<AttachArgs*>(arg);
1324
Greg Clayton743ecf42012-10-16 20:20:18 +00001325 if (!Attach(args)) {
1326 sem_post(&args->m_semaphore);
Johnny Chen25e68e32011-06-14 19:19:50 +00001327 return NULL;
Greg Clayton743ecf42012-10-16 20:20:18 +00001328 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001329
1330 ServeOperation(args);
1331 return NULL;
1332}
1333
1334bool
1335ProcessMonitor::Attach(AttachArgs *args)
1336{
1337 lldb::pid_t pid = args->m_pid;
1338
1339 ProcessMonitor *monitor = args->m_monitor;
1340 ProcessLinux &process = monitor->GetProcess();
Johnny Chen25e68e32011-06-14 19:19:50 +00001341 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001342 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen25e68e32011-06-14 19:19:50 +00001343
Matt Kopec085d6ce2013-05-31 22:00:07 +00001344 // Use a map to keep track of the threads which we have attached/need to attach.
1345 Host::TidMap tids_to_attach;
Johnny Chen25e68e32011-06-14 19:19:50 +00001346 if (pid <= 1)
1347 {
1348 args->m_error.SetErrorToGenericError();
1349 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1350 goto FINISH;
1351 }
1352
Matt Kopec085d6ce2013-05-31 22:00:07 +00001353 while (Host::FindProcessThreads(pid, tids_to_attach))
Johnny Chen25e68e32011-06-14 19:19:50 +00001354 {
Matt Kopec085d6ce2013-05-31 22:00:07 +00001355 for (Host::TidMap::iterator it = tids_to_attach.begin();
1356 it != tids_to_attach.end(); ++it)
1357 {
1358 if (it->second == false)
1359 {
1360 lldb::tid_t tid = it->first;
1361
1362 // Attach to the requested process.
1363 // An attach will cause the thread to stop with a SIGSTOP.
1364 if (PTRACE(PTRACE_ATTACH, tid, NULL, NULL, 0) < 0)
1365 {
1366 // No such thread. The thread may have exited.
1367 // More error handling may be needed.
1368 if (errno == ESRCH)
1369 {
1370 tids_to_attach.erase(it);
1371 continue;
1372 }
1373 else
1374 {
1375 args->m_error.SetErrorToErrno();
1376 goto FINISH;
1377 }
1378 }
1379
1380 int status;
1381 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1382 // At this point we should have a thread stopped if waitpid succeeds.
1383 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1384 {
1385 // No such thread. The thread may have exited.
1386 // More error handling may be needed.
1387 if (errno == ESRCH)
1388 {
1389 tids_to_attach.erase(it);
1390 continue;
1391 }
1392 else
1393 {
1394 args->m_error.SetErrorToErrno();
1395 goto FINISH;
1396 }
1397 }
1398
1399 if (!SetDefaultPtraceOpts(tid))
1400 {
1401 args->m_error.SetErrorToErrno();
1402 goto FINISH;
1403 }
1404
1405 // Update the process thread list with the attached thread.
Michael Sartain9f822cd2013-07-31 23:27:46 +00001406 inferior.reset(process.CreateNewPOSIXThread(process, tid));
Matt Kopecfb6ab542013-07-10 20:53:11 +00001407
Matt Kopec085d6ce2013-05-31 22:00:07 +00001408 if (log)
1409 log->Printf ("ProcessMonitor::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1410 process.GetThreadList().AddThread(inferior);
1411 it->second = true;
Matt Kopecb2910442013-07-09 15:09:45 +00001412 process.AddThreadForInitialStopIfNeeded(tid);
Matt Kopec085d6ce2013-05-31 22:00:07 +00001413 }
1414 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001415 }
1416
Matt Kopec085d6ce2013-05-31 22:00:07 +00001417 if (tids_to_attach.size() > 0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001418 {
Matt Kopec085d6ce2013-05-31 22:00:07 +00001419 monitor->m_pid = pid;
1420 // Let our process instance know the thread has stopped.
1421 process.SendMessage(ProcessMessage::Trace(pid));
Johnny Chen25e68e32011-06-14 19:19:50 +00001422 }
Matt Kopec085d6ce2013-05-31 22:00:07 +00001423 else
1424 {
1425 args->m_error.SetErrorToGenericError();
1426 args->m_error.SetErrorString("No such process.");
1427 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001428
1429 FINISH:
1430 return args->m_error.Success();
1431}
1432
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001433bool
Matt Kopec085d6ce2013-05-31 22:00:07 +00001434ProcessMonitor::SetDefaultPtraceOpts(lldb::pid_t pid)
1435{
1436 long ptrace_opts = 0;
1437
1438 // Have the child raise an event on exit. This is used to keep the child in
1439 // limbo until it is destroyed.
1440 ptrace_opts |= PTRACE_O_TRACEEXIT;
1441
1442 // Have the tracer trace threads which spawn in the inferior process.
1443 // TODO: if we want to support tracing the inferiors' child, add the
1444 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1445 ptrace_opts |= PTRACE_O_TRACECLONE;
1446
1447 // Have the tracer notify us before execve returns
1448 // (needed to disable legacy SIGTRAP generation)
1449 ptrace_opts |= PTRACE_O_TRACEEXEC;
1450
1451 return PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)ptrace_opts, 0) >= 0;
1452}
1453
1454bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001455ProcessMonitor::MonitorCallback(void *callback_baton,
1456 lldb::pid_t pid,
Peter Collingbourne2c67b9a2011-11-21 00:10:19 +00001457 bool exited,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001458 int signal,
1459 int status)
1460{
1461 ProcessMessage message;
1462 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001463 ProcessLinux *process = monitor->m_process;
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001464 assert(process);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001465 bool stop_monitoring;
1466 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001467 int ptrace_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001468
Andrew Kaylor93132f52013-05-28 23:04:25 +00001469 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1470
1471 if (exited)
1472 {
1473 if (log)
1474 log->Printf ("ProcessMonitor::%s() got exit signal, tid = %" PRIu64, __FUNCTION__, pid);
1475 message = ProcessMessage::Exit(pid, status);
1476 process->SendMessage(message);
1477 return pid == process->GetID();
1478 }
1479
Daniel Maleaa35970a2012-11-23 18:09:58 +00001480 if (!monitor->GetSignalInfo(pid, &info, ptrace_err)) {
1481 if (ptrace_err == EINVAL) {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001482 if (log)
1483 log->Printf ("ProcessMonitor::%s() resuming from group-stop", __FUNCTION__);
Daniel Maleaa35970a2012-11-23 18:09:58 +00001484 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1485 if (!monitor->Resume(pid, SIGSTOP)) {
1486 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1487 }
1488 stop_monitoring = false;
1489 } else {
1490 // ptrace(GETSIGINFO) failed (but not due to group-stop). Most likely,
1491 // this means the child pid is gone (or not being debugged) therefore
Andrew Kaylor93132f52013-05-28 23:04:25 +00001492 // stop the monitor thread if this is the main pid.
1493 if (log)
1494 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d",
1495 __FUNCTION__, strerror(ptrace_err), pid, signal, status);
1496 stop_monitoring = pid == monitor->m_process->GetID();
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +00001497 // If we are going to stop monitoring, we need to notify our process object
1498 if (stop_monitoring)
1499 {
1500 message = ProcessMessage::Exit(pid, status);
1501 process->SendMessage(message);
1502 }
Daniel Maleaa35970a2012-11-23 18:09:58 +00001503 }
1504 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00001505 else {
1506 switch (info.si_signo)
1507 {
1508 case SIGTRAP:
1509 message = MonitorSIGTRAP(monitor, &info, pid);
1510 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001511
Stephen Wilson84ffe702011-03-30 15:55:52 +00001512 default:
1513 message = MonitorSignal(monitor, &info, pid);
1514 break;
1515 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001516
Stephen Wilson84ffe702011-03-30 15:55:52 +00001517 process->SendMessage(message);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001518 stop_monitoring = false;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001519 }
1520
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001521 return stop_monitoring;
1522}
1523
1524ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +00001525ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001526 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001527{
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001528 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001529
Andrew Kaylor93132f52013-05-28 23:04:25 +00001530 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1531
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001532 assert(monitor);
1533 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001534
Stephen Wilson84ffe702011-03-30 15:55:52 +00001535 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001536 {
1537 default:
1538 assert(false && "Unexpected SIGTRAP code!");
1539 break;
1540
Matt Kopeca360d7e2013-05-17 19:27:47 +00001541 // TODO: these two cases are required if we want to support tracing
1542 // of the inferiors' children
1543 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1544 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1545
Matt Kopec650648f2013-01-08 16:30:18 +00001546 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1547 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001548 if (log)
1549 log->Printf ("ProcessMonitor::%s() received thread creation event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
1550
Matt Kopec650648f2013-01-08 16:30:18 +00001551 unsigned long tid = 0;
1552 if (!monitor->GetEventMessage(pid, &tid))
1553 tid = -1;
1554 message = ProcessMessage::NewThread(pid, tid);
1555 break;
1556 }
1557
Matt Kopeca360d7e2013-05-17 19:27:47 +00001558 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Matt Kopec718be872013-10-09 19:39:55 +00001559 if (log)
1560 log->Printf ("ProcessMonitor::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
1561
1562 message = ProcessMessage::Exec(pid);
Matt Kopeca360d7e2013-05-17 19:27:47 +00001563 break;
1564
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001565 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1566 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001567 // The inferior process or one of its threads is about to exit.
1568 // Maintain the process or thread in a state of "limbo" until we are
1569 // explicitly commanded to detach, destroy, resume, etc.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001570 unsigned long data = 0;
1571 if (!monitor->GetEventMessage(pid, &data))
1572 data = -1;
Andrew Kaylor93132f52013-05-28 23:04:25 +00001573 if (log)
Matt Kopecb2910442013-07-09 15:09:45 +00001574 log->Printf ("ProcessMonitor::%s() received limbo event, data = %lx, pid = %" PRIu64, __FUNCTION__, data, pid);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001575 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001576 break;
1577 }
1578
1579 case 0:
1580 case TRAP_TRACE:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001581 if (log)
1582 log->Printf ("ProcessMonitor::%s() received trace event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001583 message = ProcessMessage::Trace(pid);
1584 break;
1585
1586 case SI_KERNEL:
1587 case TRAP_BRKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001588 if (log)
1589 log->Printf ("ProcessMonitor::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001590 message = ProcessMessage::Break(pid);
1591 break;
Matt Kopece9ea0da2013-05-07 19:29:28 +00001592
1593 case TRAP_HWBKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001594 if (log)
1595 log->Printf ("ProcessMonitor::%s() received watchpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Matt Kopece9ea0da2013-05-07 19:29:28 +00001596 message = ProcessMessage::Watch(pid, (lldb::addr_t)info->si_addr);
1597 break;
Matt Kopec4a32bf52013-07-11 20:01:22 +00001598
1599 case SIGTRAP:
1600 case (SIGTRAP | 0x80):
1601 if (log)
1602 log->Printf ("ProcessMonitor::%s() received system call stop event, pid = %" PRIu64, __FUNCTION__, pid);
1603 // Ignore these signals until we know more about them
1604 monitor->Resume(pid, eResumeSignalNone);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001605 }
1606
1607 return message;
1608}
1609
Stephen Wilson84ffe702011-03-30 15:55:52 +00001610ProcessMessage
1611ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001612 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001613{
1614 ProcessMessage message;
1615 int signo = info->si_signo;
1616
Andrew Kaylor93132f52013-05-28 23:04:25 +00001617 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1618
Stephen Wilson84ffe702011-03-30 15:55:52 +00001619 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1620 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1621 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1622 //
1623 // IOW, user generated signals never generate what we consider to be a
1624 // "crash".
1625 //
1626 // Similarly, ACK signals generated by this monitor.
1627 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1628 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001629 if (log)
Matt Kopecef143712013-06-03 18:00:07 +00001630 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
Andrew Kaylor93132f52013-05-28 23:04:25 +00001631 __FUNCTION__,
1632 monitor->m_process->GetUnixSignals().GetSignalAsCString (signo),
1633 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1634 info->si_pid);
1635
Stephen Wilson84ffe702011-03-30 15:55:52 +00001636 if (info->si_pid == getpid())
1637 return ProcessMessage::SignalDelivered(pid, signo);
1638 else
1639 return ProcessMessage::Signal(pid, signo);
1640 }
1641
Andrew Kaylor93132f52013-05-28 23:04:25 +00001642 if (log)
1643 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals().GetSignalAsCString (signo));
1644
Stephen Wilson84ffe702011-03-30 15:55:52 +00001645 if (signo == SIGSEGV) {
1646 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1647 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1648 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1649 }
1650
1651 if (signo == SIGILL) {
1652 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1653 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1654 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1655 }
1656
1657 if (signo == SIGFPE) {
1658 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1659 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1660 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1661 }
1662
1663 if (signo == SIGBUS) {
1664 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1665 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1666 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1667 }
1668
1669 // Everything else is "normal" and does not require any special action on
1670 // our part.
1671 return ProcessMessage::Signal(pid, signo);
1672}
1673
Andrew Kaylord4d54992013-09-17 00:30:24 +00001674// On Linux, when a new thread is created, we receive to notifications,
1675// (1) a SIGTRAP|PTRACE_EVENT_CLONE from the main process thread with the
1676// child thread id as additional information, and (2) a SIGSTOP|SI_USER from
1677// the new child thread indicating that it has is stopped because we attached.
1678// We have no guarantee of the order in which these arrive, but we need both
1679// before we are ready to proceed. We currently keep a list of threads which
1680// have sent the initial SIGSTOP|SI_USER event. Then when we receive the
1681// SIGTRAP|PTRACE_EVENT_CLONE notification, if the initial stop has not occurred
1682// we call ProcessMonitor::WaitForInitialTIDStop() to wait for it.
1683
1684bool
1685ProcessMonitor::WaitForInitialTIDStop(lldb::tid_t tid)
1686{
1687 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1688 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001689 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waiting for thread to stop...", __FUNCTION__, tid);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001690
1691 // Wait for the thread to stop
1692 while (true)
1693 {
1694 int status = -1;
1695 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001696 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waitpid...", __FUNCTION__, tid);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001697 lldb::pid_t wait_pid = waitpid(tid, &status, __WALL);
1698 if (status == -1)
1699 {
1700 // If we got interrupted by a signal (in our process, not the
1701 // inferior) try again.
1702 if (errno == EINTR)
1703 continue;
1704 else
1705 {
1706 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001707 log->Printf("ProcessMonitor::%s(%" PRIu64 ") waitpid error -- %s", __FUNCTION__, tid, strerror(errno));
Andrew Kaylord4d54992013-09-17 00:30:24 +00001708 return false; // This is bad, but there's nothing we can do.
1709 }
1710 }
1711
1712 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001713 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waitpid, status = %d", __FUNCTION__, tid, status);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001714
1715 assert(wait_pid == tid);
1716
1717 siginfo_t info;
1718 int ptrace_err;
1719 if (!GetSignalInfo(wait_pid, &info, ptrace_err))
1720 {
1721 if (log)
1722 {
1723 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed. errno=%d (%s)", __FUNCTION__, ptrace_err, strerror(ptrace_err));
1724 }
1725 return false;
1726 }
1727
1728 // If this is a thread exit, we won't get any more information.
1729 if (WIFEXITED(status))
1730 {
1731 m_process->SendMessage(ProcessMessage::Exit(wait_pid, WEXITSTATUS(status)));
1732 if (wait_pid == tid)
1733 return true;
1734 continue;
1735 }
1736
1737 assert(info.si_code == SI_USER);
1738 assert(WSTOPSIG(status) == SIGSTOP);
1739
1740 if (log)
1741 log->Printf ("ProcessMonitor::%s(bp) received thread stop signal", __FUNCTION__);
1742 m_process->AddThreadForInitialStopIfNeeded(wait_pid);
1743 return true;
1744 }
1745 return false;
1746}
1747
Andrew Kaylor93132f52013-05-28 23:04:25 +00001748bool
1749ProcessMonitor::StopThread(lldb::tid_t tid)
1750{
1751 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1752
1753 // FIXME: Try to use tgkill or tkill
1754 int ret = tgkill(m_pid, tid, SIGSTOP);
1755 if (log)
1756 log->Printf ("ProcessMonitor::%s(bp) stopping thread, tid = %" PRIu64 ", ret = %d", __FUNCTION__, tid, ret);
1757
1758 // This can happen if a thread exited while we were trying to stop it. That's OK.
1759 // We'll get the signal for that later.
1760 if (ret < 0)
1761 return false;
1762
1763 // Wait for the thread to stop
1764 while (true)
1765 {
1766 int status = -1;
1767 if (log)
1768 log->Printf ("ProcessMonitor::%s(bp) waitpid...", __FUNCTION__);
Andrew MacPherson82aae0d2014-04-02 06:57:45 +00001769 lldb::pid_t wait_pid = ::waitpid (-1*getpgid(m_pid), &status, __WALL);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001770 if (log)
1771 log->Printf ("ProcessMonitor::%s(bp) waitpid, pid = %" PRIu64 ", status = %d", __FUNCTION__, wait_pid, status);
1772
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001773 if (wait_pid == static_cast<lldb::pid_t>(-1))
Andrew Kaylor93132f52013-05-28 23:04:25 +00001774 {
1775 // If we got interrupted by a signal (in our process, not the
1776 // inferior) try again.
1777 if (errno == EINTR)
1778 continue;
1779 else
1780 return false; // This is bad, but there's nothing we can do.
1781 }
1782
1783 // If this is a thread exit, we won't get any more information.
1784 if (WIFEXITED(status))
1785 {
1786 m_process->SendMessage(ProcessMessage::Exit(wait_pid, WEXITSTATUS(status)));
1787 if (wait_pid == tid)
1788 return true;
1789 continue;
1790 }
1791
1792 siginfo_t info;
1793 int ptrace_err;
1794 if (!GetSignalInfo(wait_pid, &info, ptrace_err))
1795 {
Todd Fiala1b0539c2014-01-27 17:03:57 +00001796 // another signal causing a StopAllThreads may have been received
1797 // before wait_pid's group-stop was processed, handle it now
1798 if (ptrace_err == EINVAL)
Andrew Kaylor93132f52013-05-28 23:04:25 +00001799 {
Todd Fiala1b0539c2014-01-27 17:03:57 +00001800 assert(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001801
Todd Fiala1b0539c2014-01-27 17:03:57 +00001802 if (log)
1803 log->Printf ("ProcessMonitor::%s() resuming from group-stop", __FUNCTION__);
1804 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1805 if (!Resume(wait_pid, SIGSTOP)) {
1806 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1807 }
1808 continue;
Andrew Kaylor93132f52013-05-28 23:04:25 +00001809 }
Todd Fiala1b0539c2014-01-27 17:03:57 +00001810
1811 if (log)
1812 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed.", __FUNCTION__);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001813 return false;
1814 }
1815
1816 // Handle events from other threads
1817 if (log)
Matt Kopecef143712013-06-03 18:00:07 +00001818 log->Printf ("ProcessMonitor::%s(bp) handling event, tid == %" PRIu64, __FUNCTION__, wait_pid);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001819
1820 ProcessMessage message;
1821 if (info.si_signo == SIGTRAP)
1822 message = MonitorSIGTRAP(this, &info, wait_pid);
1823 else
1824 message = MonitorSignal(this, &info, wait_pid);
1825
1826 POSIXThread *thread = static_cast<POSIXThread*>(m_process->GetThreadList().FindThreadByID(wait_pid).get());
1827
1828 // When a new thread is created, we may get a SIGSTOP for the new thread
1829 // just before we get the SIGTRAP that we use to add the thread to our
1830 // process thread list. We don't need to worry about that signal here.
1831 assert(thread || message.GetKind() == ProcessMessage::eSignalMessage);
1832
1833 if (!thread)
1834 {
1835 m_process->SendMessage(message);
1836 continue;
1837 }
1838
1839 switch (message.GetKind())
1840 {
Michael Sartainc258b302013-09-18 15:32:06 +00001841 case ProcessMessage::eAttachMessage:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001842 case ProcessMessage::eInvalidMessage:
1843 break;
1844
1845 // These need special handling because we don't want to send a
1846 // resume even if we already sent a SIGSTOP to this thread. In
1847 // this case the resume will cause the thread to disappear. It is
1848 // unlikely that we'll ever get eExitMessage here, but the same
1849 // reasoning applies.
1850 case ProcessMessage::eLimboMessage:
1851 case ProcessMessage::eExitMessage:
1852 if (log)
1853 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
1854 // SendMessage will set the thread state as needed.
1855 m_process->SendMessage(message);
1856 // If this is the thread we're waiting for, stop waiting. Even
1857 // though this wasn't the signal we expected, it's the last
1858 // signal we'll see while this thread is alive.
1859 if (wait_pid == tid)
1860 return true;
1861 break;
1862
Matt Kopecb2910442013-07-09 15:09:45 +00001863 case ProcessMessage::eSignalMessage:
1864 if (log)
1865 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
1866 if (WSTOPSIG(status) == SIGSTOP)
1867 {
1868 m_process->AddThreadForInitialStopIfNeeded(tid);
1869 thread->SetState(lldb::eStateStopped);
1870 }
1871 else
1872 {
1873 m_process->SendMessage(message);
1874 // This isn't the stop we were expecting, but the thread is
1875 // stopped. SendMessage will handle processing of this event,
1876 // but we need to resume here to get the stop we are waiting
1877 // for (otherwise the thread will stop again immediately when
1878 // we try to resume).
1879 if (wait_pid == tid)
1880 Resume(wait_pid, eResumeSignalNone);
1881 }
1882 break;
1883
Andrew Kaylor93132f52013-05-28 23:04:25 +00001884 case ProcessMessage::eSignalDeliveredMessage:
1885 // This is the stop we're expecting.
1886 if (wait_pid == tid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP && info.si_code == SI_TKILL)
1887 {
1888 if (log)
1889 log->Printf ("ProcessMonitor::%s(bp) received signal, done waiting", __FUNCTION__);
1890 thread->SetState(lldb::eStateStopped);
1891 return true;
1892 }
1893 // else fall-through
Andrew Kaylor93132f52013-05-28 23:04:25 +00001894 case ProcessMessage::eBreakpointMessage:
1895 case ProcessMessage::eTraceMessage:
1896 case ProcessMessage::eWatchpointMessage:
1897 case ProcessMessage::eCrashMessage:
1898 case ProcessMessage::eNewThreadMessage:
1899 if (log)
1900 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
1901 // SendMessage will set the thread state as needed.
1902 m_process->SendMessage(message);
1903 // This isn't the stop we were expecting, but the thread is
1904 // stopped. SendMessage will handle processing of this event,
1905 // but we need to resume here to get the stop we are waiting
1906 // for (otherwise the thread will stop again immediately when
1907 // we try to resume).
1908 if (wait_pid == tid)
1909 Resume(wait_pid, eResumeSignalNone);
1910 break;
1911 }
1912 }
1913 return false;
1914}
1915
Stephen Wilson84ffe702011-03-30 15:55:52 +00001916ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001917ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001918{
1919 ProcessMessage::CrashReason reason;
1920 assert(info->si_signo == SIGSEGV);
1921
1922 reason = ProcessMessage::eInvalidCrashReason;
1923
Greg Clayton542e4072012-09-07 17:49:29 +00001924 switch (info->si_code)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001925 {
1926 default:
1927 assert(false && "unexpected si_code for SIGSEGV");
1928 break;
Matt Kopecf8cfe6b2013-08-09 15:26:56 +00001929 case SI_KERNEL:
1930 // Linux will occasionally send spurious SI_KERNEL codes.
1931 // (this is poorly documented in sigaction)
1932 // One way to get this is via unaligned SIMD loads.
1933 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1934 break;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001935 case SEGV_MAPERR:
1936 reason = ProcessMessage::eInvalidAddress;
1937 break;
1938 case SEGV_ACCERR:
1939 reason = ProcessMessage::ePrivilegedAddress;
1940 break;
1941 }
Greg Clayton542e4072012-09-07 17:49:29 +00001942
Stephen Wilson84ffe702011-03-30 15:55:52 +00001943 return reason;
1944}
1945
1946ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001947ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001948{
1949 ProcessMessage::CrashReason reason;
1950 assert(info->si_signo == SIGILL);
1951
1952 reason = ProcessMessage::eInvalidCrashReason;
1953
1954 switch (info->si_code)
1955 {
1956 default:
1957 assert(false && "unexpected si_code for SIGILL");
1958 break;
1959 case ILL_ILLOPC:
1960 reason = ProcessMessage::eIllegalOpcode;
1961 break;
1962 case ILL_ILLOPN:
1963 reason = ProcessMessage::eIllegalOperand;
1964 break;
1965 case ILL_ILLADR:
1966 reason = ProcessMessage::eIllegalAddressingMode;
1967 break;
1968 case ILL_ILLTRP:
1969 reason = ProcessMessage::eIllegalTrap;
1970 break;
1971 case ILL_PRVOPC:
1972 reason = ProcessMessage::ePrivilegedOpcode;
1973 break;
1974 case ILL_PRVREG:
1975 reason = ProcessMessage::ePrivilegedRegister;
1976 break;
1977 case ILL_COPROC:
1978 reason = ProcessMessage::eCoprocessorError;
1979 break;
1980 case ILL_BADSTK:
1981 reason = ProcessMessage::eInternalStackError;
1982 break;
1983 }
1984
1985 return reason;
1986}
1987
1988ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001989ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001990{
1991 ProcessMessage::CrashReason reason;
1992 assert(info->si_signo == SIGFPE);
1993
1994 reason = ProcessMessage::eInvalidCrashReason;
1995
1996 switch (info->si_code)
1997 {
1998 default:
1999 assert(false && "unexpected si_code for SIGFPE");
2000 break;
2001 case FPE_INTDIV:
2002 reason = ProcessMessage::eIntegerDivideByZero;
2003 break;
2004 case FPE_INTOVF:
2005 reason = ProcessMessage::eIntegerOverflow;
2006 break;
2007 case FPE_FLTDIV:
2008 reason = ProcessMessage::eFloatDivideByZero;
2009 break;
2010 case FPE_FLTOVF:
2011 reason = ProcessMessage::eFloatOverflow;
2012 break;
2013 case FPE_FLTUND:
2014 reason = ProcessMessage::eFloatUnderflow;
2015 break;
2016 case FPE_FLTRES:
2017 reason = ProcessMessage::eFloatInexactResult;
2018 break;
2019 case FPE_FLTINV:
2020 reason = ProcessMessage::eFloatInvalidOperation;
2021 break;
2022 case FPE_FLTSUB:
2023 reason = ProcessMessage::eFloatSubscriptRange;
2024 break;
2025 }
2026
2027 return reason;
2028}
2029
2030ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00002031ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002032{
2033 ProcessMessage::CrashReason reason;
2034 assert(info->si_signo == SIGBUS);
2035
2036 reason = ProcessMessage::eInvalidCrashReason;
2037
2038 switch (info->si_code)
2039 {
2040 default:
2041 assert(false && "unexpected si_code for SIGBUS");
2042 break;
2043 case BUS_ADRALN:
2044 reason = ProcessMessage::eIllegalAlignment;
2045 break;
2046 case BUS_ADRERR:
2047 reason = ProcessMessage::eIllegalAddress;
2048 break;
2049 case BUS_OBJERR:
2050 reason = ProcessMessage::eHardwareError;
2051 break;
2052 }
2053
2054 return reason;
2055}
2056
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002057void
Johnny Chen25e68e32011-06-14 19:19:50 +00002058ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002059{
Stephen Wilson570243b2011-01-19 01:37:06 +00002060 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002061
Stephen Wilson570243b2011-01-19 01:37:06 +00002062 // We are finised with the arguments and are ready to go. Sync with the
2063 // parent thread and start serving operations on the inferior.
2064 sem_post(&args->m_semaphore);
2065
Michael Sartain704bf892013-10-09 01:28:57 +00002066 for(;;)
2067 {
Daniel Malea1efb4182013-09-16 23:12:18 +00002068 // wait for next pending operation
Todd Fiala8ce3dee2014-01-24 22:59:22 +00002069 if (sem_wait(&monitor->m_operation_pending))
2070 {
2071 if (errno == EINTR)
2072 continue;
2073 assert(false && "Unexpected errno from sem_wait");
2074 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002075
Daniel Malea1efb4182013-09-16 23:12:18 +00002076 monitor->m_operation->Execute(monitor);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002077
Daniel Malea1efb4182013-09-16 23:12:18 +00002078 // notify calling thread that operation is complete
2079 sem_post(&monitor->m_operation_done);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002080 }
2081}
2082
2083void
2084ProcessMonitor::DoOperation(Operation *op)
2085{
Daniel Malea1efb4182013-09-16 23:12:18 +00002086 Mutex::Locker lock(m_operation_mutex);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002087
Daniel Malea1efb4182013-09-16 23:12:18 +00002088 m_operation = op;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002089
Daniel Malea1efb4182013-09-16 23:12:18 +00002090 // notify operation thread that an operation is ready to be processed
2091 sem_post(&m_operation_pending);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002092
Daniel Malea1efb4182013-09-16 23:12:18 +00002093 // wait for operation to complete
Todd Fiala8ce3dee2014-01-24 22:59:22 +00002094 while (sem_wait(&m_operation_done))
2095 {
2096 if (errno == EINTR)
2097 continue;
2098 assert(false && "Unexpected errno from sem_wait");
2099 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002100}
2101
2102size_t
2103ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
2104 Error &error)
2105{
2106 size_t result;
2107 ReadOperation op(vm_addr, buf, size, error, result);
2108 DoOperation(&op);
2109 return result;
2110}
2111
2112size_t
2113ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
2114 lldb_private::Error &error)
2115{
2116 size_t result;
2117 WriteOperation op(vm_addr, buf, size, error, result);
2118 DoOperation(&op);
2119 return result;
2120}
2121
2122bool
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002123ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
Matt Kopec7de48462013-03-06 17:20:48 +00002124 unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002125{
2126 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002127 ReadRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002128 DoOperation(&op);
2129 return result;
2130}
2131
2132bool
Matt Kopec7de48462013-03-06 17:20:48 +00002133ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002134 const char* reg_name, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002135{
2136 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002137 WriteRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002138 DoOperation(&op);
2139 return result;
2140}
2141
2142bool
Matt Kopec7de48462013-03-06 17:20:48 +00002143ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002144{
2145 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002146 ReadGPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002147 DoOperation(&op);
2148 return result;
2149}
2150
2151bool
Matt Kopec7de48462013-03-06 17:20:48 +00002152ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002153{
2154 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002155 ReadFPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002156 DoOperation(&op);
2157 return result;
2158}
2159
2160bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002161ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2162{
2163 bool result;
2164 ReadRegisterSetOperation op(tid, buf, buf_size, regset, result);
2165 DoOperation(&op);
2166 return result;
2167}
2168
2169bool
Matt Kopec7de48462013-03-06 17:20:48 +00002170ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002171{
2172 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002173 WriteGPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002174 DoOperation(&op);
2175 return result;
2176}
2177
2178bool
Matt Kopec7de48462013-03-06 17:20:48 +00002179ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002180{
2181 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002182 WriteFPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002183 DoOperation(&op);
2184 return result;
2185}
2186
2187bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002188ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2189{
2190 bool result;
2191 WriteRegisterSetOperation op(tid, buf, buf_size, regset, result);
2192 DoOperation(&op);
2193 return result;
2194}
2195
2196bool
Richard Mitton0a558352013-10-17 21:14:00 +00002197ProcessMonitor::ReadThreadPointer(lldb::tid_t tid, lldb::addr_t &value)
2198{
2199 bool result;
2200 ReadThreadPointerOperation op(tid, &value, result);
2201 DoOperation(&op);
2202 return result;
2203}
2204
2205bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002206ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002207{
2208 bool result;
Andrew Kaylor93132f52013-05-28 23:04:25 +00002209 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
2210
2211 if (log)
2212 log->Printf ("ProcessMonitor::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
2213 m_process->GetUnixSignals().GetSignalAsCString (signo));
Stephen Wilson84ffe702011-03-30 15:55:52 +00002214 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002215 DoOperation(&op);
Andrew Kaylor93132f52013-05-28 23:04:25 +00002216 if (log)
2217 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002218 return result;
2219}
2220
2221bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002222ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002223{
2224 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00002225 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002226 DoOperation(&op);
2227 return result;
2228}
2229
2230bool
Ed Maste4e0999b2014-04-01 18:14:06 +00002231ProcessMonitor::Kill()
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002232{
Ed Maste4e0999b2014-04-01 18:14:06 +00002233 return kill(GetPID(), SIGKILL) == 0;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002234}
2235
2236bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00002237ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002238{
2239 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00002240 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002241 DoOperation(&op);
2242 return result;
2243}
2244
2245bool
2246ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2247{
2248 bool result;
2249 EventMessageOperation op(tid, message, result);
2250 DoOperation(&op);
2251 return result;
2252}
2253
Greg Clayton743ecf42012-10-16 20:20:18 +00002254lldb_private::Error
Matt Kopec085d6ce2013-05-31 22:00:07 +00002255ProcessMonitor::Detach(lldb::tid_t tid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002256{
Greg Clayton28041352011-11-29 20:50:10 +00002257 lldb_private::Error error;
Matt Kopec085d6ce2013-05-31 22:00:07 +00002258 if (tid != LLDB_INVALID_THREAD_ID)
2259 {
2260 DetachOperation op(tid, error);
Greg Clayton743ecf42012-10-16 20:20:18 +00002261 DoOperation(&op);
2262 }
Greg Clayton743ecf42012-10-16 20:20:18 +00002263 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00002264}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002265
2266bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002267ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
2268{
Peter Collingbourne62343202011-06-14 03:55:54 +00002269 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002270
2271 if (target_fd == -1)
2272 return false;
2273
Peter Collingbourne62343202011-06-14 03:55:54 +00002274 return (dup2(target_fd, fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002275}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002276
2277void
2278ProcessMonitor::StopMonitoringChildProcess()
2279{
2280 lldb::thread_result_t thread_result;
2281
Stephen Wilsond4182f42011-02-09 20:10:35 +00002282 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002283 {
2284 Host::ThreadCancel(m_monitor_thread, NULL);
2285 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
2286 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
2287 }
2288}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002289
2290void
2291ProcessMonitor::StopMonitor()
2292{
2293 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00002294 StopOpThread();
Daniel Malea1efb4182013-09-16 23:12:18 +00002295 sem_destroy(&m_operation_pending);
2296 sem_destroy(&m_operation_done);
2297
Andrew Kaylor5e268992013-09-14 00:17:31 +00002298 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
2299 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
2300 // the descriptor to a ConnectionFileDescriptor object. Consequently
2301 // even though still has the file descriptor, we shouldn't close it here.
Stephen Wilson84ffe702011-03-30 15:55:52 +00002302}
2303
2304void
Greg Clayton743ecf42012-10-16 20:20:18 +00002305ProcessMonitor::StopOpThread()
2306{
2307 lldb::thread_result_t result;
2308
2309 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
2310 return;
2311
2312 Host::ThreadCancel(m_operation_thread, NULL);
2313 Host::ThreadJoin(m_operation_thread, &result, NULL);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00002314 m_operation_thread = LLDB_INVALID_HOST_THREAD;
Greg Clayton743ecf42012-10-16 20:20:18 +00002315}