blob: 99d14d2aa7bf1f298e4a019468969a1247174a97 [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>
Todd Fiala42079682014-08-27 16:05:26 +000018#include <elf.h>
Todd Fiala0bce1b62014-08-17 00:10:50 +000019#include <sys/personality.h>
Todd Fiala49131cf2014-09-12 16:57:28 +000020#include <sys/procfs.h>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000021#include <sys/ptrace.h>
Todd Fiala6ac1be42014-08-21 16:34:03 +000022#include <sys/uio.h>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000023#include <sys/socket.h>
Andrew Kaylor93132f52013-05-28 23:04:25 +000024#include <sys/syscall.h>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000025#include <sys/types.h>
Richard Mitton0a558352013-10-17 21:14:00 +000026#include <sys/user.h>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000027#include <sys/wait.h>
28
29// C++ Includes
30// Other libraries and framework includes
Johnny Chen0d5f2d42011-10-18 18:09:30 +000031#include "lldb/Core/Debugger.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000032#include "lldb/Core/Error.h"
Johnny Chen13e8e1c2011-05-13 21:29:50 +000033#include "lldb/Core/RegisterValue.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000034#include "lldb/Core/Scalar.h"
35#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000036#include "lldb/Host/HostThread.h"
37#include "lldb/Host/ThreadLauncher.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000038#include "lldb/Target/Thread.h"
39#include "lldb/Target/RegisterContext.h"
40#include "lldb/Utility/PseudoTerminal.h"
41
Johnny Chen30213ff2012-01-05 19:17:38 +000042#include "POSIXThread.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000043#include "ProcessLinux.h"
Johnny Chen30213ff2012-01-05 19:17:38 +000044#include "ProcessPOSIXLog.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000045#include "ProcessMonitor.h"
46
Greg Clayton386ff182011-11-05 01:09:16 +000047#define DEBUG_PTRACE_MAXBYTES 20
48
Matt Kopec58c0b962013-03-20 20:34:35 +000049// Support ptrace extensions even when compiled without required kernel support
50#ifndef PTRACE_GETREGSET
51 #define PTRACE_GETREGSET 0x4204
52#endif
53#ifndef PTRACE_SETREGSET
54 #define PTRACE_SETREGSET 0x4205
55#endif
Richard Mitton0a558352013-10-17 21:14:00 +000056#ifndef PTRACE_GET_THREAD_AREA
57 #define PTRACE_GET_THREAD_AREA 25
58#endif
59#ifndef PTRACE_ARCH_PRCTL
60 #define PTRACE_ARCH_PRCTL 30
61#endif
62#ifndef ARCH_GET_FS
63 #define ARCH_SET_GS 0x1001
64 #define ARCH_SET_FS 0x1002
65 #define ARCH_GET_FS 0x1003
66 #define ARCH_GET_GS 0x1004
67#endif
68
Todd Fiala0bce1b62014-08-17 00:10:50 +000069#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Matt Kopec58c0b962013-03-20 20:34:35 +000070
Todd Fialadbec1ff2014-09-04 16:08:20 +000071#define LLDB_PTRACE_NT_ARM_TLS 0x401 // ARM TLS register
72
Matt Kopece9ea0da2013-05-07 19:29:28 +000073// Support hardware breakpoints in case it has not been defined
74#ifndef TRAP_HWBKPT
75 #define TRAP_HWBKPT 4
76#endif
77
Andrew Kaylor93132f52013-05-28 23:04:25 +000078// Try to define a macro to encapsulate the tgkill syscall
79// fall back on kill() if tgkill isn't available
80#define tgkill(pid, tid, sig) syscall(SYS_tgkill, pid, tid, sig)
81
Stephen Wilsone6f9f662010-07-24 02:19:04 +000082using namespace lldb_private;
83
Johnny Chen0d5f2d42011-10-18 18:09:30 +000084// FIXME: this code is host-dependent with respect to types and
85// endianness and needs to be fixed. For example, lldb::addr_t is
86// hard-coded to uint64_t, but on a 32-bit Linux host, ptrace requires
87// 32-bit pointer arguments. This code uses casts to work around the
88// problem.
89
90// We disable the tracing of ptrace calls for integration builds to
91// avoid the additional indirection and checks.
92#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
93
Greg Clayton386ff182011-11-05 01:09:16 +000094static void
95DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
96{
97 uint8_t *ptr = (uint8_t *)bytes;
98 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
99 for(uint32_t i=0; i<loop_count; i++)
100 {
101 s.Printf ("[%x]", *ptr);
102 ptr++;
103 }
104}
105
Matt Kopec58c0b962013-03-20 20:34:35 +0000106static void PtraceDisplayBytes(int &req, void *data, size_t data_size)
Greg Clayton386ff182011-11-05 01:09:16 +0000107{
108 StreamString buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000109 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
Johnny Chen30213ff2012-01-05 19:17:38 +0000110 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
Greg Clayton386ff182011-11-05 01:09:16 +0000111
112 if (verbose_log)
113 {
114 switch(req)
115 {
116 case PTRACE_POKETEXT:
117 {
118 DisplayBytes(buf, &data, 8);
119 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
120 break;
121 }
Greg Clayton542e4072012-09-07 17:49:29 +0000122 case PTRACE_POKEDATA:
Greg Clayton386ff182011-11-05 01:09:16 +0000123 {
124 DisplayBytes(buf, &data, 8);
125 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
126 break;
127 }
Greg Clayton542e4072012-09-07 17:49:29 +0000128 case PTRACE_POKEUSER:
Greg Clayton386ff182011-11-05 01:09:16 +0000129 {
130 DisplayBytes(buf, &data, 8);
131 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
132 break;
133 }
Todd Fiala6ac1be42014-08-21 16:34:03 +0000134#if !defined (__arm64__) && !defined (__aarch64__)
Greg Clayton542e4072012-09-07 17:49:29 +0000135 case PTRACE_SETREGS:
Greg Clayton386ff182011-11-05 01:09:16 +0000136 {
Matt Kopec7de48462013-03-06 17:20:48 +0000137 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000138 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
139 break;
140 }
141 case PTRACE_SETFPREGS:
142 {
Matt Kopec7de48462013-03-06 17:20:48 +0000143 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000144 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
145 break;
146 }
Todd Fialad35f2b92014-06-23 15:59:04 +0000147#endif
Greg Clayton542e4072012-09-07 17:49:29 +0000148 case PTRACE_SETSIGINFO:
Greg Clayton386ff182011-11-05 01:09:16 +0000149 {
150 DisplayBytes(buf, data, sizeof(siginfo_t));
151 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
152 break;
153 }
Matt Kopec58c0b962013-03-20 20:34:35 +0000154 case PTRACE_SETREGSET:
155 {
156 // Extract iov_base from data, which is a pointer to the struct IOVEC
157 DisplayBytes(buf, *(void **)data, data_size);
158 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
159 break;
160 }
Greg Clayton386ff182011-11-05 01:09:16 +0000161 default:
162 {
163 }
164 }
165 }
166}
167
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000168// Wrapper for ptrace to catch errors and log calls.
Ashok Thirumurthi762fbd02013-03-27 21:09:30 +0000169// 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 +0000170extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000171PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000172 const char* reqName, const char* file, int line)
173{
Greg Clayton386ff182011-11-05 01:09:16 +0000174 long int result;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000175
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000176 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
Greg Clayton386ff182011-11-05 01:09:16 +0000177
Matt Kopec7de48462013-03-06 17:20:48 +0000178 PtraceDisplayBytes(req, data, data_size);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000179
180 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000181 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala4507f062014-02-27 20:46:12 +0000182 result = ptrace(static_cast<__ptrace_request>(req), static_cast<pid_t>(pid), *(unsigned int *)addr, data);
Matt Kopec58c0b962013-03-20 20:34:35 +0000183 else
Todd Fiala4507f062014-02-27 20:46:12 +0000184 result = ptrace(static_cast<__ptrace_request>(req), static_cast<pid_t>(pid), addr, data);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000185
Ed Mastec099c952014-02-24 14:07:45 +0000186 if (log)
187 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
188 reqName, pid, addr, data, data_size, result, file, line);
189
Matt Kopec7de48462013-03-06 17:20:48 +0000190 PtraceDisplayBytes(req, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000191
Matt Kopec7de48462013-03-06 17:20:48 +0000192 if (log && errno != 0)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000193 {
194 const char* str;
195 switch (errno)
196 {
197 case ESRCH: str = "ESRCH"; break;
198 case EINVAL: str = "EINVAL"; break;
199 case EBUSY: str = "EBUSY"; break;
200 case EPERM: str = "EPERM"; break;
201 default: str = "<unknown>";
202 }
203 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
204 }
205
206 return result;
207}
208
Matt Kopec7de48462013-03-06 17:20:48 +0000209// Wrapper for ptrace when logging is not required.
210// Sets errno to 0 prior to calling ptrace.
211extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000212PtraceWrapper(int req, pid_t pid, void *addr, void *data, size_t data_size)
Matt Kopec7de48462013-03-06 17:20:48 +0000213{
Matt Kopec58c0b962013-03-20 20:34:35 +0000214 long result = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000215 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000216 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
217 result = ptrace(static_cast<__ptrace_request>(req), pid, *(unsigned int *)addr, data);
218 else
219 result = ptrace(static_cast<__ptrace_request>(req), pid, addr, data);
Matt Kopec7de48462013-03-06 17:20:48 +0000220 return result;
221}
222
223#define PTRACE(req, pid, addr, data, data_size) \
224 PtraceWrapper((req), (pid), (addr), (data), (data_size), #req, __FILE__, __LINE__)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000225#else
Matt Kopec7de48462013-03-06 17:20:48 +0000226 PtraceWrapper((req), (pid), (addr), (data), (data_size))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000227#endif
228
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000229//------------------------------------------------------------------------------
230// Static implementations of ProcessMonitor::ReadMemory and
231// ProcessMonitor::WriteMemory. This enables mutual recursion between these
232// functions without needed to go thru the thread funnel.
233
234static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000235DoReadMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000236 lldb::addr_t vm_addr, void *buf, size_t size, Error &error)
237{
Greg Clayton542e4072012-09-07 17:49:29 +0000238 // ptrace word size is determined by the host, not the child
239 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000240 unsigned char *dst = static_cast<unsigned char*>(buf);
241 size_t bytes_read;
242 size_t remainder;
243 long data;
244
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000245 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000246 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000247 ProcessPOSIXLog::IncNestLevel();
248 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000249 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000250 pid, word_size, (void*)vm_addr, buf, size);
251
252 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000253 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
254 {
255 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000256 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, NULL, 0);
257 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000258 {
259 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000260 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000261 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000262 return bytes_read;
263 }
264
265 remainder = size - bytes_read;
266 remainder = remainder > word_size ? word_size : remainder;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000267
268 // Copy the data into our buffer
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000269 for (unsigned i = 0; i < remainder; ++i)
270 dst[i] = ((data >> i*8) & 0xFF);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000271
Johnny Chen30213ff2012-01-05 19:17:38 +0000272 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
273 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
274 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
275 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Daniel Maleac63dddd2012-12-14 21:07:07 +0000276 {
277 uintptr_t print_dst = 0;
278 // Format bytes from data by moving into print_dst for log output
279 for (unsigned i = 0; i < remainder; ++i)
280 print_dst |= (((data >> i*8) & 0xFF) << i*8);
281 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
282 (void*)vm_addr, print_dst, (unsigned long)data);
283 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000284
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000285 vm_addr += word_size;
286 dst += word_size;
287 }
288
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000289 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000290 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000291 return bytes_read;
292}
293
294static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000295DoWriteMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000296 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
297{
Greg Clayton542e4072012-09-07 17:49:29 +0000298 // ptrace word size is determined by the host, not the child
299 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000300 const unsigned char *src = static_cast<const unsigned char*>(buf);
301 size_t bytes_written = 0;
302 size_t remainder;
303
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000304 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000305 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000306 ProcessPOSIXLog::IncNestLevel();
307 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000308 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000309 pid, word_size, (void*)vm_addr, buf, size);
310
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000311 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
312 {
313 remainder = size - bytes_written;
314 remainder = remainder > word_size ? word_size : remainder;
315
316 if (remainder == word_size)
317 {
318 unsigned long data = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000319 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000320 for (unsigned i = 0; i < word_size; ++i)
321 data |= (unsigned long)src[i] << i*8;
322
Johnny Chen30213ff2012-01-05 19:17:38 +0000323 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
324 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
325 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
326 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000327 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
328 (void*)vm_addr, *(unsigned long*)src, data);
329
Matt Kopec7de48462013-03-06 17:20:48 +0000330 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000331 {
332 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000333 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000334 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000335 return bytes_written;
336 }
337 }
338 else
339 {
340 unsigned char buff[8];
Greg Clayton542e4072012-09-07 17:49:29 +0000341 if (DoReadMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000342 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000343 {
344 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000345 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000346 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000347 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000348
349 memcpy(buff, src, remainder);
350
Greg Clayton542e4072012-09-07 17:49:29 +0000351 if (DoWriteMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000352 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000353 {
354 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000355 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000356 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000357 }
358
Johnny Chen30213ff2012-01-05 19:17:38 +0000359 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
360 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
361 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
362 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000363 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
364 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000365 }
366
367 vm_addr += word_size;
368 src += word_size;
369 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000370 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000371 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000372 return bytes_written;
373}
374
Stephen Wilson26977162011-03-23 02:14:42 +0000375// Simple helper function to ensure flags are enabled on the given file
376// descriptor.
377static bool
378EnsureFDFlags(int fd, int flags, Error &error)
379{
380 int status;
381
382 if ((status = fcntl(fd, F_GETFL)) == -1)
383 {
384 error.SetErrorToErrno();
385 return false;
386 }
387
388 if (fcntl(fd, F_SETFL, status | flags) == -1)
389 {
390 error.SetErrorToErrno();
391 return false;
392 }
393
394 return true;
395}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000396
397//------------------------------------------------------------------------------
398/// @class Operation
399/// @brief Represents a ProcessMonitor operation.
400///
401/// Under Linux, it is not possible to ptrace() from any other thread but the
402/// one that spawned or attached to the process from the start. Therefore, when
403/// a ProcessMonitor is asked to deliver or change the state of an inferior
404/// process the operation must be "funneled" to a specific thread to perform the
405/// task. The Operation class provides an abstract base for all services the
406/// ProcessMonitor must perform via the single virtual function Execute, thus
407/// encapsulating the code that needs to run in the privileged context.
408class Operation
409{
410public:
Daniel Maleadd15b782013-05-13 17:32:07 +0000411 virtual ~Operation() {}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000412 virtual void Execute(ProcessMonitor *monitor) = 0;
413};
414
415//------------------------------------------------------------------------------
416/// @class ReadOperation
417/// @brief Implements ProcessMonitor::ReadMemory.
418class ReadOperation : public Operation
419{
420public:
421 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
422 Error &error, size_t &result)
423 : m_addr(addr), m_buff(buff), m_size(size),
424 m_error(error), m_result(result)
425 { }
426
427 void Execute(ProcessMonitor *monitor);
428
429private:
430 lldb::addr_t m_addr;
431 void *m_buff;
432 size_t m_size;
433 Error &m_error;
434 size_t &m_result;
435};
436
437void
438ReadOperation::Execute(ProcessMonitor *monitor)
439{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000440 lldb::pid_t pid = monitor->GetPID();
441
Greg Clayton542e4072012-09-07 17:49:29 +0000442 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000443}
444
445//------------------------------------------------------------------------------
Ed Mastea56115f2013-07-17 14:30:26 +0000446/// @class WriteOperation
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000447/// @brief Implements ProcessMonitor::WriteMemory.
448class WriteOperation : public Operation
449{
450public:
451 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
452 Error &error, size_t &result)
453 : m_addr(addr), m_buff(buff), m_size(size),
454 m_error(error), m_result(result)
455 { }
456
457 void Execute(ProcessMonitor *monitor);
458
459private:
460 lldb::addr_t m_addr;
461 const void *m_buff;
462 size_t m_size;
463 Error &m_error;
464 size_t &m_result;
465};
466
467void
468WriteOperation::Execute(ProcessMonitor *monitor)
469{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000470 lldb::pid_t pid = monitor->GetPID();
471
Greg Clayton542e4072012-09-07 17:49:29 +0000472 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000473}
474
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000475
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000476//------------------------------------------------------------------------------
477/// @class ReadRegOperation
478/// @brief Implements ProcessMonitor::ReadRegisterValue.
479class ReadRegOperation : public Operation
480{
481public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000482 ReadRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000483 RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000484 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000485 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000486 { }
487
488 void Execute(ProcessMonitor *monitor);
489
490private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000491 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000492 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000493 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000494 RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000495 bool &m_result;
496};
497
498void
499ReadRegOperation::Execute(ProcessMonitor *monitor)
500{
Todd Fiala49131cf2014-09-12 16:57:28 +0000501#if defined (__arm64__) || defined (__aarch64__)
502 if (m_offset > sizeof(struct user_pt_regs))
503 {
504 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
505 if (offset > sizeof(struct user_fpsimd_state))
506 {
507 m_result = false;
508 }
509 else
510 {
511 elf_fpregset_t regs;
512 int regset = NT_FPREGSET;
513 struct iovec ioVec;
514
515 ioVec.iov_base = &regs;
516 ioVec.iov_len = sizeof regs;
517 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
518 m_result = false;
519 else
520 {
521 m_result = true;
522 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, monitor->GetProcess().GetByteOrder());
523 }
524 }
525 }
526 else
527 {
528 elf_gregset_t regs;
529 int regset = NT_PRSTATUS;
530 struct iovec ioVec;
531
532 ioVec.iov_base = &regs;
533 ioVec.iov_len = sizeof regs;
534 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
535 m_result = false;
536 else
537 {
538 m_result = true;
539 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, monitor->GetProcess().GetByteOrder());
540 }
541 }
542#else
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000543 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000544
545 // Set errno to zero so that we can detect a failed peek.
546 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000547 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, NULL, 0);
548 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000549 m_result = false;
550 else
551 {
552 m_value = data;
553 m_result = true;
554 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000555 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000556 log->Printf ("ProcessMonitor::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000557 m_reg_name, data);
Todd Fiala49131cf2014-09-12 16:57:28 +0000558#endif
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000559}
560
561//------------------------------------------------------------------------------
562/// @class WriteRegOperation
563/// @brief Implements ProcessMonitor::WriteRegisterValue.
564class WriteRegOperation : public Operation
565{
566public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000567 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000568 const RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000569 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000570 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000571 { }
572
573 void Execute(ProcessMonitor *monitor);
574
575private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000576 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000577 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000578 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000579 const RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000580 bool &m_result;
581};
582
583void
584WriteRegOperation::Execute(ProcessMonitor *monitor)
585{
Todd Fiala49131cf2014-09-12 16:57:28 +0000586#if defined (__arm64__) || defined (__aarch64__)
587 if (m_offset > sizeof(struct user_pt_regs))
588 {
589 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
590 if (offset > sizeof(struct user_fpsimd_state))
591 {
592 m_result = false;
593 }
594 else
595 {
596 elf_fpregset_t regs;
597 int regset = NT_FPREGSET;
598 struct iovec ioVec;
599
600 ioVec.iov_base = &regs;
601 ioVec.iov_len = sizeof regs;
602 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
603 m_result = false;
604 else
605 {
606 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
607 if (PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
608 m_result = false;
609 else
610 m_result = true;
611 }
612 }
613 }
614 else
615 {
616 elf_gregset_t regs;
617 int regset = NT_PRSTATUS;
618 struct iovec ioVec;
619
620 ioVec.iov_base = &regs;
621 ioVec.iov_len = sizeof regs;
622 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
623 m_result = false;
624 else
625 {
626 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
627 if (PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
628 m_result = false;
629 else
630 m_result = true;
631 }
632 }
633#else
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000634 void* buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000635 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000636
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000637 buf = (void*) m_value.GetAsUInt64();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000638
639 if (log)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000640 log->Printf ("ProcessMonitor::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Matt Kopec7de48462013-03-06 17:20:48 +0000641 if (PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000642 m_result = false;
643 else
644 m_result = true;
Todd Fiala49131cf2014-09-12 16:57:28 +0000645#endif
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000646}
647
648//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000649/// @class ReadGPROperation
650/// @brief Implements ProcessMonitor::ReadGPR.
651class ReadGPROperation : public Operation
652{
653public:
Matt Kopec7de48462013-03-06 17:20:48 +0000654 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
655 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000656 { }
657
658 void Execute(ProcessMonitor *monitor);
659
660private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000661 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000662 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000663 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000664 bool &m_result;
665};
666
667void
668ReadGPROperation::Execute(ProcessMonitor *monitor)
669{
Todd Fiala6ac1be42014-08-21 16:34:03 +0000670#if defined (__arm64__) || defined (__aarch64__)
671 int regset = NT_PRSTATUS;
672 struct iovec ioVec;
673
674 ioVec.iov_base = m_buf;
675 ioVec.iov_len = m_buf_size;
676 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000677 m_result = false;
678 else
679 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000680#else
Todd Fiala6ac1be42014-08-21 16:34:03 +0000681 if (PTRACE(PTRACE_GETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
682 m_result = false;
683 else
684 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000685#endif
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000686}
687
688//------------------------------------------------------------------------------
689/// @class ReadFPROperation
690/// @brief Implements ProcessMonitor::ReadFPR.
691class ReadFPROperation : public Operation
692{
693public:
Matt Kopec7de48462013-03-06 17:20:48 +0000694 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
695 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000696 { }
697
698 void Execute(ProcessMonitor *monitor);
699
700private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000701 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000702 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000703 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000704 bool &m_result;
705};
706
707void
708ReadFPROperation::Execute(ProcessMonitor *monitor)
709{
Todd Fiala6ac1be42014-08-21 16:34:03 +0000710#if defined (__arm64__) || defined (__aarch64__)
711 int regset = NT_FPREGSET;
712 struct iovec ioVec;
713
714 ioVec.iov_base = m_buf;
715 ioVec.iov_len = m_buf_size;
716 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000717 m_result = false;
718 else
719 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000720#else
Todd Fiala6ac1be42014-08-21 16:34:03 +0000721 if (PTRACE(PTRACE_GETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
722 m_result = false;
723 else
724 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000725#endif
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000726}
727
728//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000729/// @class ReadRegisterSetOperation
730/// @brief Implements ProcessMonitor::ReadRegisterSet.
731class ReadRegisterSetOperation : public Operation
732{
733public:
734 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
735 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
736 { }
737
738 void Execute(ProcessMonitor *monitor);
739
740private:
741 lldb::tid_t m_tid;
742 void *m_buf;
743 size_t m_buf_size;
744 const unsigned int m_regset;
745 bool &m_result;
746};
747
748void
749ReadRegisterSetOperation::Execute(ProcessMonitor *monitor)
750{
751 if (PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
752 m_result = false;
753 else
754 m_result = true;
755}
756
757//------------------------------------------------------------------------------
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000758/// @class WriteGPROperation
759/// @brief Implements ProcessMonitor::WriteGPR.
760class WriteGPROperation : public Operation
761{
762public:
Matt Kopec7de48462013-03-06 17:20:48 +0000763 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
764 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000765 { }
766
767 void Execute(ProcessMonitor *monitor);
768
769private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000770 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000771 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000772 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000773 bool &m_result;
774};
775
776void
777WriteGPROperation::Execute(ProcessMonitor *monitor)
778{
Todd Fiala6ac1be42014-08-21 16:34:03 +0000779#if defined (__arm64__) || defined (__aarch64__)
780 int regset = NT_PRSTATUS;
781 struct iovec ioVec;
782
783 ioVec.iov_base = m_buf;
784 ioVec.iov_len = m_buf_size;
785 if (PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000786 m_result = false;
787 else
788 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000789#else
Todd Fiala6ac1be42014-08-21 16:34:03 +0000790 if (PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
791 m_result = false;
792 else
793 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000794#endif
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000795}
796
797//------------------------------------------------------------------------------
798/// @class WriteFPROperation
799/// @brief Implements ProcessMonitor::WriteFPR.
800class WriteFPROperation : public Operation
801{
802public:
Matt Kopec7de48462013-03-06 17:20:48 +0000803 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
804 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000805 { }
806
807 void Execute(ProcessMonitor *monitor);
808
809private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000810 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000811 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000812 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000813 bool &m_result;
814};
815
816void
817WriteFPROperation::Execute(ProcessMonitor *monitor)
818{
Todd Fiala6ac1be42014-08-21 16:34:03 +0000819#if defined (__arm64__) || defined (__aarch64__)
820 int regset = NT_FPREGSET;
821 struct iovec ioVec;
822
823 ioVec.iov_base = m_buf;
824 ioVec.iov_len = m_buf_size;
825 if (PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000826 m_result = false;
827 else
828 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000829#else
Todd Fiala6ac1be42014-08-21 16:34:03 +0000830 if (PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
831 m_result = false;
832 else
833 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000834#endif
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000835}
836
837//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000838/// @class WriteRegisterSetOperation
839/// @brief Implements ProcessMonitor::WriteRegisterSet.
840class WriteRegisterSetOperation : public Operation
841{
842public:
843 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
844 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
845 { }
846
847 void Execute(ProcessMonitor *monitor);
848
849private:
850 lldb::tid_t m_tid;
851 void *m_buf;
852 size_t m_buf_size;
853 const unsigned int m_regset;
854 bool &m_result;
855};
856
857void
858WriteRegisterSetOperation::Execute(ProcessMonitor *monitor)
859{
860 if (PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
861 m_result = false;
862 else
863 m_result = true;
864}
865
866//------------------------------------------------------------------------------
Richard Mitton0a558352013-10-17 21:14:00 +0000867/// @class ReadThreadPointerOperation
868/// @brief Implements ProcessMonitor::ReadThreadPointer.
869class ReadThreadPointerOperation : public Operation
870{
871public:
872 ReadThreadPointerOperation(lldb::tid_t tid, lldb::addr_t *addr, bool &result)
873 : m_tid(tid), m_addr(addr), m_result(result)
874 { }
875
876 void Execute(ProcessMonitor *monitor);
877
878private:
879 lldb::tid_t m_tid;
880 lldb::addr_t *m_addr;
881 bool &m_result;
882};
883
884void
885ReadThreadPointerOperation::Execute(ProcessMonitor *monitor)
886{
887 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
888 if (log)
889 log->Printf ("ProcessMonitor::%s()", __FUNCTION__);
890
891 // The process for getting the thread area on Linux is
892 // somewhat... obscure. There's several different ways depending on
893 // what arch you're on, and what kernel version you have.
894
895 const ArchSpec& arch = monitor->GetProcess().GetTarget().GetArchitecture();
896 switch(arch.GetMachine())
897 {
Todd Fiala42079682014-08-27 16:05:26 +0000898 case llvm::Triple::aarch64:
899 {
Todd Fialadbec1ff2014-09-04 16:08:20 +0000900 int regset = LLDB_PTRACE_NT_ARM_TLS;
Todd Fiala42079682014-08-27 16:05:26 +0000901 struct iovec ioVec;
902
903 ioVec.iov_base = m_addr;
904 ioVec.iov_len = sizeof(lldb::addr_t);
905 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, ioVec.iov_len) < 0)
906 m_result = false;
907 else
908 m_result = true;
909 break;
910 }
Todd Fiala720cd3f2014-06-16 14:49:28 +0000911#if defined(__i386__) || defined(__x86_64__)
912 // Note that struct user below has a field named i387 which is x86-specific.
913 // Therefore, this case should be compiled only for x86-based systems.
Richard Mitton0a558352013-10-17 21:14:00 +0000914 case llvm::Triple::x86:
915 {
916 // Find the GS register location for our host architecture.
917 size_t gs_user_offset = offsetof(struct user, regs);
918#ifdef __x86_64__
919 gs_user_offset += offsetof(struct user_regs_struct, gs);
920#endif
921#ifdef __i386__
922 gs_user_offset += offsetof(struct user_regs_struct, xgs);
923#endif
924
925 // Read the GS register value to get the selector.
926 errno = 0;
927 long gs = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)gs_user_offset, NULL, 0);
928 if (errno)
929 {
930 m_result = false;
931 break;
932 }
933
934 // Read the LDT base for that selector.
935 uint32_t tmp[4];
936 m_result = (PTRACE(PTRACE_GET_THREAD_AREA, m_tid, (void *)(gs >> 3), &tmp, 0) == 0);
937 *m_addr = tmp[1];
938 break;
939 }
Todd Fiala720cd3f2014-06-16 14:49:28 +0000940#endif
Richard Mitton0a558352013-10-17 21:14:00 +0000941 case llvm::Triple::x86_64:
942 // Read the FS register base.
943 m_result = (PTRACE(PTRACE_ARCH_PRCTL, m_tid, m_addr, (void *)ARCH_GET_FS, 0) == 0);
944 break;
945 default:
946 m_result = false;
947 break;
948 }
949}
950
951//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000952/// @class ResumeOperation
953/// @brief Implements ProcessMonitor::Resume.
954class ResumeOperation : public Operation
955{
956public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000957 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
958 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000959
960 void Execute(ProcessMonitor *monitor);
961
962private:
963 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000964 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000965 bool &m_result;
966};
967
968void
969ResumeOperation::Execute(ProcessMonitor *monitor)
970{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000971 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000972
973 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
974 data = m_signo;
975
Matt Kopec7de48462013-03-06 17:20:48 +0000976 if (PTRACE(PTRACE_CONT, m_tid, NULL, (void*)data, 0))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000977 {
978 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
979
980 if (log)
981 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, strerror(errno));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000982 m_result = false;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000983 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000984 else
985 m_result = true;
986}
987
988//------------------------------------------------------------------------------
Ed Maste428a6782013-06-24 15:04:47 +0000989/// @class SingleStepOperation
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000990/// @brief Implements ProcessMonitor::SingleStep.
991class SingleStepOperation : public Operation
992{
993public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000994 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
995 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000996
997 void Execute(ProcessMonitor *monitor);
998
999private:
1000 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001001 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001002 bool &m_result;
1003};
1004
1005void
1006SingleStepOperation::Execute(ProcessMonitor *monitor)
1007{
Daniel Maleaa85e6b62012-12-07 22:21:08 +00001008 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001009
1010 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
1011 data = m_signo;
1012
Matt Kopec7de48462013-03-06 17:20:48 +00001013 if (PTRACE(PTRACE_SINGLESTEP, m_tid, NULL, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001014 m_result = false;
1015 else
1016 m_result = true;
1017}
1018
1019//------------------------------------------------------------------------------
1020/// @class SiginfoOperation
1021/// @brief Implements ProcessMonitor::GetSignalInfo.
1022class SiginfoOperation : public Operation
1023{
1024public:
Daniel Maleaa35970a2012-11-23 18:09:58 +00001025 SiginfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
1026 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001027
1028 void Execute(ProcessMonitor *monitor);
1029
1030private:
1031 lldb::tid_t m_tid;
1032 void *m_info;
1033 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001034 int &m_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001035};
1036
1037void
1038SiginfoOperation::Execute(ProcessMonitor *monitor)
1039{
Matt Kopec7de48462013-03-06 17:20:48 +00001040 if (PTRACE(PTRACE_GETSIGINFO, m_tid, NULL, m_info, 0)) {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001041 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001042 m_err = errno;
1043 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001044 else
1045 m_result = true;
1046}
1047
1048//------------------------------------------------------------------------------
1049/// @class EventMessageOperation
1050/// @brief Implements ProcessMonitor::GetEventMessage.
1051class EventMessageOperation : public Operation
1052{
1053public:
1054 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
1055 : m_tid(tid), m_message(message), m_result(result) { }
1056
1057 void Execute(ProcessMonitor *monitor);
1058
1059private:
1060 lldb::tid_t m_tid;
1061 unsigned long *m_message;
1062 bool &m_result;
1063};
1064
1065void
1066EventMessageOperation::Execute(ProcessMonitor *monitor)
1067{
Matt Kopec7de48462013-03-06 17:20:48 +00001068 if (PTRACE(PTRACE_GETEVENTMSG, m_tid, NULL, m_message, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001069 m_result = false;
1070 else
1071 m_result = true;
1072}
1073
1074//------------------------------------------------------------------------------
Ed Maste263c9282014-03-17 17:45:53 +00001075/// @class DetachOperation
1076/// @brief Implements ProcessMonitor::Detach.
Greg Clayton28041352011-11-29 20:50:10 +00001077class DetachOperation : public Operation
1078{
1079public:
Matt Kopec085d6ce2013-05-31 22:00:07 +00001080 DetachOperation(lldb::tid_t tid, Error &result) : m_tid(tid), m_error(result) { }
Greg Clayton28041352011-11-29 20:50:10 +00001081
1082 void Execute(ProcessMonitor *monitor);
1083
1084private:
Matt Kopec085d6ce2013-05-31 22:00:07 +00001085 lldb::tid_t m_tid;
Greg Clayton28041352011-11-29 20:50:10 +00001086 Error &m_error;
1087};
1088
1089void
1090DetachOperation::Execute(ProcessMonitor *monitor)
1091{
Matt Kopec085d6ce2013-05-31 22:00:07 +00001092 if (ptrace(PT_DETACH, m_tid, NULL, 0) < 0)
Greg Clayton28041352011-11-29 20:50:10 +00001093 m_error.SetErrorToErrno();
Greg Clayton28041352011-11-29 20:50:10 +00001094}
1095
Johnny Chen25e68e32011-06-14 19:19:50 +00001096ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
1097 : m_monitor(monitor)
1098{
1099 sem_init(&m_semaphore, 0, 0);
1100}
1101
1102ProcessMonitor::OperationArgs::~OperationArgs()
1103{
1104 sem_destroy(&m_semaphore);
1105}
1106
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001107ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
1108 lldb_private::Module *module,
1109 char const **argv,
1110 char const **envp,
1111 const char *stdin_path,
1112 const char *stdout_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001113 const char *stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001114 const char *working_dir,
1115 const lldb_private::ProcessLaunchInfo &launch_info)
Johnny Chen25e68e32011-06-14 19:19:50 +00001116 : OperationArgs(monitor),
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001117 m_module(module),
1118 m_argv(argv),
1119 m_envp(envp),
1120 m_stdin_path(stdin_path),
1121 m_stdout_path(stdout_path),
Daniel Malea6217d2a2013-01-08 14:49:22 +00001122 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001123 m_working_dir(working_dir),
1124 m_launch_info(launch_info)
1125{
1126}
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001127
1128ProcessMonitor::LaunchArgs::~LaunchArgs()
Johnny Chen25e68e32011-06-14 19:19:50 +00001129{ }
1130
1131ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
1132 lldb::pid_t pid)
1133 : OperationArgs(monitor), m_pid(pid) { }
1134
1135ProcessMonitor::AttachArgs::~AttachArgs()
1136{ }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001137
1138//------------------------------------------------------------------------------
1139/// The basic design of the ProcessMonitor is built around two threads.
1140///
1141/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
1142/// for changes in the debugee state. When a change is detected a
1143/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
1144/// "drives" state changes in the debugger.
1145///
1146/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +00001147/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001148/// operations such as register reads/writes, stepping, etc. See the comments
1149/// on the Operation class for more info as to why this is needed.
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001150ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001151 Module *module,
1152 const char *argv[],
1153 const char *envp[],
1154 const char *stdin_path,
1155 const char *stdout_path,
1156 const char *stderr_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001157 const char *working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001158 const lldb_private::ProcessLaunchInfo &launch_info,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001159 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001160 : m_process(static_cast<ProcessLinux *>(process)),
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001161 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +00001162 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001163 m_pid(LLDB_INVALID_PROCESS_ID),
1164 m_terminal_fd(-1),
Daniel Malea1efb4182013-09-16 23:12:18 +00001165 m_operation(0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001166{
Daniel Malea1efb4182013-09-16 23:12:18 +00001167 std::unique_ptr<LaunchArgs> args(new LaunchArgs(this, module, argv, envp,
1168 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001169 working_dir, launch_info));
Stephen Wilson57740ec2011-01-15 00:12:41 +00001170
Daniel Malea1efb4182013-09-16 23:12:18 +00001171 sem_init(&m_operation_pending, 0, 0);
1172 sem_init(&m_operation_done, 0, 0);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001173
Johnny Chen25e68e32011-06-14 19:19:50 +00001174 StartLaunchOpThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001175 if (!error.Success())
1176 return;
1177
1178WAIT_AGAIN:
1179 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +00001180 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001181 {
1182 if (errno == EINTR)
1183 goto WAIT_AGAIN;
1184 else
1185 {
1186 error.SetErrorToErrno();
1187 return;
1188 }
1189 }
1190
1191 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +00001192 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001193 {
Greg Clayton743ecf42012-10-16 20:20:18 +00001194 StopOpThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +00001195 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001196 return;
1197 }
1198
1199 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +00001200 m_monitor_thread = Host::StartMonitoringChildProcess(
1201 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Zachary Turner39de3112014-09-09 20:54:56 +00001202 if (m_monitor_thread.GetState() != eThreadStateRunning)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001203 {
1204 error.SetErrorToGenericError();
1205 error.SetErrorString("Process launch failed.");
1206 return;
1207 }
1208}
1209
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001210ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen25e68e32011-06-14 19:19:50 +00001211 lldb::pid_t pid,
1212 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001213 : m_process(static_cast<ProcessLinux *>(process)),
Johnny Chen25e68e32011-06-14 19:19:50 +00001214 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +00001215 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Johnny Chen25e68e32011-06-14 19:19:50 +00001216 m_pid(LLDB_INVALID_PROCESS_ID),
1217 m_terminal_fd(-1),
Daniel Malea1efb4182013-09-16 23:12:18 +00001218 m_operation(0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001219{
Daniel Malea1efb4182013-09-16 23:12:18 +00001220 sem_init(&m_operation_pending, 0, 0);
1221 sem_init(&m_operation_done, 0, 0);
Johnny Chen25e68e32011-06-14 19:19:50 +00001222
Daniel Malea1efb4182013-09-16 23:12:18 +00001223 std::unique_ptr<AttachArgs> args(new AttachArgs(this, pid));
Johnny Chen25e68e32011-06-14 19:19:50 +00001224
1225 StartAttachOpThread(args.get(), error);
1226 if (!error.Success())
1227 return;
1228
1229WAIT_AGAIN:
1230 // Wait for the operation thread to initialize.
1231 if (sem_wait(&args->m_semaphore))
1232 {
1233 if (errno == EINTR)
1234 goto WAIT_AGAIN;
1235 else
1236 {
1237 error.SetErrorToErrno();
1238 return;
1239 }
1240 }
1241
Greg Clayton743ecf42012-10-16 20:20:18 +00001242 // Check that the attach was a success.
Johnny Chen25e68e32011-06-14 19:19:50 +00001243 if (!args->m_error.Success())
1244 {
Greg Clayton743ecf42012-10-16 20:20:18 +00001245 StopOpThread();
Johnny Chen25e68e32011-06-14 19:19:50 +00001246 error = args->m_error;
1247 return;
1248 }
1249
1250 // Finally, start monitoring the child process for change in state.
1251 m_monitor_thread = Host::StartMonitoringChildProcess(
1252 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Zachary Turner39de3112014-09-09 20:54:56 +00001253 if (m_monitor_thread.GetState() != eThreadStateRunning)
Johnny Chen25e68e32011-06-14 19:19:50 +00001254 {
1255 error.SetErrorToGenericError();
1256 error.SetErrorString("Process attach failed.");
1257 return;
1258 }
1259}
1260
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001261ProcessMonitor::~ProcessMonitor()
1262{
Stephen Wilson84ffe702011-03-30 15:55:52 +00001263 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001264}
1265
1266//------------------------------------------------------------------------------
1267// Thread setup and tear down.
1268void
Johnny Chen25e68e32011-06-14 19:19:50 +00001269ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001270{
1271 static const char *g_thread_name = "lldb.process.linux.operation";
1272
Zachary Turner39de3112014-09-09 20:54:56 +00001273 if (m_operation_thread.GetState() == eThreadStateRunning)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001274 return;
1275
Zachary Turner39de3112014-09-09 20:54:56 +00001276 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001277}
1278
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001279void *
Johnny Chen25e68e32011-06-14 19:19:50 +00001280ProcessMonitor::LaunchOpThread(void *arg)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001281{
1282 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1283
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001284 if (!Launch(args)) {
1285 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001286 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001287 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001288
Stephen Wilson570243b2011-01-19 01:37:06 +00001289 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001290 return NULL;
1291}
1292
1293bool
1294ProcessMonitor::Launch(LaunchArgs *args)
1295{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001296 assert (args && "null args");
1297 if (!args)
1298 return false;
1299
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001300 ProcessMonitor *monitor = args->m_monitor;
1301 ProcessLinux &process = monitor->GetProcess();
1302 const char **argv = args->m_argv;
1303 const char **envp = args->m_envp;
1304 const char *stdin_path = args->m_stdin_path;
1305 const char *stdout_path = args->m_stdout_path;
1306 const char *stderr_path = args->m_stderr_path;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001307 const char *working_dir = args->m_working_dir;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001308
1309 lldb_utility::PseudoTerminal terminal;
1310 const size_t err_len = 1024;
1311 char err_str[err_len];
1312 lldb::pid_t pid;
1313
1314 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001315 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001316
Stephen Wilson57740ec2011-01-15 00:12:41 +00001317 // Propagate the environment if one is not supplied.
1318 if (envp == NULL || envp[0] == NULL)
1319 envp = const_cast<const char **>(environ);
1320
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001321 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t>(-1))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001322 {
1323 args->m_error.SetErrorToGenericError();
1324 args->m_error.SetErrorString("Process fork failed.");
1325 goto FINISH;
1326 }
1327
Peter Collingbourne6a520222011-06-14 03:55:58 +00001328 // Recognized child exit status codes.
1329 enum {
1330 ePtraceFailed = 1,
1331 eDupStdinFailed,
1332 eDupStdoutFailed,
1333 eDupStderrFailed,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001334 eChdirFailed,
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001335 eExecFailed,
1336 eSetGidFailed
Peter Collingbourne6a520222011-06-14 03:55:58 +00001337 };
1338
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001339 // Child process.
1340 if (pid == 0)
1341 {
1342 // Trace this process.
Matt Kopec7de48462013-03-06 17:20:48 +00001343 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL, 0) < 0)
Peter Collingbourne6a520222011-06-14 03:55:58 +00001344 exit(ePtraceFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001345
1346 // Do not inherit setgid powers.
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001347 if (setgid(getgid()) != 0)
1348 exit(eSetGidFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001349
1350 // Let us have our own process group.
1351 setpgid(0, 0);
1352
Greg Clayton710dd5a2011-01-08 20:28:42 +00001353 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001354 //
1355 // FIXME: If two or more of the paths are the same we needlessly open
1356 // the same file multiple times.
1357 if (stdin_path != NULL && stdin_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001358 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001359 exit(eDupStdinFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001360
1361 if (stdout_path != NULL && stdout_path[0])
1362 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001363 exit(eDupStdoutFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001364
1365 if (stderr_path != NULL && stderr_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001366 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001367 exit(eDupStderrFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001368
Daniel Malea6217d2a2013-01-08 14:49:22 +00001369 // Change working directory
1370 if (working_dir != NULL && working_dir[0])
1371 if (0 != ::chdir(working_dir))
1372 exit(eChdirFailed);
1373
Todd Fiala0bce1b62014-08-17 00:10:50 +00001374 // Disable ASLR if requested.
1375 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1376 {
1377 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1378 if (old_personality == -1)
1379 {
1380 if (log)
1381 log->Printf ("ProcessMonitor::%s retrieval of Linux personality () failed: %s. Cannot disable ASLR.", __FUNCTION__, strerror (errno));
1382 }
1383 else
1384 {
1385 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1386 if (new_personality == -1)
1387 {
1388 if (log)
1389 log->Printf ("ProcessMonitor::%s setting of Linux personality () to disable ASLR failed, ignoring: %s", __FUNCTION__, strerror (errno));
1390
1391 }
1392 else
1393 {
1394 if (log)
Todd Fiala850f9a22014-09-19 18:27:45 +00001395 log->Printf ("ProcessMonitor::%s disabling ASLR: SUCCESS", __FUNCTION__);
Todd Fiala0bce1b62014-08-17 00:10:50 +00001396
1397 }
1398 }
1399 }
1400
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001401 // Execute. We should never return.
1402 execve(argv[0],
1403 const_cast<char *const *>(argv),
1404 const_cast<char *const *>(envp));
Peter Collingbourne6a520222011-06-14 03:55:58 +00001405 exit(eExecFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001406 }
1407
1408 // Wait for the child process to to trap on its call to execve.
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001409 lldb::pid_t wpid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001410 ::pid_t raw_pid;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001411 int status;
Todd Fialaaf245d12014-06-30 21:05:18 +00001412
1413 raw_pid = waitpid(pid, &status, 0);
1414 wpid = static_cast <lldb::pid_t> (raw_pid);
1415 if (raw_pid < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001416 {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001417 args->m_error.SetErrorToErrno();
1418 goto FINISH;
1419 }
Peter Collingbourne6a520222011-06-14 03:55:58 +00001420 else if (WIFEXITED(status))
1421 {
1422 // open, dup or execve likely failed for some reason.
1423 args->m_error.SetErrorToGenericError();
1424 switch (WEXITSTATUS(status))
1425 {
Greg Clayton542e4072012-09-07 17:49:29 +00001426 case ePtraceFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001427 args->m_error.SetErrorString("Child ptrace failed.");
1428 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001429 case eDupStdinFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001430 args->m_error.SetErrorString("Child open stdin failed.");
1431 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001432 case eDupStdoutFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001433 args->m_error.SetErrorString("Child open stdout failed.");
1434 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001435 case eDupStderrFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001436 args->m_error.SetErrorString("Child open stderr failed.");
1437 break;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001438 case eChdirFailed:
1439 args->m_error.SetErrorString("Child failed to set working directory.");
1440 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001441 case eExecFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001442 args->m_error.SetErrorString("Child exec failed.");
1443 break;
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001444 case eSetGidFailed:
1445 args->m_error.SetErrorString("Child setgid failed.");
1446 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001447 default:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001448 args->m_error.SetErrorString("Child returned unknown exit status.");
1449 break;
1450 }
1451 goto FINISH;
1452 }
1453 assert(WIFSTOPPED(status) && wpid == pid &&
1454 "Could not sync with inferior process.");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001455
Matt Kopec085d6ce2013-05-31 22:00:07 +00001456 if (!SetDefaultPtraceOpts(pid))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001457 {
1458 args->m_error.SetErrorToErrno();
1459 goto FINISH;
1460 }
1461
1462 // Release the master terminal descriptor and pass it off to the
1463 // ProcessMonitor instance. Similarly stash the inferior pid.
1464 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1465 monitor->m_pid = pid;
1466
Stephen Wilson26977162011-03-23 02:14:42 +00001467 // Set the terminal fd to be in non blocking mode (it simplifies the
1468 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1469 // descriptor to read from).
1470 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1471 goto FINISH;
1472
Johnny Chen30213ff2012-01-05 19:17:38 +00001473 // Update the process thread list with this new thread.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001474 // FIXME: should we be letting UpdateThreadList handle this?
1475 // FIXME: by using pids instead of tids, we can only support one thread.
Michael Sartain9f822cd2013-07-31 23:27:46 +00001476 inferior.reset(process.CreateNewPOSIXThread(process, pid));
Matt Kopecfb6ab542013-07-10 20:53:11 +00001477
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001478 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001479 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001480 process.GetThreadList().AddThread(inferior);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001481
Matt Kopecb2910442013-07-09 15:09:45 +00001482 process.AddThreadForInitialStopIfNeeded(pid);
1483
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001484 // Let our process instance know the thread has stopped.
1485 process.SendMessage(ProcessMessage::Trace(pid));
1486
1487FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001488 return args->m_error.Success();
1489}
1490
Johnny Chen25e68e32011-06-14 19:19:50 +00001491void
1492ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1493{
1494 static const char *g_thread_name = "lldb.process.linux.operation";
1495
Zachary Turner39de3112014-09-09 20:54:56 +00001496 if (m_operation_thread.GetState() == eThreadStateRunning)
Johnny Chen25e68e32011-06-14 19:19:50 +00001497 return;
1498
Zachary Turner39de3112014-09-09 20:54:56 +00001499 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
Johnny Chen25e68e32011-06-14 19:19:50 +00001500}
1501
Johnny Chen25e68e32011-06-14 19:19:50 +00001502void *
1503ProcessMonitor::AttachOpThread(void *arg)
1504{
1505 AttachArgs *args = static_cast<AttachArgs*>(arg);
1506
Greg Clayton743ecf42012-10-16 20:20:18 +00001507 if (!Attach(args)) {
1508 sem_post(&args->m_semaphore);
Johnny Chen25e68e32011-06-14 19:19:50 +00001509 return NULL;
Greg Clayton743ecf42012-10-16 20:20:18 +00001510 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001511
1512 ServeOperation(args);
1513 return NULL;
1514}
1515
1516bool
1517ProcessMonitor::Attach(AttachArgs *args)
1518{
1519 lldb::pid_t pid = args->m_pid;
1520
1521 ProcessMonitor *monitor = args->m_monitor;
1522 ProcessLinux &process = monitor->GetProcess();
Johnny Chen25e68e32011-06-14 19:19:50 +00001523 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001524 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen25e68e32011-06-14 19:19:50 +00001525
Matt Kopec085d6ce2013-05-31 22:00:07 +00001526 // Use a map to keep track of the threads which we have attached/need to attach.
1527 Host::TidMap tids_to_attach;
Johnny Chen25e68e32011-06-14 19:19:50 +00001528 if (pid <= 1)
1529 {
1530 args->m_error.SetErrorToGenericError();
1531 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1532 goto FINISH;
1533 }
1534
Matt Kopec085d6ce2013-05-31 22:00:07 +00001535 while (Host::FindProcessThreads(pid, tids_to_attach))
Johnny Chen25e68e32011-06-14 19:19:50 +00001536 {
Matt Kopec085d6ce2013-05-31 22:00:07 +00001537 for (Host::TidMap::iterator it = tids_to_attach.begin();
1538 it != tids_to_attach.end(); ++it)
1539 {
1540 if (it->second == false)
1541 {
1542 lldb::tid_t tid = it->first;
1543
1544 // Attach to the requested process.
1545 // An attach will cause the thread to stop with a SIGSTOP.
1546 if (PTRACE(PTRACE_ATTACH, tid, NULL, NULL, 0) < 0)
1547 {
1548 // No such thread. The thread may have exited.
1549 // More error handling may be needed.
1550 if (errno == ESRCH)
1551 {
1552 tids_to_attach.erase(it);
1553 continue;
1554 }
1555 else
1556 {
1557 args->m_error.SetErrorToErrno();
1558 goto FINISH;
1559 }
1560 }
1561
Todd Fiala9be50492014-07-01 16:30:53 +00001562 ::pid_t wpid;
Matt Kopec085d6ce2013-05-31 22:00:07 +00001563 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1564 // At this point we should have a thread stopped if waitpid succeeds.
Todd Fiala9be50492014-07-01 16:30:53 +00001565 if ((wpid = waitpid(tid, NULL, __WALL)) < 0)
Matt Kopec085d6ce2013-05-31 22:00:07 +00001566 {
1567 // No such thread. The thread may have exited.
1568 // More error handling may be needed.
1569 if (errno == ESRCH)
1570 {
1571 tids_to_attach.erase(it);
1572 continue;
1573 }
1574 else
1575 {
1576 args->m_error.SetErrorToErrno();
1577 goto FINISH;
1578 }
1579 }
1580
1581 if (!SetDefaultPtraceOpts(tid))
1582 {
1583 args->m_error.SetErrorToErrno();
1584 goto FINISH;
1585 }
1586
1587 // Update the process thread list with the attached thread.
Michael Sartain9f822cd2013-07-31 23:27:46 +00001588 inferior.reset(process.CreateNewPOSIXThread(process, tid));
Matt Kopecfb6ab542013-07-10 20:53:11 +00001589
Matt Kopec085d6ce2013-05-31 22:00:07 +00001590 if (log)
1591 log->Printf ("ProcessMonitor::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1592 process.GetThreadList().AddThread(inferior);
1593 it->second = true;
Matt Kopecb2910442013-07-09 15:09:45 +00001594 process.AddThreadForInitialStopIfNeeded(tid);
Matt Kopec085d6ce2013-05-31 22:00:07 +00001595 }
1596 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001597 }
1598
Matt Kopec085d6ce2013-05-31 22:00:07 +00001599 if (tids_to_attach.size() > 0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001600 {
Matt Kopec085d6ce2013-05-31 22:00:07 +00001601 monitor->m_pid = pid;
1602 // Let our process instance know the thread has stopped.
1603 process.SendMessage(ProcessMessage::Trace(pid));
Johnny Chen25e68e32011-06-14 19:19:50 +00001604 }
Matt Kopec085d6ce2013-05-31 22:00:07 +00001605 else
1606 {
1607 args->m_error.SetErrorToGenericError();
1608 args->m_error.SetErrorString("No such process.");
1609 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001610
1611 FINISH:
1612 return args->m_error.Success();
1613}
1614
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001615bool
Matt Kopec085d6ce2013-05-31 22:00:07 +00001616ProcessMonitor::SetDefaultPtraceOpts(lldb::pid_t pid)
1617{
1618 long ptrace_opts = 0;
1619
1620 // Have the child raise an event on exit. This is used to keep the child in
1621 // limbo until it is destroyed.
1622 ptrace_opts |= PTRACE_O_TRACEEXIT;
1623
1624 // Have the tracer trace threads which spawn in the inferior process.
1625 // TODO: if we want to support tracing the inferiors' child, add the
1626 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1627 ptrace_opts |= PTRACE_O_TRACECLONE;
1628
1629 // Have the tracer notify us before execve returns
1630 // (needed to disable legacy SIGTRAP generation)
1631 ptrace_opts |= PTRACE_O_TRACEEXEC;
1632
1633 return PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)ptrace_opts, 0) >= 0;
1634}
1635
1636bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001637ProcessMonitor::MonitorCallback(void *callback_baton,
1638 lldb::pid_t pid,
Peter Collingbourne2c67b9a2011-11-21 00:10:19 +00001639 bool exited,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001640 int signal,
1641 int status)
1642{
1643 ProcessMessage message;
1644 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001645 ProcessLinux *process = monitor->m_process;
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001646 assert(process);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001647 bool stop_monitoring;
1648 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001649 int ptrace_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001650
Andrew Kaylor93132f52013-05-28 23:04:25 +00001651 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1652
1653 if (exited)
1654 {
1655 if (log)
1656 log->Printf ("ProcessMonitor::%s() got exit signal, tid = %" PRIu64, __FUNCTION__, pid);
1657 message = ProcessMessage::Exit(pid, status);
1658 process->SendMessage(message);
1659 return pid == process->GetID();
1660 }
1661
Daniel Maleaa35970a2012-11-23 18:09:58 +00001662 if (!monitor->GetSignalInfo(pid, &info, ptrace_err)) {
1663 if (ptrace_err == EINVAL) {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001664 if (log)
1665 log->Printf ("ProcessMonitor::%s() resuming from group-stop", __FUNCTION__);
Daniel Maleaa35970a2012-11-23 18:09:58 +00001666 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1667 if (!monitor->Resume(pid, SIGSTOP)) {
1668 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1669 }
1670 stop_monitoring = false;
1671 } else {
1672 // ptrace(GETSIGINFO) failed (but not due to group-stop). Most likely,
1673 // this means the child pid is gone (or not being debugged) therefore
Andrew Kaylor93132f52013-05-28 23:04:25 +00001674 // stop the monitor thread if this is the main pid.
1675 if (log)
1676 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d",
1677 __FUNCTION__, strerror(ptrace_err), pid, signal, status);
1678 stop_monitoring = pid == monitor->m_process->GetID();
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +00001679 // If we are going to stop monitoring, we need to notify our process object
1680 if (stop_monitoring)
1681 {
1682 message = ProcessMessage::Exit(pid, status);
1683 process->SendMessage(message);
1684 }
Daniel Maleaa35970a2012-11-23 18:09:58 +00001685 }
1686 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00001687 else {
1688 switch (info.si_signo)
1689 {
1690 case SIGTRAP:
1691 message = MonitorSIGTRAP(monitor, &info, pid);
1692 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001693
Stephen Wilson84ffe702011-03-30 15:55:52 +00001694 default:
1695 message = MonitorSignal(monitor, &info, pid);
1696 break;
1697 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001698
Stephen Wilson84ffe702011-03-30 15:55:52 +00001699 process->SendMessage(message);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001700 stop_monitoring = false;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001701 }
1702
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001703 return stop_monitoring;
1704}
1705
1706ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +00001707ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001708 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001709{
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001710 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001711
Andrew Kaylor93132f52013-05-28 23:04:25 +00001712 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1713
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001714 assert(monitor);
1715 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001716
Stephen Wilson84ffe702011-03-30 15:55:52 +00001717 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001718 {
1719 default:
1720 assert(false && "Unexpected SIGTRAP code!");
1721 break;
1722
Matt Kopeca360d7e2013-05-17 19:27:47 +00001723 // TODO: these two cases are required if we want to support tracing
1724 // of the inferiors' children
1725 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1726 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1727
Matt Kopec650648f2013-01-08 16:30:18 +00001728 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1729 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001730 if (log)
1731 log->Printf ("ProcessMonitor::%s() received thread creation event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
1732
Matt Kopec650648f2013-01-08 16:30:18 +00001733 unsigned long tid = 0;
1734 if (!monitor->GetEventMessage(pid, &tid))
1735 tid = -1;
1736 message = ProcessMessage::NewThread(pid, tid);
1737 break;
1738 }
1739
Matt Kopeca360d7e2013-05-17 19:27:47 +00001740 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Matt Kopec718be872013-10-09 19:39:55 +00001741 if (log)
1742 log->Printf ("ProcessMonitor::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
1743
1744 message = ProcessMessage::Exec(pid);
Matt Kopeca360d7e2013-05-17 19:27:47 +00001745 break;
1746
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001747 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1748 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001749 // The inferior process or one of its threads is about to exit.
1750 // Maintain the process or thread in a state of "limbo" until we are
1751 // explicitly commanded to detach, destroy, resume, etc.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001752 unsigned long data = 0;
1753 if (!monitor->GetEventMessage(pid, &data))
1754 data = -1;
Andrew Kaylor93132f52013-05-28 23:04:25 +00001755 if (log)
Matt Kopecb2910442013-07-09 15:09:45 +00001756 log->Printf ("ProcessMonitor::%s() received limbo event, data = %lx, pid = %" PRIu64, __FUNCTION__, data, pid);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001757 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001758 break;
1759 }
1760
1761 case 0:
1762 case TRAP_TRACE:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001763 if (log)
1764 log->Printf ("ProcessMonitor::%s() received trace event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001765 message = ProcessMessage::Trace(pid);
1766 break;
1767
1768 case SI_KERNEL:
1769 case TRAP_BRKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001770 if (log)
1771 log->Printf ("ProcessMonitor::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001772 message = ProcessMessage::Break(pid);
1773 break;
Matt Kopece9ea0da2013-05-07 19:29:28 +00001774
1775 case TRAP_HWBKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001776 if (log)
1777 log->Printf ("ProcessMonitor::%s() received watchpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Matt Kopece9ea0da2013-05-07 19:29:28 +00001778 message = ProcessMessage::Watch(pid, (lldb::addr_t)info->si_addr);
1779 break;
Matt Kopec4a32bf52013-07-11 20:01:22 +00001780
1781 case SIGTRAP:
1782 case (SIGTRAP | 0x80):
1783 if (log)
1784 log->Printf ("ProcessMonitor::%s() received system call stop event, pid = %" PRIu64, __FUNCTION__, pid);
1785 // Ignore these signals until we know more about them
1786 monitor->Resume(pid, eResumeSignalNone);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001787 }
1788
1789 return message;
1790}
1791
Stephen Wilson84ffe702011-03-30 15:55:52 +00001792ProcessMessage
1793ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001794 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001795{
1796 ProcessMessage message;
1797 int signo = info->si_signo;
1798
Andrew Kaylor93132f52013-05-28 23:04:25 +00001799 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1800
Stephen Wilson84ffe702011-03-30 15:55:52 +00001801 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1802 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1803 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1804 //
1805 // IOW, user generated signals never generate what we consider to be a
1806 // "crash".
1807 //
1808 // Similarly, ACK signals generated by this monitor.
1809 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1810 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001811 if (log)
Matt Kopecef143712013-06-03 18:00:07 +00001812 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
Andrew Kaylor93132f52013-05-28 23:04:25 +00001813 __FUNCTION__,
1814 monitor->m_process->GetUnixSignals().GetSignalAsCString (signo),
1815 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1816 info->si_pid);
1817
Stephen Wilson84ffe702011-03-30 15:55:52 +00001818 if (info->si_pid == getpid())
1819 return ProcessMessage::SignalDelivered(pid, signo);
1820 else
1821 return ProcessMessage::Signal(pid, signo);
1822 }
1823
Andrew Kaylor93132f52013-05-28 23:04:25 +00001824 if (log)
1825 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals().GetSignalAsCString (signo));
1826
Stephen Wilson84ffe702011-03-30 15:55:52 +00001827 if (signo == SIGSEGV) {
1828 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1829 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1830 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1831 }
1832
1833 if (signo == SIGILL) {
1834 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1835 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1836 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1837 }
1838
1839 if (signo == SIGFPE) {
1840 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1841 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1842 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1843 }
1844
1845 if (signo == SIGBUS) {
1846 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1847 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1848 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1849 }
1850
1851 // Everything else is "normal" and does not require any special action on
1852 // our part.
1853 return ProcessMessage::Signal(pid, signo);
1854}
1855
Andrew Kaylord4d54992013-09-17 00:30:24 +00001856// On Linux, when a new thread is created, we receive to notifications,
1857// (1) a SIGTRAP|PTRACE_EVENT_CLONE from the main process thread with the
1858// child thread id as additional information, and (2) a SIGSTOP|SI_USER from
1859// the new child thread indicating that it has is stopped because we attached.
1860// We have no guarantee of the order in which these arrive, but we need both
1861// before we are ready to proceed. We currently keep a list of threads which
1862// have sent the initial SIGSTOP|SI_USER event. Then when we receive the
1863// SIGTRAP|PTRACE_EVENT_CLONE notification, if the initial stop has not occurred
1864// we call ProcessMonitor::WaitForInitialTIDStop() to wait for it.
1865
1866bool
1867ProcessMonitor::WaitForInitialTIDStop(lldb::tid_t tid)
1868{
1869 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1870 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001871 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waiting for thread to stop...", __FUNCTION__, tid);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001872
1873 // Wait for the thread to stop
1874 while (true)
1875 {
1876 int status = -1;
1877 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001878 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waitpid...", __FUNCTION__, tid);
Todd Fiala9be50492014-07-01 16:30:53 +00001879 ::pid_t wait_pid = waitpid(tid, &status, __WALL);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001880 if (status == -1)
1881 {
1882 // If we got interrupted by a signal (in our process, not the
1883 // inferior) try again.
1884 if (errno == EINTR)
1885 continue;
1886 else
1887 {
1888 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001889 log->Printf("ProcessMonitor::%s(%" PRIu64 ") waitpid error -- %s", __FUNCTION__, tid, strerror(errno));
Andrew Kaylord4d54992013-09-17 00:30:24 +00001890 return false; // This is bad, but there's nothing we can do.
1891 }
1892 }
1893
1894 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001895 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waitpid, status = %d", __FUNCTION__, tid, status);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001896
Todd Fiala9be50492014-07-01 16:30:53 +00001897 assert(static_cast<lldb::tid_t>(wait_pid) == tid);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001898
1899 siginfo_t info;
1900 int ptrace_err;
1901 if (!GetSignalInfo(wait_pid, &info, ptrace_err))
1902 {
1903 if (log)
1904 {
1905 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed. errno=%d (%s)", __FUNCTION__, ptrace_err, strerror(ptrace_err));
1906 }
1907 return false;
1908 }
1909
1910 // If this is a thread exit, we won't get any more information.
1911 if (WIFEXITED(status))
1912 {
1913 m_process->SendMessage(ProcessMessage::Exit(wait_pid, WEXITSTATUS(status)));
Todd Fiala9be50492014-07-01 16:30:53 +00001914 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Andrew Kaylord4d54992013-09-17 00:30:24 +00001915 return true;
1916 continue;
1917 }
1918
1919 assert(info.si_code == SI_USER);
1920 assert(WSTOPSIG(status) == SIGSTOP);
1921
1922 if (log)
1923 log->Printf ("ProcessMonitor::%s(bp) received thread stop signal", __FUNCTION__);
1924 m_process->AddThreadForInitialStopIfNeeded(wait_pid);
1925 return true;
1926 }
1927 return false;
1928}
1929
Andrew Kaylor93132f52013-05-28 23:04:25 +00001930bool
1931ProcessMonitor::StopThread(lldb::tid_t tid)
1932{
1933 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1934
1935 // FIXME: Try to use tgkill or tkill
1936 int ret = tgkill(m_pid, tid, SIGSTOP);
1937 if (log)
1938 log->Printf ("ProcessMonitor::%s(bp) stopping thread, tid = %" PRIu64 ", ret = %d", __FUNCTION__, tid, ret);
1939
1940 // This can happen if a thread exited while we were trying to stop it. That's OK.
1941 // We'll get the signal for that later.
1942 if (ret < 0)
1943 return false;
1944
1945 // Wait for the thread to stop
1946 while (true)
1947 {
1948 int status = -1;
1949 if (log)
1950 log->Printf ("ProcessMonitor::%s(bp) waitpid...", __FUNCTION__);
Todd Fiala9be50492014-07-01 16:30:53 +00001951 ::pid_t wait_pid = ::waitpid (-1*getpgid(m_pid), &status, __WALL);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001952 if (log)
Todd Fiala9be50492014-07-01 16:30:53 +00001953 log->Printf ("ProcessMonitor::%s(bp) waitpid, pid = %" PRIu64 ", status = %d",
1954 __FUNCTION__, static_cast<lldb::pid_t>(wait_pid), status);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001955
Todd Fiala9be50492014-07-01 16:30:53 +00001956 if (wait_pid == -1)
Andrew Kaylor93132f52013-05-28 23:04:25 +00001957 {
1958 // If we got interrupted by a signal (in our process, not the
1959 // inferior) try again.
1960 if (errno == EINTR)
1961 continue;
1962 else
1963 return false; // This is bad, but there's nothing we can do.
1964 }
1965
1966 // If this is a thread exit, we won't get any more information.
1967 if (WIFEXITED(status))
1968 {
1969 m_process->SendMessage(ProcessMessage::Exit(wait_pid, WEXITSTATUS(status)));
Todd Fiala9be50492014-07-01 16:30:53 +00001970 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Andrew Kaylor93132f52013-05-28 23:04:25 +00001971 return true;
1972 continue;
1973 }
1974
1975 siginfo_t info;
1976 int ptrace_err;
1977 if (!GetSignalInfo(wait_pid, &info, ptrace_err))
1978 {
Todd Fiala1b0539c2014-01-27 17:03:57 +00001979 // another signal causing a StopAllThreads may have been received
1980 // before wait_pid's group-stop was processed, handle it now
1981 if (ptrace_err == EINVAL)
Andrew Kaylor93132f52013-05-28 23:04:25 +00001982 {
Todd Fiala1b0539c2014-01-27 17:03:57 +00001983 assert(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001984
Todd Fiala1b0539c2014-01-27 17:03:57 +00001985 if (log)
1986 log->Printf ("ProcessMonitor::%s() resuming from group-stop", __FUNCTION__);
1987 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1988 if (!Resume(wait_pid, SIGSTOP)) {
1989 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1990 }
1991 continue;
Andrew Kaylor93132f52013-05-28 23:04:25 +00001992 }
Todd Fiala1b0539c2014-01-27 17:03:57 +00001993
1994 if (log)
1995 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed.", __FUNCTION__);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001996 return false;
1997 }
1998
1999 // Handle events from other threads
2000 if (log)
Todd Fiala9be50492014-07-01 16:30:53 +00002001 log->Printf ("ProcessMonitor::%s(bp) handling event, tid == %" PRIu64,
2002 __FUNCTION__, static_cast<lldb::tid_t>(wait_pid));
Andrew Kaylor93132f52013-05-28 23:04:25 +00002003
2004 ProcessMessage message;
2005 if (info.si_signo == SIGTRAP)
2006 message = MonitorSIGTRAP(this, &info, wait_pid);
2007 else
2008 message = MonitorSignal(this, &info, wait_pid);
2009
2010 POSIXThread *thread = static_cast<POSIXThread*>(m_process->GetThreadList().FindThreadByID(wait_pid).get());
2011
2012 // When a new thread is created, we may get a SIGSTOP for the new thread
2013 // just before we get the SIGTRAP that we use to add the thread to our
2014 // process thread list. We don't need to worry about that signal here.
2015 assert(thread || message.GetKind() == ProcessMessage::eSignalMessage);
2016
2017 if (!thread)
2018 {
2019 m_process->SendMessage(message);
2020 continue;
2021 }
2022
2023 switch (message.GetKind())
2024 {
Saleem Abdulrasool6747c7d2014-07-20 05:28:57 +00002025 case ProcessMessage::eExecMessage:
2026 llvm_unreachable("unexpected message");
Michael Sartainc258b302013-09-18 15:32:06 +00002027 case ProcessMessage::eAttachMessage:
Andrew Kaylor93132f52013-05-28 23:04:25 +00002028 case ProcessMessage::eInvalidMessage:
2029 break;
2030
2031 // These need special handling because we don't want to send a
2032 // resume even if we already sent a SIGSTOP to this thread. In
2033 // this case the resume will cause the thread to disappear. It is
2034 // unlikely that we'll ever get eExitMessage here, but the same
2035 // reasoning applies.
2036 case ProcessMessage::eLimboMessage:
2037 case ProcessMessage::eExitMessage:
2038 if (log)
2039 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
2040 // SendMessage will set the thread state as needed.
2041 m_process->SendMessage(message);
2042 // If this is the thread we're waiting for, stop waiting. Even
2043 // though this wasn't the signal we expected, it's the last
2044 // signal we'll see while this thread is alive.
Todd Fiala9be50492014-07-01 16:30:53 +00002045 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Andrew Kaylor93132f52013-05-28 23:04:25 +00002046 return true;
2047 break;
2048
Matt Kopecb2910442013-07-09 15:09:45 +00002049 case ProcessMessage::eSignalMessage:
2050 if (log)
2051 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
2052 if (WSTOPSIG(status) == SIGSTOP)
2053 {
2054 m_process->AddThreadForInitialStopIfNeeded(tid);
2055 thread->SetState(lldb::eStateStopped);
2056 }
2057 else
2058 {
2059 m_process->SendMessage(message);
2060 // This isn't the stop we were expecting, but the thread is
2061 // stopped. SendMessage will handle processing of this event,
2062 // but we need to resume here to get the stop we are waiting
2063 // for (otherwise the thread will stop again immediately when
2064 // we try to resume).
Todd Fiala9be50492014-07-01 16:30:53 +00002065 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Matt Kopecb2910442013-07-09 15:09:45 +00002066 Resume(wait_pid, eResumeSignalNone);
2067 }
2068 break;
2069
Andrew Kaylor93132f52013-05-28 23:04:25 +00002070 case ProcessMessage::eSignalDeliveredMessage:
2071 // This is the stop we're expecting.
Todd Fiala9be50492014-07-01 16:30:53 +00002072 if (static_cast<lldb::tid_t>(wait_pid) == tid &&
2073 WIFSTOPPED(status) &&
2074 WSTOPSIG(status) == SIGSTOP &&
2075 info.si_code == SI_TKILL)
Andrew Kaylor93132f52013-05-28 23:04:25 +00002076 {
2077 if (log)
2078 log->Printf ("ProcessMonitor::%s(bp) received signal, done waiting", __FUNCTION__);
2079 thread->SetState(lldb::eStateStopped);
2080 return true;
2081 }
2082 // else fall-through
Andrew Kaylor93132f52013-05-28 23:04:25 +00002083 case ProcessMessage::eBreakpointMessage:
2084 case ProcessMessage::eTraceMessage:
2085 case ProcessMessage::eWatchpointMessage:
2086 case ProcessMessage::eCrashMessage:
2087 case ProcessMessage::eNewThreadMessage:
2088 if (log)
2089 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
2090 // SendMessage will set the thread state as needed.
2091 m_process->SendMessage(message);
2092 // This isn't the stop we were expecting, but the thread is
2093 // stopped. SendMessage will handle processing of this event,
2094 // but we need to resume here to get the stop we are waiting
2095 // for (otherwise the thread will stop again immediately when
2096 // we try to resume).
Todd Fiala9be50492014-07-01 16:30:53 +00002097 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Andrew Kaylor93132f52013-05-28 23:04:25 +00002098 Resume(wait_pid, eResumeSignalNone);
2099 break;
2100 }
2101 }
2102 return false;
2103}
2104
Stephen Wilson84ffe702011-03-30 15:55:52 +00002105ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00002106ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002107{
2108 ProcessMessage::CrashReason reason;
2109 assert(info->si_signo == SIGSEGV);
2110
2111 reason = ProcessMessage::eInvalidCrashReason;
2112
Greg Clayton542e4072012-09-07 17:49:29 +00002113 switch (info->si_code)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002114 {
2115 default:
2116 assert(false && "unexpected si_code for SIGSEGV");
2117 break;
Matt Kopecf8cfe6b2013-08-09 15:26:56 +00002118 case SI_KERNEL:
2119 // Linux will occasionally send spurious SI_KERNEL codes.
2120 // (this is poorly documented in sigaction)
2121 // One way to get this is via unaligned SIMD loads.
2122 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2123 break;
Stephen Wilson84ffe702011-03-30 15:55:52 +00002124 case SEGV_MAPERR:
2125 reason = ProcessMessage::eInvalidAddress;
2126 break;
2127 case SEGV_ACCERR:
2128 reason = ProcessMessage::ePrivilegedAddress;
2129 break;
2130 }
Greg Clayton542e4072012-09-07 17:49:29 +00002131
Stephen Wilson84ffe702011-03-30 15:55:52 +00002132 return reason;
2133}
2134
2135ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00002136ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002137{
2138 ProcessMessage::CrashReason reason;
2139 assert(info->si_signo == SIGILL);
2140
2141 reason = ProcessMessage::eInvalidCrashReason;
2142
2143 switch (info->si_code)
2144 {
2145 default:
2146 assert(false && "unexpected si_code for SIGILL");
2147 break;
2148 case ILL_ILLOPC:
2149 reason = ProcessMessage::eIllegalOpcode;
2150 break;
2151 case ILL_ILLOPN:
2152 reason = ProcessMessage::eIllegalOperand;
2153 break;
2154 case ILL_ILLADR:
2155 reason = ProcessMessage::eIllegalAddressingMode;
2156 break;
2157 case ILL_ILLTRP:
2158 reason = ProcessMessage::eIllegalTrap;
2159 break;
2160 case ILL_PRVOPC:
2161 reason = ProcessMessage::ePrivilegedOpcode;
2162 break;
2163 case ILL_PRVREG:
2164 reason = ProcessMessage::ePrivilegedRegister;
2165 break;
2166 case ILL_COPROC:
2167 reason = ProcessMessage::eCoprocessorError;
2168 break;
2169 case ILL_BADSTK:
2170 reason = ProcessMessage::eInternalStackError;
2171 break;
2172 }
2173
2174 return reason;
2175}
2176
2177ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00002178ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002179{
2180 ProcessMessage::CrashReason reason;
2181 assert(info->si_signo == SIGFPE);
2182
2183 reason = ProcessMessage::eInvalidCrashReason;
2184
2185 switch (info->si_code)
2186 {
2187 default:
2188 assert(false && "unexpected si_code for SIGFPE");
2189 break;
2190 case FPE_INTDIV:
2191 reason = ProcessMessage::eIntegerDivideByZero;
2192 break;
2193 case FPE_INTOVF:
2194 reason = ProcessMessage::eIntegerOverflow;
2195 break;
2196 case FPE_FLTDIV:
2197 reason = ProcessMessage::eFloatDivideByZero;
2198 break;
2199 case FPE_FLTOVF:
2200 reason = ProcessMessage::eFloatOverflow;
2201 break;
2202 case FPE_FLTUND:
2203 reason = ProcessMessage::eFloatUnderflow;
2204 break;
2205 case FPE_FLTRES:
2206 reason = ProcessMessage::eFloatInexactResult;
2207 break;
2208 case FPE_FLTINV:
2209 reason = ProcessMessage::eFloatInvalidOperation;
2210 break;
2211 case FPE_FLTSUB:
2212 reason = ProcessMessage::eFloatSubscriptRange;
2213 break;
2214 }
2215
2216 return reason;
2217}
2218
2219ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00002220ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002221{
2222 ProcessMessage::CrashReason reason;
2223 assert(info->si_signo == SIGBUS);
2224
2225 reason = ProcessMessage::eInvalidCrashReason;
2226
2227 switch (info->si_code)
2228 {
2229 default:
2230 assert(false && "unexpected si_code for SIGBUS");
2231 break;
2232 case BUS_ADRALN:
2233 reason = ProcessMessage::eIllegalAlignment;
2234 break;
2235 case BUS_ADRERR:
2236 reason = ProcessMessage::eIllegalAddress;
2237 break;
2238 case BUS_OBJERR:
2239 reason = ProcessMessage::eHardwareError;
2240 break;
2241 }
2242
2243 return reason;
2244}
2245
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002246void
Johnny Chen25e68e32011-06-14 19:19:50 +00002247ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002248{
Stephen Wilson570243b2011-01-19 01:37:06 +00002249 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002250
Stephen Wilson570243b2011-01-19 01:37:06 +00002251 // We are finised with the arguments and are ready to go. Sync with the
2252 // parent thread and start serving operations on the inferior.
2253 sem_post(&args->m_semaphore);
2254
Michael Sartain704bf892013-10-09 01:28:57 +00002255 for(;;)
2256 {
Daniel Malea1efb4182013-09-16 23:12:18 +00002257 // wait for next pending operation
Todd Fiala8ce3dee2014-01-24 22:59:22 +00002258 if (sem_wait(&monitor->m_operation_pending))
2259 {
2260 if (errno == EINTR)
2261 continue;
2262 assert(false && "Unexpected errno from sem_wait");
2263 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002264
Daniel Malea1efb4182013-09-16 23:12:18 +00002265 monitor->m_operation->Execute(monitor);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002266
Daniel Malea1efb4182013-09-16 23:12:18 +00002267 // notify calling thread that operation is complete
2268 sem_post(&monitor->m_operation_done);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002269 }
2270}
2271
2272void
2273ProcessMonitor::DoOperation(Operation *op)
2274{
Daniel Malea1efb4182013-09-16 23:12:18 +00002275 Mutex::Locker lock(m_operation_mutex);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002276
Daniel Malea1efb4182013-09-16 23:12:18 +00002277 m_operation = op;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002278
Daniel Malea1efb4182013-09-16 23:12:18 +00002279 // notify operation thread that an operation is ready to be processed
2280 sem_post(&m_operation_pending);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002281
Daniel Malea1efb4182013-09-16 23:12:18 +00002282 // wait for operation to complete
Todd Fiala8ce3dee2014-01-24 22:59:22 +00002283 while (sem_wait(&m_operation_done))
2284 {
2285 if (errno == EINTR)
2286 continue;
2287 assert(false && "Unexpected errno from sem_wait");
2288 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002289}
2290
2291size_t
2292ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
2293 Error &error)
2294{
2295 size_t result;
2296 ReadOperation op(vm_addr, buf, size, error, result);
2297 DoOperation(&op);
2298 return result;
2299}
2300
2301size_t
2302ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
2303 lldb_private::Error &error)
2304{
2305 size_t result;
2306 WriteOperation op(vm_addr, buf, size, error, result);
2307 DoOperation(&op);
2308 return result;
2309}
2310
2311bool
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002312ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
Matt Kopec7de48462013-03-06 17:20:48 +00002313 unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002314{
2315 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002316 ReadRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002317 DoOperation(&op);
2318 return result;
2319}
2320
2321bool
Matt Kopec7de48462013-03-06 17:20:48 +00002322ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002323 const char* reg_name, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002324{
2325 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002326 WriteRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002327 DoOperation(&op);
2328 return result;
2329}
2330
2331bool
Matt Kopec7de48462013-03-06 17:20:48 +00002332ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002333{
2334 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002335 ReadGPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002336 DoOperation(&op);
2337 return result;
2338}
2339
2340bool
Matt Kopec7de48462013-03-06 17:20:48 +00002341ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002342{
2343 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002344 ReadFPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002345 DoOperation(&op);
2346 return result;
2347}
2348
2349bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002350ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2351{
2352 bool result;
2353 ReadRegisterSetOperation op(tid, buf, buf_size, regset, result);
2354 DoOperation(&op);
2355 return result;
2356}
2357
2358bool
Matt Kopec7de48462013-03-06 17:20:48 +00002359ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002360{
2361 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002362 WriteGPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002363 DoOperation(&op);
2364 return result;
2365}
2366
2367bool
Matt Kopec7de48462013-03-06 17:20:48 +00002368ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002369{
2370 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002371 WriteFPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002372 DoOperation(&op);
2373 return result;
2374}
2375
2376bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002377ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2378{
2379 bool result;
2380 WriteRegisterSetOperation op(tid, buf, buf_size, regset, result);
2381 DoOperation(&op);
2382 return result;
2383}
2384
2385bool
Richard Mitton0a558352013-10-17 21:14:00 +00002386ProcessMonitor::ReadThreadPointer(lldb::tid_t tid, lldb::addr_t &value)
2387{
2388 bool result;
2389 ReadThreadPointerOperation op(tid, &value, result);
2390 DoOperation(&op);
2391 return result;
2392}
2393
2394bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002395ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002396{
2397 bool result;
Andrew Kaylor93132f52013-05-28 23:04:25 +00002398 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
2399
2400 if (log)
2401 log->Printf ("ProcessMonitor::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
2402 m_process->GetUnixSignals().GetSignalAsCString (signo));
Stephen Wilson84ffe702011-03-30 15:55:52 +00002403 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002404 DoOperation(&op);
Andrew Kaylor93132f52013-05-28 23:04:25 +00002405 if (log)
2406 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002407 return result;
2408}
2409
2410bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002411ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002412{
2413 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00002414 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002415 DoOperation(&op);
2416 return result;
2417}
2418
2419bool
Ed Maste4e0999b2014-04-01 18:14:06 +00002420ProcessMonitor::Kill()
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002421{
Ed Maste4e0999b2014-04-01 18:14:06 +00002422 return kill(GetPID(), SIGKILL) == 0;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002423}
2424
2425bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00002426ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002427{
2428 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00002429 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002430 DoOperation(&op);
2431 return result;
2432}
2433
2434bool
2435ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2436{
2437 bool result;
2438 EventMessageOperation op(tid, message, result);
2439 DoOperation(&op);
2440 return result;
2441}
2442
Greg Clayton743ecf42012-10-16 20:20:18 +00002443lldb_private::Error
Matt Kopec085d6ce2013-05-31 22:00:07 +00002444ProcessMonitor::Detach(lldb::tid_t tid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002445{
Greg Clayton28041352011-11-29 20:50:10 +00002446 lldb_private::Error error;
Matt Kopec085d6ce2013-05-31 22:00:07 +00002447 if (tid != LLDB_INVALID_THREAD_ID)
2448 {
2449 DetachOperation op(tid, error);
Greg Clayton743ecf42012-10-16 20:20:18 +00002450 DoOperation(&op);
2451 }
Greg Clayton743ecf42012-10-16 20:20:18 +00002452 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00002453}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002454
2455bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002456ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
2457{
Peter Collingbourne62343202011-06-14 03:55:54 +00002458 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002459
2460 if (target_fd == -1)
2461 return false;
2462
Peter Collingbourne62343202011-06-14 03:55:54 +00002463 return (dup2(target_fd, fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002464}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002465
2466void
2467ProcessMonitor::StopMonitoringChildProcess()
2468{
Zachary Turner39de3112014-09-09 20:54:56 +00002469 if (m_monitor_thread.GetState() == eThreadStateRunning)
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002470 {
Zachary Turner39de3112014-09-09 20:54:56 +00002471 m_monitor_thread.Cancel();
2472 m_monitor_thread.Join(nullptr);
2473 m_monitor_thread.Reset();
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002474 }
2475}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002476
2477void
2478ProcessMonitor::StopMonitor()
2479{
2480 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00002481 StopOpThread();
Daniel Malea1efb4182013-09-16 23:12:18 +00002482 sem_destroy(&m_operation_pending);
2483 sem_destroy(&m_operation_done);
2484
Andrew Kaylor5e268992013-09-14 00:17:31 +00002485 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
2486 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
2487 // the descriptor to a ConnectionFileDescriptor object. Consequently
2488 // even though still has the file descriptor, we shouldn't close it here.
Stephen Wilson84ffe702011-03-30 15:55:52 +00002489}
2490
2491void
Greg Clayton743ecf42012-10-16 20:20:18 +00002492ProcessMonitor::StopOpThread()
2493{
Zachary Turner39de3112014-09-09 20:54:56 +00002494 if (m_operation_thread.GetState() != eThreadStateRunning)
Greg Clayton743ecf42012-10-16 20:20:18 +00002495 return;
2496
Zachary Turner39de3112014-09-09 20:54:56 +00002497 m_operation_thread.Cancel();
2498 m_operation_thread.Join(nullptr);
2499 m_operation_thread.Reset();
Greg Clayton743ecf42012-10-16 20:20:18 +00002500}