blob: 3efeb5de627ea3a584bedf329f2dd0e02e48ac22 [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>
Shawn Best8da0bf32014-11-08 01:41:49 +000019#if defined(__ANDROID_NDK__) && defined (__arm__)
20#include <linux/personality.h>
21#include <linux/user.h>
22#else
Todd Fiala0bce1b62014-08-17 00:10:50 +000023#include <sys/personality.h>
Shawn Best8da0bf32014-11-08 01:41:49 +000024#include <sys/user.h>
25#endif
Todd Fialacacde7d2014-09-27 16:54:22 +000026#ifndef __ANDROID__
Todd Fiala49131cf2014-09-12 16:57:28 +000027#include <sys/procfs.h>
Todd Fialacacde7d2014-09-27 16:54:22 +000028#endif
Stephen Wilsone6f9f662010-07-24 02:19:04 +000029#include <sys/ptrace.h>
Todd Fiala6ac1be42014-08-21 16:34:03 +000030#include <sys/uio.h>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000031#include <sys/socket.h>
Andrew Kaylor93132f52013-05-28 23:04:25 +000032#include <sys/syscall.h>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000033#include <sys/types.h>
34#include <sys/wait.h>
35
36// C++ Includes
37// Other libraries and framework includes
Johnny Chen0d5f2d42011-10-18 18:09:30 +000038#include "lldb/Core/Debugger.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000039#include "lldb/Core/Error.h"
Johnny Chen13e8e1c2011-05-13 21:29:50 +000040#include "lldb/Core/RegisterValue.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000041#include "lldb/Core/Scalar.h"
42#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000043#include "lldb/Host/HostThread.h"
44#include "lldb/Host/ThreadLauncher.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000045#include "lldb/Target/Thread.h"
46#include "lldb/Target/RegisterContext.h"
47#include "lldb/Utility/PseudoTerminal.h"
48
Todd Fialacacde7d2014-09-27 16:54:22 +000049#include "Plugins/Process/POSIX/POSIXThread.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000050#include "ProcessLinux.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000051#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000052#include "ProcessMonitor.h"
53
Todd Fialacacde7d2014-09-27 16:54:22 +000054#ifdef __ANDROID__
55#define __ptrace_request int
56#define PT_DETACH PTRACE_DETACH
57#endif
58
Greg Clayton386ff182011-11-05 01:09:16 +000059#define DEBUG_PTRACE_MAXBYTES 20
60
Matt Kopec58c0b962013-03-20 20:34:35 +000061// Support ptrace extensions even when compiled without required kernel support
62#ifndef PTRACE_GETREGSET
63 #define PTRACE_GETREGSET 0x4204
64#endif
65#ifndef PTRACE_SETREGSET
66 #define PTRACE_SETREGSET 0x4205
67#endif
Richard Mitton0a558352013-10-17 21:14:00 +000068#ifndef PTRACE_GET_THREAD_AREA
69 #define PTRACE_GET_THREAD_AREA 25
70#endif
71#ifndef PTRACE_ARCH_PRCTL
72 #define PTRACE_ARCH_PRCTL 30
73#endif
74#ifndef ARCH_GET_FS
75 #define ARCH_SET_GS 0x1001
76 #define ARCH_SET_FS 0x1002
77 #define ARCH_GET_FS 0x1003
78 #define ARCH_GET_GS 0x1004
79#endif
80
Todd Fiala0bce1b62014-08-17 00:10:50 +000081#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Matt Kopec58c0b962013-03-20 20:34:35 +000082
Todd Fialadbec1ff2014-09-04 16:08:20 +000083#define LLDB_PTRACE_NT_ARM_TLS 0x401 // ARM TLS register
84
Matt Kopece9ea0da2013-05-07 19:29:28 +000085// Support hardware breakpoints in case it has not been defined
86#ifndef TRAP_HWBKPT
87 #define TRAP_HWBKPT 4
88#endif
89
Andrew Kaylor93132f52013-05-28 23:04:25 +000090// Try to define a macro to encapsulate the tgkill syscall
91// fall back on kill() if tgkill isn't available
92#define tgkill(pid, tid, sig) syscall(SYS_tgkill, pid, tid, sig)
93
Stephen Wilsone6f9f662010-07-24 02:19:04 +000094using namespace lldb_private;
95
Johnny Chen0d5f2d42011-10-18 18:09:30 +000096// FIXME: this code is host-dependent with respect to types and
97// endianness and needs to be fixed. For example, lldb::addr_t is
98// hard-coded to uint64_t, but on a 32-bit Linux host, ptrace requires
99// 32-bit pointer arguments. This code uses casts to work around the
100// problem.
101
102// We disable the tracing of ptrace calls for integration builds to
103// avoid the additional indirection and checks.
104#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
105
Greg Clayton386ff182011-11-05 01:09:16 +0000106static void
107DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
108{
109 uint8_t *ptr = (uint8_t *)bytes;
110 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
111 for(uint32_t i=0; i<loop_count; i++)
112 {
113 s.Printf ("[%x]", *ptr);
114 ptr++;
115 }
116}
117
Matt Kopec58c0b962013-03-20 20:34:35 +0000118static void PtraceDisplayBytes(int &req, void *data, size_t data_size)
Greg Clayton386ff182011-11-05 01:09:16 +0000119{
120 StreamString buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000121 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
Johnny Chen30213ff2012-01-05 19:17:38 +0000122 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
Greg Clayton386ff182011-11-05 01:09:16 +0000123
124 if (verbose_log)
125 {
126 switch(req)
127 {
128 case PTRACE_POKETEXT:
129 {
130 DisplayBytes(buf, &data, 8);
131 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
132 break;
133 }
Greg Clayton542e4072012-09-07 17:49:29 +0000134 case PTRACE_POKEDATA:
Greg Clayton386ff182011-11-05 01:09:16 +0000135 {
136 DisplayBytes(buf, &data, 8);
137 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
138 break;
139 }
Greg Clayton542e4072012-09-07 17:49:29 +0000140 case PTRACE_POKEUSER:
Greg Clayton386ff182011-11-05 01:09:16 +0000141 {
142 DisplayBytes(buf, &data, 8);
143 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
144 break;
145 }
Todd Fiala6ac1be42014-08-21 16:34:03 +0000146#if !defined (__arm64__) && !defined (__aarch64__)
Greg Clayton542e4072012-09-07 17:49:29 +0000147 case PTRACE_SETREGS:
Greg Clayton386ff182011-11-05 01:09:16 +0000148 {
Matt Kopec7de48462013-03-06 17:20:48 +0000149 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000150 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
151 break;
152 }
153 case PTRACE_SETFPREGS:
154 {
Matt Kopec7de48462013-03-06 17:20:48 +0000155 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000156 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
157 break;
158 }
Todd Fialad35f2b92014-06-23 15:59:04 +0000159#endif
Greg Clayton542e4072012-09-07 17:49:29 +0000160 case PTRACE_SETSIGINFO:
Greg Clayton386ff182011-11-05 01:09:16 +0000161 {
162 DisplayBytes(buf, data, sizeof(siginfo_t));
163 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
164 break;
165 }
Matt Kopec58c0b962013-03-20 20:34:35 +0000166 case PTRACE_SETREGSET:
167 {
168 // Extract iov_base from data, which is a pointer to the struct IOVEC
169 DisplayBytes(buf, *(void **)data, data_size);
170 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
171 break;
172 }
Greg Clayton386ff182011-11-05 01:09:16 +0000173 default:
174 {
175 }
176 }
177 }
178}
179
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000180// Wrapper for ptrace to catch errors and log calls.
Ashok Thirumurthi762fbd02013-03-27 21:09:30 +0000181// 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 +0000182extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000183PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000184 const char* reqName, const char* file, int line)
185{
Greg Clayton386ff182011-11-05 01:09:16 +0000186 long int result;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000187
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000188 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
Greg Clayton386ff182011-11-05 01:09:16 +0000189
Matt Kopec7de48462013-03-06 17:20:48 +0000190 PtraceDisplayBytes(req, data, data_size);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000191
192 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000193 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala4507f062014-02-27 20:46:12 +0000194 result = ptrace(static_cast<__ptrace_request>(req), static_cast<pid_t>(pid), *(unsigned int *)addr, data);
Matt Kopec58c0b962013-03-20 20:34:35 +0000195 else
Todd Fiala4507f062014-02-27 20:46:12 +0000196 result = ptrace(static_cast<__ptrace_request>(req), static_cast<pid_t>(pid), addr, data);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000197
Ed Mastec099c952014-02-24 14:07:45 +0000198 if (log)
199 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
200 reqName, pid, addr, data, data_size, result, file, line);
201
Matt Kopec7de48462013-03-06 17:20:48 +0000202 PtraceDisplayBytes(req, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000203
Matt Kopec7de48462013-03-06 17:20:48 +0000204 if (log && errno != 0)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000205 {
206 const char* str;
207 switch (errno)
208 {
209 case ESRCH: str = "ESRCH"; break;
210 case EINVAL: str = "EINVAL"; break;
211 case EBUSY: str = "EBUSY"; break;
212 case EPERM: str = "EPERM"; break;
213 default: str = "<unknown>";
214 }
215 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
216 }
217
218 return result;
219}
220
Matt Kopec7de48462013-03-06 17:20:48 +0000221// Wrapper for ptrace when logging is not required.
222// Sets errno to 0 prior to calling ptrace.
223extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000224PtraceWrapper(int req, pid_t pid, void *addr, void *data, size_t data_size)
Matt Kopec7de48462013-03-06 17:20:48 +0000225{
Matt Kopec58c0b962013-03-20 20:34:35 +0000226 long result = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000227 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000228 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
229 result = ptrace(static_cast<__ptrace_request>(req), pid, *(unsigned int *)addr, data);
230 else
231 result = ptrace(static_cast<__ptrace_request>(req), pid, addr, data);
Matt Kopec7de48462013-03-06 17:20:48 +0000232 return result;
233}
234
235#define PTRACE(req, pid, addr, data, data_size) \
236 PtraceWrapper((req), (pid), (addr), (data), (data_size), #req, __FILE__, __LINE__)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000237#else
Matt Kopec7de48462013-03-06 17:20:48 +0000238 PtraceWrapper((req), (pid), (addr), (data), (data_size))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000239#endif
240
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000241//------------------------------------------------------------------------------
242// Static implementations of ProcessMonitor::ReadMemory and
243// ProcessMonitor::WriteMemory. This enables mutual recursion between these
244// functions without needed to go thru the thread funnel.
245
246static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000247DoReadMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000248 lldb::addr_t vm_addr, void *buf, size_t size, Error &error)
249{
Greg Clayton542e4072012-09-07 17:49:29 +0000250 // ptrace word size is determined by the host, not the child
251 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000252 unsigned char *dst = static_cast<unsigned char*>(buf);
253 size_t bytes_read;
254 size_t remainder;
255 long data;
256
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000257 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000258 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000259 ProcessPOSIXLog::IncNestLevel();
260 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000261 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000262 pid, word_size, (void*)vm_addr, buf, size);
263
264 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000265 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
266 {
267 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000268 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, NULL, 0);
269 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000270 {
271 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000272 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000273 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000274 return bytes_read;
275 }
276
277 remainder = size - bytes_read;
278 remainder = remainder > word_size ? word_size : remainder;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000279
280 // Copy the data into our buffer
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000281 for (unsigned i = 0; i < remainder; ++i)
282 dst[i] = ((data >> i*8) & 0xFF);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000283
Johnny Chen30213ff2012-01-05 19:17:38 +0000284 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
285 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
286 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
287 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Daniel Maleac63dddd2012-12-14 21:07:07 +0000288 {
289 uintptr_t print_dst = 0;
290 // Format bytes from data by moving into print_dst for log output
291 for (unsigned i = 0; i < remainder; ++i)
292 print_dst |= (((data >> i*8) & 0xFF) << i*8);
293 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
294 (void*)vm_addr, print_dst, (unsigned long)data);
295 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000296
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000297 vm_addr += word_size;
298 dst += word_size;
299 }
300
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000301 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000302 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000303 return bytes_read;
304}
305
306static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000307DoWriteMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000308 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
309{
Greg Clayton542e4072012-09-07 17:49:29 +0000310 // ptrace word size is determined by the host, not the child
311 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000312 const unsigned char *src = static_cast<const unsigned char*>(buf);
313 size_t bytes_written = 0;
314 size_t remainder;
315
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000316 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000317 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000318 ProcessPOSIXLog::IncNestLevel();
319 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000320 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000321 pid, word_size, (void*)vm_addr, buf, size);
322
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000323 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
324 {
325 remainder = size - bytes_written;
326 remainder = remainder > word_size ? word_size : remainder;
327
328 if (remainder == word_size)
329 {
330 unsigned long data = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000331 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000332 for (unsigned i = 0; i < word_size; ++i)
333 data |= (unsigned long)src[i] << i*8;
334
Johnny Chen30213ff2012-01-05 19:17:38 +0000335 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
336 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
337 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
338 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000339 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
340 (void*)vm_addr, *(unsigned long*)src, data);
341
Matt Kopec7de48462013-03-06 17:20:48 +0000342 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000343 {
344 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000345 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000346 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000347 return bytes_written;
348 }
349 }
350 else
351 {
352 unsigned char buff[8];
Greg Clayton542e4072012-09-07 17:49:29 +0000353 if (DoReadMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000354 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000355 {
356 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000357 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000358 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000359 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000360
361 memcpy(buff, src, remainder);
362
Greg Clayton542e4072012-09-07 17:49:29 +0000363 if (DoWriteMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000364 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000365 {
366 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000367 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000368 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000369 }
370
Johnny Chen30213ff2012-01-05 19:17:38 +0000371 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
372 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
373 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
374 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000375 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
376 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000377 }
378
379 vm_addr += word_size;
380 src += word_size;
381 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000382 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000383 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000384 return bytes_written;
385}
386
Stephen Wilson26977162011-03-23 02:14:42 +0000387// Simple helper function to ensure flags are enabled on the given file
388// descriptor.
389static bool
390EnsureFDFlags(int fd, int flags, Error &error)
391{
392 int status;
393
394 if ((status = fcntl(fd, F_GETFL)) == -1)
395 {
396 error.SetErrorToErrno();
397 return false;
398 }
399
400 if (fcntl(fd, F_SETFL, status | flags) == -1)
401 {
402 error.SetErrorToErrno();
403 return false;
404 }
405
406 return true;
407}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000408
409//------------------------------------------------------------------------------
410/// @class Operation
411/// @brief Represents a ProcessMonitor operation.
412///
413/// Under Linux, it is not possible to ptrace() from any other thread but the
414/// one that spawned or attached to the process from the start. Therefore, when
415/// a ProcessMonitor is asked to deliver or change the state of an inferior
416/// process the operation must be "funneled" to a specific thread to perform the
417/// task. The Operation class provides an abstract base for all services the
418/// ProcessMonitor must perform via the single virtual function Execute, thus
419/// encapsulating the code that needs to run in the privileged context.
420class Operation
421{
422public:
Daniel Maleadd15b782013-05-13 17:32:07 +0000423 virtual ~Operation() {}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000424 virtual void Execute(ProcessMonitor *monitor) = 0;
425};
426
427//------------------------------------------------------------------------------
428/// @class ReadOperation
429/// @brief Implements ProcessMonitor::ReadMemory.
430class ReadOperation : public Operation
431{
432public:
433 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
434 Error &error, size_t &result)
435 : m_addr(addr), m_buff(buff), m_size(size),
436 m_error(error), m_result(result)
437 { }
438
439 void Execute(ProcessMonitor *monitor);
440
441private:
442 lldb::addr_t m_addr;
443 void *m_buff;
444 size_t m_size;
445 Error &m_error;
446 size_t &m_result;
447};
448
449void
450ReadOperation::Execute(ProcessMonitor *monitor)
451{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000452 lldb::pid_t pid = monitor->GetPID();
453
Greg Clayton542e4072012-09-07 17:49:29 +0000454 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000455}
456
457//------------------------------------------------------------------------------
Ed Mastea56115f2013-07-17 14:30:26 +0000458/// @class WriteOperation
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000459/// @brief Implements ProcessMonitor::WriteMemory.
460class WriteOperation : public Operation
461{
462public:
463 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
464 Error &error, size_t &result)
465 : m_addr(addr), m_buff(buff), m_size(size),
466 m_error(error), m_result(result)
467 { }
468
469 void Execute(ProcessMonitor *monitor);
470
471private:
472 lldb::addr_t m_addr;
473 const void *m_buff;
474 size_t m_size;
475 Error &m_error;
476 size_t &m_result;
477};
478
479void
480WriteOperation::Execute(ProcessMonitor *monitor)
481{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000482 lldb::pid_t pid = monitor->GetPID();
483
Greg Clayton542e4072012-09-07 17:49:29 +0000484 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000485}
486
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000487
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000488//------------------------------------------------------------------------------
489/// @class ReadRegOperation
490/// @brief Implements ProcessMonitor::ReadRegisterValue.
491class ReadRegOperation : public Operation
492{
493public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000494 ReadRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000495 RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000496 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000497 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000498 { }
499
500 void Execute(ProcessMonitor *monitor);
501
502private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000503 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000504 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000505 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000506 RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000507 bool &m_result;
508};
509
510void
511ReadRegOperation::Execute(ProcessMonitor *monitor)
512{
Todd Fiala49131cf2014-09-12 16:57:28 +0000513#if defined (__arm64__) || defined (__aarch64__)
514 if (m_offset > sizeof(struct user_pt_regs))
515 {
516 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
517 if (offset > sizeof(struct user_fpsimd_state))
518 {
519 m_result = false;
520 }
521 else
522 {
523 elf_fpregset_t regs;
524 int regset = NT_FPREGSET;
525 struct iovec ioVec;
526
527 ioVec.iov_base = &regs;
528 ioVec.iov_len = sizeof regs;
529 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
530 m_result = false;
531 else
532 {
533 m_result = true;
534 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, monitor->GetProcess().GetByteOrder());
535 }
536 }
537 }
538 else
539 {
540 elf_gregset_t regs;
541 int regset = NT_PRSTATUS;
542 struct iovec ioVec;
543
544 ioVec.iov_base = &regs;
545 ioVec.iov_len = sizeof regs;
546 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
547 m_result = false;
548 else
549 {
550 m_result = true;
551 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, monitor->GetProcess().GetByteOrder());
552 }
553 }
554#else
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000555 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000556
557 // Set errno to zero so that we can detect a failed peek.
558 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000559 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, NULL, 0);
560 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000561 m_result = false;
562 else
563 {
564 m_value = data;
565 m_result = true;
566 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000567 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000568 log->Printf ("ProcessMonitor::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000569 m_reg_name, data);
Todd Fiala49131cf2014-09-12 16:57:28 +0000570#endif
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000571}
572
573//------------------------------------------------------------------------------
574/// @class WriteRegOperation
575/// @brief Implements ProcessMonitor::WriteRegisterValue.
576class WriteRegOperation : public Operation
577{
578public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000579 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000580 const RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000581 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000582 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000583 { }
584
585 void Execute(ProcessMonitor *monitor);
586
587private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000588 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000589 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000590 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000591 const RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000592 bool &m_result;
593};
594
595void
596WriteRegOperation::Execute(ProcessMonitor *monitor)
597{
Todd Fiala49131cf2014-09-12 16:57:28 +0000598#if defined (__arm64__) || defined (__aarch64__)
599 if (m_offset > sizeof(struct user_pt_regs))
600 {
601 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
602 if (offset > sizeof(struct user_fpsimd_state))
603 {
604 m_result = false;
605 }
606 else
607 {
608 elf_fpregset_t regs;
609 int regset = NT_FPREGSET;
610 struct iovec ioVec;
611
612 ioVec.iov_base = &regs;
613 ioVec.iov_len = sizeof regs;
614 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
615 m_result = false;
616 else
617 {
618 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
619 if (PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
620 m_result = false;
621 else
622 m_result = true;
623 }
624 }
625 }
626 else
627 {
628 elf_gregset_t regs;
629 int regset = NT_PRSTATUS;
630 struct iovec ioVec;
631
632 ioVec.iov_base = &regs;
633 ioVec.iov_len = sizeof regs;
634 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
635 m_result = false;
636 else
637 {
638 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
639 if (PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
640 m_result = false;
641 else
642 m_result = true;
643 }
644 }
645#else
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000646 void* buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000647 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000648
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000649 buf = (void*) m_value.GetAsUInt64();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000650
651 if (log)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000652 log->Printf ("ProcessMonitor::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Matt Kopec7de48462013-03-06 17:20:48 +0000653 if (PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000654 m_result = false;
655 else
656 m_result = true;
Todd Fiala49131cf2014-09-12 16:57:28 +0000657#endif
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000658}
659
660//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000661/// @class ReadGPROperation
662/// @brief Implements ProcessMonitor::ReadGPR.
663class ReadGPROperation : public Operation
664{
665public:
Matt Kopec7de48462013-03-06 17:20:48 +0000666 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
667 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000668 { }
669
670 void Execute(ProcessMonitor *monitor);
671
672private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000673 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000674 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000675 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000676 bool &m_result;
677};
678
679void
680ReadGPROperation::Execute(ProcessMonitor *monitor)
681{
Todd Fiala6ac1be42014-08-21 16:34:03 +0000682#if defined (__arm64__) || defined (__aarch64__)
683 int regset = NT_PRSTATUS;
684 struct iovec ioVec;
685
686 ioVec.iov_base = m_buf;
687 ioVec.iov_len = m_buf_size;
688 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000689 m_result = false;
690 else
691 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000692#else
Todd Fiala6ac1be42014-08-21 16:34:03 +0000693 if (PTRACE(PTRACE_GETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
694 m_result = false;
695 else
696 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000697#endif
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000698}
699
700//------------------------------------------------------------------------------
701/// @class ReadFPROperation
702/// @brief Implements ProcessMonitor::ReadFPR.
703class ReadFPROperation : public Operation
704{
705public:
Matt Kopec7de48462013-03-06 17:20:48 +0000706 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
707 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000708 { }
709
710 void Execute(ProcessMonitor *monitor);
711
712private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000713 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000714 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000715 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000716 bool &m_result;
717};
718
719void
720ReadFPROperation::Execute(ProcessMonitor *monitor)
721{
Todd Fiala6ac1be42014-08-21 16:34:03 +0000722#if defined (__arm64__) || defined (__aarch64__)
723 int regset = NT_FPREGSET;
724 struct iovec ioVec;
725
726 ioVec.iov_base = m_buf;
727 ioVec.iov_len = m_buf_size;
728 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000729 m_result = false;
730 else
731 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000732#else
Todd Fiala6ac1be42014-08-21 16:34:03 +0000733 if (PTRACE(PTRACE_GETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
734 m_result = false;
735 else
736 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000737#endif
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000738}
739
740//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000741/// @class ReadRegisterSetOperation
742/// @brief Implements ProcessMonitor::ReadRegisterSet.
743class ReadRegisterSetOperation : public Operation
744{
745public:
746 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
747 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
748 { }
749
750 void Execute(ProcessMonitor *monitor);
751
752private:
753 lldb::tid_t m_tid;
754 void *m_buf;
755 size_t m_buf_size;
756 const unsigned int m_regset;
757 bool &m_result;
758};
759
760void
761ReadRegisterSetOperation::Execute(ProcessMonitor *monitor)
762{
763 if (PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
764 m_result = false;
765 else
766 m_result = true;
767}
768
769//------------------------------------------------------------------------------
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000770/// @class WriteGPROperation
771/// @brief Implements ProcessMonitor::WriteGPR.
772class WriteGPROperation : public Operation
773{
774public:
Matt Kopec7de48462013-03-06 17:20:48 +0000775 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
776 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000777 { }
778
779 void Execute(ProcessMonitor *monitor);
780
781private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000782 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000783 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000784 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000785 bool &m_result;
786};
787
788void
789WriteGPROperation::Execute(ProcessMonitor *monitor)
790{
Todd Fiala6ac1be42014-08-21 16:34:03 +0000791#if defined (__arm64__) || defined (__aarch64__)
792 int regset = NT_PRSTATUS;
793 struct iovec ioVec;
794
795 ioVec.iov_base = m_buf;
796 ioVec.iov_len = m_buf_size;
797 if (PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000798 m_result = false;
799 else
800 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000801#else
Todd Fiala6ac1be42014-08-21 16:34:03 +0000802 if (PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
803 m_result = false;
804 else
805 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000806#endif
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000807}
808
809//------------------------------------------------------------------------------
810/// @class WriteFPROperation
811/// @brief Implements ProcessMonitor::WriteFPR.
812class WriteFPROperation : public Operation
813{
814public:
Matt Kopec7de48462013-03-06 17:20:48 +0000815 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
816 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000817 { }
818
819 void Execute(ProcessMonitor *monitor);
820
821private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000822 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000823 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000824 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000825 bool &m_result;
826};
827
828void
829WriteFPROperation::Execute(ProcessMonitor *monitor)
830{
Todd Fiala6ac1be42014-08-21 16:34:03 +0000831#if defined (__arm64__) || defined (__aarch64__)
832 int regset = NT_FPREGSET;
833 struct iovec ioVec;
834
835 ioVec.iov_base = m_buf;
836 ioVec.iov_len = m_buf_size;
837 if (PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000838 m_result = false;
839 else
840 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000841#else
Todd Fiala6ac1be42014-08-21 16:34:03 +0000842 if (PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
843 m_result = false;
844 else
845 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000846#endif
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000847}
848
849//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000850/// @class WriteRegisterSetOperation
851/// @brief Implements ProcessMonitor::WriteRegisterSet.
852class WriteRegisterSetOperation : public Operation
853{
854public:
855 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
856 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
857 { }
858
859 void Execute(ProcessMonitor *monitor);
860
861private:
862 lldb::tid_t m_tid;
863 void *m_buf;
864 size_t m_buf_size;
865 const unsigned int m_regset;
866 bool &m_result;
867};
868
869void
870WriteRegisterSetOperation::Execute(ProcessMonitor *monitor)
871{
872 if (PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
873 m_result = false;
874 else
875 m_result = true;
876}
877
878//------------------------------------------------------------------------------
Richard Mitton0a558352013-10-17 21:14:00 +0000879/// @class ReadThreadPointerOperation
880/// @brief Implements ProcessMonitor::ReadThreadPointer.
881class ReadThreadPointerOperation : public Operation
882{
883public:
884 ReadThreadPointerOperation(lldb::tid_t tid, lldb::addr_t *addr, bool &result)
885 : m_tid(tid), m_addr(addr), m_result(result)
886 { }
887
888 void Execute(ProcessMonitor *monitor);
889
890private:
891 lldb::tid_t m_tid;
892 lldb::addr_t *m_addr;
893 bool &m_result;
894};
895
896void
897ReadThreadPointerOperation::Execute(ProcessMonitor *monitor)
898{
899 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
900 if (log)
901 log->Printf ("ProcessMonitor::%s()", __FUNCTION__);
902
903 // The process for getting the thread area on Linux is
904 // somewhat... obscure. There's several different ways depending on
905 // what arch you're on, and what kernel version you have.
906
907 const ArchSpec& arch = monitor->GetProcess().GetTarget().GetArchitecture();
908 switch(arch.GetMachine())
909 {
Todd Fiala42079682014-08-27 16:05:26 +0000910 case llvm::Triple::aarch64:
911 {
Todd Fialadbec1ff2014-09-04 16:08:20 +0000912 int regset = LLDB_PTRACE_NT_ARM_TLS;
Todd Fiala42079682014-08-27 16:05:26 +0000913 struct iovec ioVec;
914
915 ioVec.iov_base = m_addr;
916 ioVec.iov_len = sizeof(lldb::addr_t);
917 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, ioVec.iov_len) < 0)
918 m_result = false;
919 else
920 m_result = true;
921 break;
922 }
Todd Fiala720cd3f2014-06-16 14:49:28 +0000923#if defined(__i386__) || defined(__x86_64__)
924 // Note that struct user below has a field named i387 which is x86-specific.
925 // Therefore, this case should be compiled only for x86-based systems.
Richard Mitton0a558352013-10-17 21:14:00 +0000926 case llvm::Triple::x86:
927 {
928 // Find the GS register location for our host architecture.
929 size_t gs_user_offset = offsetof(struct user, regs);
930#ifdef __x86_64__
931 gs_user_offset += offsetof(struct user_regs_struct, gs);
932#endif
933#ifdef __i386__
934 gs_user_offset += offsetof(struct user_regs_struct, xgs);
935#endif
936
937 // Read the GS register value to get the selector.
938 errno = 0;
939 long gs = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)gs_user_offset, NULL, 0);
940 if (errno)
941 {
942 m_result = false;
943 break;
944 }
945
946 // Read the LDT base for that selector.
947 uint32_t tmp[4];
948 m_result = (PTRACE(PTRACE_GET_THREAD_AREA, m_tid, (void *)(gs >> 3), &tmp, 0) == 0);
949 *m_addr = tmp[1];
950 break;
951 }
Todd Fiala720cd3f2014-06-16 14:49:28 +0000952#endif
Richard Mitton0a558352013-10-17 21:14:00 +0000953 case llvm::Triple::x86_64:
954 // Read the FS register base.
955 m_result = (PTRACE(PTRACE_ARCH_PRCTL, m_tid, m_addr, (void *)ARCH_GET_FS, 0) == 0);
956 break;
957 default:
958 m_result = false;
959 break;
960 }
961}
962
963//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000964/// @class ResumeOperation
965/// @brief Implements ProcessMonitor::Resume.
966class ResumeOperation : public Operation
967{
968public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000969 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
970 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000971
972 void Execute(ProcessMonitor *monitor);
973
974private:
975 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000976 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000977 bool &m_result;
978};
979
980void
981ResumeOperation::Execute(ProcessMonitor *monitor)
982{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000983 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000984
985 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
986 data = m_signo;
987
Matt Kopec7de48462013-03-06 17:20:48 +0000988 if (PTRACE(PTRACE_CONT, m_tid, NULL, (void*)data, 0))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000989 {
990 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
991
992 if (log)
993 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, strerror(errno));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000994 m_result = false;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000995 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000996 else
997 m_result = true;
998}
999
1000//------------------------------------------------------------------------------
Ed Maste428a6782013-06-24 15:04:47 +00001001/// @class SingleStepOperation
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001002/// @brief Implements ProcessMonitor::SingleStep.
1003class SingleStepOperation : public Operation
1004{
1005public:
Stephen Wilson84ffe702011-03-30 15:55:52 +00001006 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
1007 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001008
1009 void Execute(ProcessMonitor *monitor);
1010
1011private:
1012 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001013 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001014 bool &m_result;
1015};
1016
1017void
1018SingleStepOperation::Execute(ProcessMonitor *monitor)
1019{
Daniel Maleaa85e6b62012-12-07 22:21:08 +00001020 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001021
1022 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
1023 data = m_signo;
1024
Matt Kopec7de48462013-03-06 17:20:48 +00001025 if (PTRACE(PTRACE_SINGLESTEP, m_tid, NULL, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001026 m_result = false;
1027 else
1028 m_result = true;
1029}
1030
1031//------------------------------------------------------------------------------
1032/// @class SiginfoOperation
1033/// @brief Implements ProcessMonitor::GetSignalInfo.
1034class SiginfoOperation : public Operation
1035{
1036public:
Daniel Maleaa35970a2012-11-23 18:09:58 +00001037 SiginfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
1038 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001039
1040 void Execute(ProcessMonitor *monitor);
1041
1042private:
1043 lldb::tid_t m_tid;
1044 void *m_info;
1045 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001046 int &m_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001047};
1048
1049void
1050SiginfoOperation::Execute(ProcessMonitor *monitor)
1051{
Matt Kopec7de48462013-03-06 17:20:48 +00001052 if (PTRACE(PTRACE_GETSIGINFO, m_tid, NULL, m_info, 0)) {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001053 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001054 m_err = errno;
1055 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001056 else
1057 m_result = true;
1058}
1059
1060//------------------------------------------------------------------------------
1061/// @class EventMessageOperation
1062/// @brief Implements ProcessMonitor::GetEventMessage.
1063class EventMessageOperation : public Operation
1064{
1065public:
1066 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
1067 : m_tid(tid), m_message(message), m_result(result) { }
1068
1069 void Execute(ProcessMonitor *monitor);
1070
1071private:
1072 lldb::tid_t m_tid;
1073 unsigned long *m_message;
1074 bool &m_result;
1075};
1076
1077void
1078EventMessageOperation::Execute(ProcessMonitor *monitor)
1079{
Matt Kopec7de48462013-03-06 17:20:48 +00001080 if (PTRACE(PTRACE_GETEVENTMSG, m_tid, NULL, m_message, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001081 m_result = false;
1082 else
1083 m_result = true;
1084}
1085
1086//------------------------------------------------------------------------------
Ed Maste263c9282014-03-17 17:45:53 +00001087/// @class DetachOperation
1088/// @brief Implements ProcessMonitor::Detach.
Greg Clayton28041352011-11-29 20:50:10 +00001089class DetachOperation : public Operation
1090{
1091public:
Matt Kopec085d6ce2013-05-31 22:00:07 +00001092 DetachOperation(lldb::tid_t tid, Error &result) : m_tid(tid), m_error(result) { }
Greg Clayton28041352011-11-29 20:50:10 +00001093
1094 void Execute(ProcessMonitor *monitor);
1095
1096private:
Matt Kopec085d6ce2013-05-31 22:00:07 +00001097 lldb::tid_t m_tid;
Greg Clayton28041352011-11-29 20:50:10 +00001098 Error &m_error;
1099};
1100
1101void
1102DetachOperation::Execute(ProcessMonitor *monitor)
1103{
Matt Kopec085d6ce2013-05-31 22:00:07 +00001104 if (ptrace(PT_DETACH, m_tid, NULL, 0) < 0)
Greg Clayton28041352011-11-29 20:50:10 +00001105 m_error.SetErrorToErrno();
Greg Clayton28041352011-11-29 20:50:10 +00001106}
1107
Johnny Chen25e68e32011-06-14 19:19:50 +00001108ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
1109 : m_monitor(monitor)
1110{
1111 sem_init(&m_semaphore, 0, 0);
1112}
1113
1114ProcessMonitor::OperationArgs::~OperationArgs()
1115{
1116 sem_destroy(&m_semaphore);
1117}
1118
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001119ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
1120 lldb_private::Module *module,
1121 char const **argv,
1122 char const **envp,
1123 const char *stdin_path,
1124 const char *stdout_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001125 const char *stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001126 const char *working_dir,
1127 const lldb_private::ProcessLaunchInfo &launch_info)
Johnny Chen25e68e32011-06-14 19:19:50 +00001128 : OperationArgs(monitor),
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001129 m_module(module),
1130 m_argv(argv),
1131 m_envp(envp),
1132 m_stdin_path(stdin_path),
1133 m_stdout_path(stdout_path),
Daniel Malea6217d2a2013-01-08 14:49:22 +00001134 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001135 m_working_dir(working_dir),
1136 m_launch_info(launch_info)
1137{
1138}
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001139
1140ProcessMonitor::LaunchArgs::~LaunchArgs()
Johnny Chen25e68e32011-06-14 19:19:50 +00001141{ }
1142
1143ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
1144 lldb::pid_t pid)
1145 : OperationArgs(monitor), m_pid(pid) { }
1146
1147ProcessMonitor::AttachArgs::~AttachArgs()
1148{ }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001149
1150//------------------------------------------------------------------------------
1151/// The basic design of the ProcessMonitor is built around two threads.
1152///
1153/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
1154/// for changes in the debugee state. When a change is detected a
1155/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
1156/// "drives" state changes in the debugger.
1157///
1158/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +00001159/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001160/// operations such as register reads/writes, stepping, etc. See the comments
1161/// on the Operation class for more info as to why this is needed.
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001162ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001163 Module *module,
1164 const char *argv[],
1165 const char *envp[],
1166 const char *stdin_path,
1167 const char *stdout_path,
1168 const char *stderr_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001169 const char *working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001170 const lldb_private::ProcessLaunchInfo &launch_info,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001171 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001172 : m_process(static_cast<ProcessLinux *>(process)),
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001173 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +00001174 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001175 m_pid(LLDB_INVALID_PROCESS_ID),
1176 m_terminal_fd(-1),
Daniel Malea1efb4182013-09-16 23:12:18 +00001177 m_operation(0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001178{
Daniel Malea1efb4182013-09-16 23:12:18 +00001179 std::unique_ptr<LaunchArgs> args(new LaunchArgs(this, module, argv, envp,
1180 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001181 working_dir, launch_info));
Stephen Wilson57740ec2011-01-15 00:12:41 +00001182
Daniel Malea1efb4182013-09-16 23:12:18 +00001183 sem_init(&m_operation_pending, 0, 0);
1184 sem_init(&m_operation_done, 0, 0);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001185
Johnny Chen25e68e32011-06-14 19:19:50 +00001186 StartLaunchOpThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001187 if (!error.Success())
1188 return;
1189
1190WAIT_AGAIN:
1191 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +00001192 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001193 {
1194 if (errno == EINTR)
1195 goto WAIT_AGAIN;
1196 else
1197 {
1198 error.SetErrorToErrno();
1199 return;
1200 }
1201 }
1202
1203 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +00001204 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001205 {
Greg Clayton743ecf42012-10-16 20:20:18 +00001206 StopOpThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +00001207 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001208 return;
1209 }
1210
1211 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +00001212 m_monitor_thread = Host::StartMonitoringChildProcess(
1213 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001214 if (!m_monitor_thread.IsJoinable())
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001215 {
1216 error.SetErrorToGenericError();
1217 error.SetErrorString("Process launch failed.");
1218 return;
1219 }
1220}
1221
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001222ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen25e68e32011-06-14 19:19:50 +00001223 lldb::pid_t pid,
1224 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001225 : m_process(static_cast<ProcessLinux *>(process)),
Johnny Chen25e68e32011-06-14 19:19:50 +00001226 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +00001227 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Johnny Chen25e68e32011-06-14 19:19:50 +00001228 m_pid(LLDB_INVALID_PROCESS_ID),
1229 m_terminal_fd(-1),
Daniel Malea1efb4182013-09-16 23:12:18 +00001230 m_operation(0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001231{
Daniel Malea1efb4182013-09-16 23:12:18 +00001232 sem_init(&m_operation_pending, 0, 0);
1233 sem_init(&m_operation_done, 0, 0);
Johnny Chen25e68e32011-06-14 19:19:50 +00001234
Daniel Malea1efb4182013-09-16 23:12:18 +00001235 std::unique_ptr<AttachArgs> args(new AttachArgs(this, pid));
Johnny Chen25e68e32011-06-14 19:19:50 +00001236
1237 StartAttachOpThread(args.get(), error);
1238 if (!error.Success())
1239 return;
1240
1241WAIT_AGAIN:
1242 // Wait for the operation thread to initialize.
1243 if (sem_wait(&args->m_semaphore))
1244 {
1245 if (errno == EINTR)
1246 goto WAIT_AGAIN;
1247 else
1248 {
1249 error.SetErrorToErrno();
1250 return;
1251 }
1252 }
1253
Greg Clayton743ecf42012-10-16 20:20:18 +00001254 // Check that the attach was a success.
Johnny Chen25e68e32011-06-14 19:19:50 +00001255 if (!args->m_error.Success())
1256 {
Greg Clayton743ecf42012-10-16 20:20:18 +00001257 StopOpThread();
Johnny Chen25e68e32011-06-14 19:19:50 +00001258 error = args->m_error;
1259 return;
1260 }
1261
1262 // Finally, start monitoring the child process for change in state.
1263 m_monitor_thread = Host::StartMonitoringChildProcess(
1264 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001265 if (!m_monitor_thread.IsJoinable())
Johnny Chen25e68e32011-06-14 19:19:50 +00001266 {
1267 error.SetErrorToGenericError();
1268 error.SetErrorString("Process attach failed.");
1269 return;
1270 }
1271}
1272
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001273ProcessMonitor::~ProcessMonitor()
1274{
Stephen Wilson84ffe702011-03-30 15:55:52 +00001275 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001276}
1277
1278//------------------------------------------------------------------------------
1279// Thread setup and tear down.
1280void
Johnny Chen25e68e32011-06-14 19:19:50 +00001281ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001282{
1283 static const char *g_thread_name = "lldb.process.linux.operation";
1284
Zachary Turneracee96a2014-09-23 18:32:09 +00001285 if (m_operation_thread.IsJoinable())
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001286 return;
1287
Zachary Turner39de3112014-09-09 20:54:56 +00001288 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001289}
1290
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001291void *
Johnny Chen25e68e32011-06-14 19:19:50 +00001292ProcessMonitor::LaunchOpThread(void *arg)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001293{
1294 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1295
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001296 if (!Launch(args)) {
1297 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001298 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001299 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001300
Stephen Wilson570243b2011-01-19 01:37:06 +00001301 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001302 return NULL;
1303}
1304
1305bool
1306ProcessMonitor::Launch(LaunchArgs *args)
1307{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001308 assert (args && "null args");
1309 if (!args)
1310 return false;
1311
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001312 ProcessMonitor *monitor = args->m_monitor;
1313 ProcessLinux &process = monitor->GetProcess();
1314 const char **argv = args->m_argv;
1315 const char **envp = args->m_envp;
1316 const char *stdin_path = args->m_stdin_path;
1317 const char *stdout_path = args->m_stdout_path;
1318 const char *stderr_path = args->m_stderr_path;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001319 const char *working_dir = args->m_working_dir;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001320
1321 lldb_utility::PseudoTerminal terminal;
1322 const size_t err_len = 1024;
1323 char err_str[err_len];
1324 lldb::pid_t pid;
1325
1326 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001327 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001328
Stephen Wilson57740ec2011-01-15 00:12:41 +00001329 // Propagate the environment if one is not supplied.
1330 if (envp == NULL || envp[0] == NULL)
1331 envp = const_cast<const char **>(environ);
1332
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001333 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t>(-1))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001334 {
1335 args->m_error.SetErrorToGenericError();
1336 args->m_error.SetErrorString("Process fork failed.");
1337 goto FINISH;
1338 }
1339
Peter Collingbourne6a520222011-06-14 03:55:58 +00001340 // Recognized child exit status codes.
1341 enum {
1342 ePtraceFailed = 1,
1343 eDupStdinFailed,
1344 eDupStdoutFailed,
1345 eDupStderrFailed,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001346 eChdirFailed,
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001347 eExecFailed,
1348 eSetGidFailed
Peter Collingbourne6a520222011-06-14 03:55:58 +00001349 };
1350
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001351 // Child process.
1352 if (pid == 0)
1353 {
1354 // Trace this process.
Matt Kopec7de48462013-03-06 17:20:48 +00001355 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL, 0) < 0)
Peter Collingbourne6a520222011-06-14 03:55:58 +00001356 exit(ePtraceFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001357
1358 // Do not inherit setgid powers.
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001359 if (setgid(getgid()) != 0)
1360 exit(eSetGidFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001361
1362 // Let us have our own process group.
1363 setpgid(0, 0);
1364
Greg Clayton710dd5a2011-01-08 20:28:42 +00001365 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001366 //
1367 // FIXME: If two or more of the paths are the same we needlessly open
1368 // the same file multiple times.
1369 if (stdin_path != NULL && stdin_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001370 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001371 exit(eDupStdinFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001372
1373 if (stdout_path != NULL && stdout_path[0])
1374 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001375 exit(eDupStdoutFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001376
1377 if (stderr_path != NULL && stderr_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001378 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001379 exit(eDupStderrFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001380
Daniel Malea6217d2a2013-01-08 14:49:22 +00001381 // Change working directory
1382 if (working_dir != NULL && working_dir[0])
1383 if (0 != ::chdir(working_dir))
1384 exit(eChdirFailed);
1385
Todd Fiala0bce1b62014-08-17 00:10:50 +00001386 // Disable ASLR if requested.
1387 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1388 {
1389 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1390 if (old_personality == -1)
1391 {
1392 if (log)
1393 log->Printf ("ProcessMonitor::%s retrieval of Linux personality () failed: %s. Cannot disable ASLR.", __FUNCTION__, strerror (errno));
1394 }
1395 else
1396 {
1397 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1398 if (new_personality == -1)
1399 {
1400 if (log)
1401 log->Printf ("ProcessMonitor::%s setting of Linux personality () to disable ASLR failed, ignoring: %s", __FUNCTION__, strerror (errno));
1402
1403 }
1404 else
1405 {
1406 if (log)
Todd Fiala850f9a22014-09-19 18:27:45 +00001407 log->Printf ("ProcessMonitor::%s disabling ASLR: SUCCESS", __FUNCTION__);
Todd Fiala0bce1b62014-08-17 00:10:50 +00001408
1409 }
1410 }
1411 }
1412
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001413 // Execute. We should never return.
1414 execve(argv[0],
1415 const_cast<char *const *>(argv),
1416 const_cast<char *const *>(envp));
Peter Collingbourne6a520222011-06-14 03:55:58 +00001417 exit(eExecFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001418 }
1419
1420 // Wait for the child process to to trap on its call to execve.
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001421 lldb::pid_t wpid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001422 ::pid_t raw_pid;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001423 int status;
Todd Fialaaf245d12014-06-30 21:05:18 +00001424
1425 raw_pid = waitpid(pid, &status, 0);
1426 wpid = static_cast <lldb::pid_t> (raw_pid);
1427 if (raw_pid < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001428 {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001429 args->m_error.SetErrorToErrno();
1430 goto FINISH;
1431 }
Peter Collingbourne6a520222011-06-14 03:55:58 +00001432 else if (WIFEXITED(status))
1433 {
1434 // open, dup or execve likely failed for some reason.
1435 args->m_error.SetErrorToGenericError();
1436 switch (WEXITSTATUS(status))
1437 {
Greg Clayton542e4072012-09-07 17:49:29 +00001438 case ePtraceFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001439 args->m_error.SetErrorString("Child ptrace failed.");
1440 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001441 case eDupStdinFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001442 args->m_error.SetErrorString("Child open stdin failed.");
1443 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001444 case eDupStdoutFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001445 args->m_error.SetErrorString("Child open stdout failed.");
1446 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001447 case eDupStderrFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001448 args->m_error.SetErrorString("Child open stderr failed.");
1449 break;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001450 case eChdirFailed:
1451 args->m_error.SetErrorString("Child failed to set working directory.");
1452 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001453 case eExecFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001454 args->m_error.SetErrorString("Child exec failed.");
1455 break;
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001456 case eSetGidFailed:
1457 args->m_error.SetErrorString("Child setgid failed.");
1458 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001459 default:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001460 args->m_error.SetErrorString("Child returned unknown exit status.");
1461 break;
1462 }
1463 goto FINISH;
1464 }
1465 assert(WIFSTOPPED(status) && wpid == pid &&
1466 "Could not sync with inferior process.");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001467
Matt Kopec085d6ce2013-05-31 22:00:07 +00001468 if (!SetDefaultPtraceOpts(pid))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001469 {
1470 args->m_error.SetErrorToErrno();
1471 goto FINISH;
1472 }
1473
1474 // Release the master terminal descriptor and pass it off to the
1475 // ProcessMonitor instance. Similarly stash the inferior pid.
1476 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1477 monitor->m_pid = pid;
1478
Stephen Wilson26977162011-03-23 02:14:42 +00001479 // Set the terminal fd to be in non blocking mode (it simplifies the
1480 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1481 // descriptor to read from).
1482 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1483 goto FINISH;
1484
Johnny Chen30213ff2012-01-05 19:17:38 +00001485 // Update the process thread list with this new thread.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001486 // FIXME: should we be letting UpdateThreadList handle this?
1487 // FIXME: by using pids instead of tids, we can only support one thread.
Michael Sartain9f822cd2013-07-31 23:27:46 +00001488 inferior.reset(process.CreateNewPOSIXThread(process, pid));
Matt Kopecfb6ab542013-07-10 20:53:11 +00001489
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001490 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001491 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001492 process.GetThreadList().AddThread(inferior);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001493
Matt Kopecb2910442013-07-09 15:09:45 +00001494 process.AddThreadForInitialStopIfNeeded(pid);
1495
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001496 // Let our process instance know the thread has stopped.
1497 process.SendMessage(ProcessMessage::Trace(pid));
1498
1499FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001500 return args->m_error.Success();
1501}
1502
Johnny Chen25e68e32011-06-14 19:19:50 +00001503void
1504ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1505{
1506 static const char *g_thread_name = "lldb.process.linux.operation";
1507
Zachary Turneracee96a2014-09-23 18:32:09 +00001508 if (m_operation_thread.IsJoinable())
Johnny Chen25e68e32011-06-14 19:19:50 +00001509 return;
1510
Zachary Turner39de3112014-09-09 20:54:56 +00001511 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
Johnny Chen25e68e32011-06-14 19:19:50 +00001512}
1513
Johnny Chen25e68e32011-06-14 19:19:50 +00001514void *
1515ProcessMonitor::AttachOpThread(void *arg)
1516{
1517 AttachArgs *args = static_cast<AttachArgs*>(arg);
1518
Greg Clayton743ecf42012-10-16 20:20:18 +00001519 if (!Attach(args)) {
1520 sem_post(&args->m_semaphore);
Johnny Chen25e68e32011-06-14 19:19:50 +00001521 return NULL;
Greg Clayton743ecf42012-10-16 20:20:18 +00001522 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001523
1524 ServeOperation(args);
1525 return NULL;
1526}
1527
1528bool
1529ProcessMonitor::Attach(AttachArgs *args)
1530{
1531 lldb::pid_t pid = args->m_pid;
1532
1533 ProcessMonitor *monitor = args->m_monitor;
1534 ProcessLinux &process = monitor->GetProcess();
Johnny Chen25e68e32011-06-14 19:19:50 +00001535 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001536 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen25e68e32011-06-14 19:19:50 +00001537
Matt Kopec085d6ce2013-05-31 22:00:07 +00001538 // Use a map to keep track of the threads which we have attached/need to attach.
1539 Host::TidMap tids_to_attach;
Johnny Chen25e68e32011-06-14 19:19:50 +00001540 if (pid <= 1)
1541 {
1542 args->m_error.SetErrorToGenericError();
1543 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1544 goto FINISH;
1545 }
1546
Matt Kopec085d6ce2013-05-31 22:00:07 +00001547 while (Host::FindProcessThreads(pid, tids_to_attach))
Johnny Chen25e68e32011-06-14 19:19:50 +00001548 {
Matt Kopec085d6ce2013-05-31 22:00:07 +00001549 for (Host::TidMap::iterator it = tids_to_attach.begin();
1550 it != tids_to_attach.end(); ++it)
1551 {
1552 if (it->second == false)
1553 {
1554 lldb::tid_t tid = it->first;
1555
1556 // Attach to the requested process.
1557 // An attach will cause the thread to stop with a SIGSTOP.
1558 if (PTRACE(PTRACE_ATTACH, tid, NULL, NULL, 0) < 0)
1559 {
1560 // No such thread. The thread may have exited.
1561 // More error handling may be needed.
1562 if (errno == ESRCH)
1563 {
1564 tids_to_attach.erase(it);
1565 continue;
1566 }
1567 else
1568 {
1569 args->m_error.SetErrorToErrno();
1570 goto FINISH;
1571 }
1572 }
1573
Todd Fiala9be50492014-07-01 16:30:53 +00001574 ::pid_t wpid;
Matt Kopec085d6ce2013-05-31 22:00:07 +00001575 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1576 // At this point we should have a thread stopped if waitpid succeeds.
Todd Fiala9be50492014-07-01 16:30:53 +00001577 if ((wpid = waitpid(tid, NULL, __WALL)) < 0)
Matt Kopec085d6ce2013-05-31 22:00:07 +00001578 {
1579 // No such thread. The thread may have exited.
1580 // More error handling may be needed.
1581 if (errno == ESRCH)
1582 {
1583 tids_to_attach.erase(it);
1584 continue;
1585 }
1586 else
1587 {
1588 args->m_error.SetErrorToErrno();
1589 goto FINISH;
1590 }
1591 }
1592
1593 if (!SetDefaultPtraceOpts(tid))
1594 {
1595 args->m_error.SetErrorToErrno();
1596 goto FINISH;
1597 }
1598
1599 // Update the process thread list with the attached thread.
Michael Sartain9f822cd2013-07-31 23:27:46 +00001600 inferior.reset(process.CreateNewPOSIXThread(process, tid));
Matt Kopecfb6ab542013-07-10 20:53:11 +00001601
Matt Kopec085d6ce2013-05-31 22:00:07 +00001602 if (log)
1603 log->Printf ("ProcessMonitor::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1604 process.GetThreadList().AddThread(inferior);
1605 it->second = true;
Matt Kopecb2910442013-07-09 15:09:45 +00001606 process.AddThreadForInitialStopIfNeeded(tid);
Matt Kopec085d6ce2013-05-31 22:00:07 +00001607 }
1608 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001609 }
1610
Matt Kopec085d6ce2013-05-31 22:00:07 +00001611 if (tids_to_attach.size() > 0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001612 {
Matt Kopec085d6ce2013-05-31 22:00:07 +00001613 monitor->m_pid = pid;
1614 // Let our process instance know the thread has stopped.
1615 process.SendMessage(ProcessMessage::Trace(pid));
Johnny Chen25e68e32011-06-14 19:19:50 +00001616 }
Matt Kopec085d6ce2013-05-31 22:00:07 +00001617 else
1618 {
1619 args->m_error.SetErrorToGenericError();
1620 args->m_error.SetErrorString("No such process.");
1621 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001622
1623 FINISH:
1624 return args->m_error.Success();
1625}
1626
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001627bool
Matt Kopec085d6ce2013-05-31 22:00:07 +00001628ProcessMonitor::SetDefaultPtraceOpts(lldb::pid_t pid)
1629{
1630 long ptrace_opts = 0;
1631
1632 // Have the child raise an event on exit. This is used to keep the child in
1633 // limbo until it is destroyed.
1634 ptrace_opts |= PTRACE_O_TRACEEXIT;
1635
1636 // Have the tracer trace threads which spawn in the inferior process.
1637 // TODO: if we want to support tracing the inferiors' child, add the
1638 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1639 ptrace_opts |= PTRACE_O_TRACECLONE;
1640
1641 // Have the tracer notify us before execve returns
1642 // (needed to disable legacy SIGTRAP generation)
1643 ptrace_opts |= PTRACE_O_TRACEEXEC;
1644
1645 return PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)ptrace_opts, 0) >= 0;
1646}
1647
1648bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001649ProcessMonitor::MonitorCallback(void *callback_baton,
1650 lldb::pid_t pid,
Peter Collingbourne2c67b9a2011-11-21 00:10:19 +00001651 bool exited,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001652 int signal,
1653 int status)
1654{
1655 ProcessMessage message;
1656 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001657 ProcessLinux *process = monitor->m_process;
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001658 assert(process);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001659 bool stop_monitoring;
1660 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001661 int ptrace_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001662
Andrew Kaylor93132f52013-05-28 23:04:25 +00001663 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1664
1665 if (exited)
1666 {
1667 if (log)
1668 log->Printf ("ProcessMonitor::%s() got exit signal, tid = %" PRIu64, __FUNCTION__, pid);
1669 message = ProcessMessage::Exit(pid, status);
1670 process->SendMessage(message);
1671 return pid == process->GetID();
1672 }
1673
Daniel Maleaa35970a2012-11-23 18:09:58 +00001674 if (!monitor->GetSignalInfo(pid, &info, ptrace_err)) {
1675 if (ptrace_err == EINVAL) {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001676 if (log)
1677 log->Printf ("ProcessMonitor::%s() resuming from group-stop", __FUNCTION__);
Daniel Maleaa35970a2012-11-23 18:09:58 +00001678 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1679 if (!monitor->Resume(pid, SIGSTOP)) {
1680 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1681 }
1682 stop_monitoring = false;
1683 } else {
1684 // ptrace(GETSIGINFO) failed (but not due to group-stop). Most likely,
1685 // this means the child pid is gone (or not being debugged) therefore
Andrew Kaylor93132f52013-05-28 23:04:25 +00001686 // stop the monitor thread if this is the main pid.
1687 if (log)
1688 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d",
1689 __FUNCTION__, strerror(ptrace_err), pid, signal, status);
1690 stop_monitoring = pid == monitor->m_process->GetID();
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +00001691 // If we are going to stop monitoring, we need to notify our process object
1692 if (stop_monitoring)
1693 {
1694 message = ProcessMessage::Exit(pid, status);
1695 process->SendMessage(message);
1696 }
Daniel Maleaa35970a2012-11-23 18:09:58 +00001697 }
1698 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00001699 else {
1700 switch (info.si_signo)
1701 {
1702 case SIGTRAP:
1703 message = MonitorSIGTRAP(monitor, &info, pid);
1704 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001705
Stephen Wilson84ffe702011-03-30 15:55:52 +00001706 default:
1707 message = MonitorSignal(monitor, &info, pid);
1708 break;
1709 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001710
Stephen Wilson84ffe702011-03-30 15:55:52 +00001711 process->SendMessage(message);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001712 stop_monitoring = false;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001713 }
1714
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001715 return stop_monitoring;
1716}
1717
1718ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +00001719ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001720 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001721{
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001722 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001723
Andrew Kaylor93132f52013-05-28 23:04:25 +00001724 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1725
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001726 assert(monitor);
1727 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001728
Stephen Wilson84ffe702011-03-30 15:55:52 +00001729 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001730 {
1731 default:
1732 assert(false && "Unexpected SIGTRAP code!");
1733 break;
1734
Matt Kopeca360d7e2013-05-17 19:27:47 +00001735 // TODO: these two cases are required if we want to support tracing
1736 // of the inferiors' children
1737 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1738 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1739
Matt Kopec650648f2013-01-08 16:30:18 +00001740 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1741 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001742 if (log)
1743 log->Printf ("ProcessMonitor::%s() received thread creation event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
1744
Matt Kopec650648f2013-01-08 16:30:18 +00001745 unsigned long tid = 0;
1746 if (!monitor->GetEventMessage(pid, &tid))
1747 tid = -1;
1748 message = ProcessMessage::NewThread(pid, tid);
1749 break;
1750 }
1751
Matt Kopeca360d7e2013-05-17 19:27:47 +00001752 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Matt Kopec718be872013-10-09 19:39:55 +00001753 if (log)
1754 log->Printf ("ProcessMonitor::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
1755
1756 message = ProcessMessage::Exec(pid);
Matt Kopeca360d7e2013-05-17 19:27:47 +00001757 break;
1758
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001759 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1760 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001761 // The inferior process or one of its threads is about to exit.
1762 // Maintain the process or thread in a state of "limbo" until we are
1763 // explicitly commanded to detach, destroy, resume, etc.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001764 unsigned long data = 0;
1765 if (!monitor->GetEventMessage(pid, &data))
1766 data = -1;
Andrew Kaylor93132f52013-05-28 23:04:25 +00001767 if (log)
Matt Kopecb2910442013-07-09 15:09:45 +00001768 log->Printf ("ProcessMonitor::%s() received limbo event, data = %lx, pid = %" PRIu64, __FUNCTION__, data, pid);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001769 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001770 break;
1771 }
1772
1773 case 0:
1774 case TRAP_TRACE:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001775 if (log)
1776 log->Printf ("ProcessMonitor::%s() received trace event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001777 message = ProcessMessage::Trace(pid);
1778 break;
1779
1780 case SI_KERNEL:
1781 case TRAP_BRKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001782 if (log)
1783 log->Printf ("ProcessMonitor::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001784 message = ProcessMessage::Break(pid);
1785 break;
Matt Kopece9ea0da2013-05-07 19:29:28 +00001786
1787 case TRAP_HWBKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001788 if (log)
1789 log->Printf ("ProcessMonitor::%s() received watchpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Matt Kopece9ea0da2013-05-07 19:29:28 +00001790 message = ProcessMessage::Watch(pid, (lldb::addr_t)info->si_addr);
1791 break;
Matt Kopec4a32bf52013-07-11 20:01:22 +00001792
1793 case SIGTRAP:
1794 case (SIGTRAP | 0x80):
1795 if (log)
1796 log->Printf ("ProcessMonitor::%s() received system call stop event, pid = %" PRIu64, __FUNCTION__, pid);
1797 // Ignore these signals until we know more about them
1798 monitor->Resume(pid, eResumeSignalNone);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001799 }
1800
1801 return message;
1802}
1803
Stephen Wilson84ffe702011-03-30 15:55:52 +00001804ProcessMessage
1805ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001806 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001807{
1808 ProcessMessage message;
1809 int signo = info->si_signo;
1810
Andrew Kaylor93132f52013-05-28 23:04:25 +00001811 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1812
Stephen Wilson84ffe702011-03-30 15:55:52 +00001813 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1814 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1815 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1816 //
1817 // IOW, user generated signals never generate what we consider to be a
1818 // "crash".
1819 //
1820 // Similarly, ACK signals generated by this monitor.
1821 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1822 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001823 if (log)
Matt Kopecef143712013-06-03 18:00:07 +00001824 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
Andrew Kaylor93132f52013-05-28 23:04:25 +00001825 __FUNCTION__,
1826 monitor->m_process->GetUnixSignals().GetSignalAsCString (signo),
1827 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1828 info->si_pid);
1829
Stephen Wilson84ffe702011-03-30 15:55:52 +00001830 if (info->si_pid == getpid())
1831 return ProcessMessage::SignalDelivered(pid, signo);
1832 else
1833 return ProcessMessage::Signal(pid, signo);
1834 }
1835
Andrew Kaylor93132f52013-05-28 23:04:25 +00001836 if (log)
1837 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals().GetSignalAsCString (signo));
1838
Stephen Wilson84ffe702011-03-30 15:55:52 +00001839 if (signo == SIGSEGV) {
1840 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1841 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1842 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1843 }
1844
1845 if (signo == SIGILL) {
1846 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1847 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1848 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1849 }
1850
1851 if (signo == SIGFPE) {
1852 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1853 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1854 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1855 }
1856
1857 if (signo == SIGBUS) {
1858 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1859 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1860 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1861 }
1862
1863 // Everything else is "normal" and does not require any special action on
1864 // our part.
1865 return ProcessMessage::Signal(pid, signo);
1866}
1867
Andrew Kaylord4d54992013-09-17 00:30:24 +00001868// On Linux, when a new thread is created, we receive to notifications,
1869// (1) a SIGTRAP|PTRACE_EVENT_CLONE from the main process thread with the
1870// child thread id as additional information, and (2) a SIGSTOP|SI_USER from
1871// the new child thread indicating that it has is stopped because we attached.
1872// We have no guarantee of the order in which these arrive, but we need both
1873// before we are ready to proceed. We currently keep a list of threads which
1874// have sent the initial SIGSTOP|SI_USER event. Then when we receive the
1875// SIGTRAP|PTRACE_EVENT_CLONE notification, if the initial stop has not occurred
1876// we call ProcessMonitor::WaitForInitialTIDStop() to wait for it.
1877
1878bool
1879ProcessMonitor::WaitForInitialTIDStop(lldb::tid_t tid)
1880{
1881 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1882 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001883 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waiting for thread to stop...", __FUNCTION__, tid);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001884
1885 // Wait for the thread to stop
1886 while (true)
1887 {
1888 int status = -1;
1889 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001890 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waitpid...", __FUNCTION__, tid);
Todd Fiala9be50492014-07-01 16:30:53 +00001891 ::pid_t wait_pid = waitpid(tid, &status, __WALL);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001892 if (status == -1)
1893 {
1894 // If we got interrupted by a signal (in our process, not the
1895 // inferior) try again.
1896 if (errno == EINTR)
1897 continue;
1898 else
1899 {
1900 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001901 log->Printf("ProcessMonitor::%s(%" PRIu64 ") waitpid error -- %s", __FUNCTION__, tid, strerror(errno));
Andrew Kaylord4d54992013-09-17 00:30:24 +00001902 return false; // This is bad, but there's nothing we can do.
1903 }
1904 }
1905
1906 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001907 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waitpid, status = %d", __FUNCTION__, tid, status);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001908
Todd Fiala9be50492014-07-01 16:30:53 +00001909 assert(static_cast<lldb::tid_t>(wait_pid) == tid);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001910
1911 siginfo_t info;
1912 int ptrace_err;
1913 if (!GetSignalInfo(wait_pid, &info, ptrace_err))
1914 {
1915 if (log)
1916 {
1917 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed. errno=%d (%s)", __FUNCTION__, ptrace_err, strerror(ptrace_err));
1918 }
1919 return false;
1920 }
1921
1922 // If this is a thread exit, we won't get any more information.
1923 if (WIFEXITED(status))
1924 {
1925 m_process->SendMessage(ProcessMessage::Exit(wait_pid, WEXITSTATUS(status)));
Todd Fiala9be50492014-07-01 16:30:53 +00001926 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Andrew Kaylord4d54992013-09-17 00:30:24 +00001927 return true;
1928 continue;
1929 }
1930
1931 assert(info.si_code == SI_USER);
1932 assert(WSTOPSIG(status) == SIGSTOP);
1933
1934 if (log)
1935 log->Printf ("ProcessMonitor::%s(bp) received thread stop signal", __FUNCTION__);
1936 m_process->AddThreadForInitialStopIfNeeded(wait_pid);
1937 return true;
1938 }
1939 return false;
1940}
1941
Andrew Kaylor93132f52013-05-28 23:04:25 +00001942bool
1943ProcessMonitor::StopThread(lldb::tid_t tid)
1944{
1945 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1946
1947 // FIXME: Try to use tgkill or tkill
1948 int ret = tgkill(m_pid, tid, SIGSTOP);
1949 if (log)
1950 log->Printf ("ProcessMonitor::%s(bp) stopping thread, tid = %" PRIu64 ", ret = %d", __FUNCTION__, tid, ret);
1951
1952 // This can happen if a thread exited while we were trying to stop it. That's OK.
1953 // We'll get the signal for that later.
1954 if (ret < 0)
1955 return false;
1956
1957 // Wait for the thread to stop
1958 while (true)
1959 {
1960 int status = -1;
1961 if (log)
1962 log->Printf ("ProcessMonitor::%s(bp) waitpid...", __FUNCTION__);
Todd Fiala9be50492014-07-01 16:30:53 +00001963 ::pid_t wait_pid = ::waitpid (-1*getpgid(m_pid), &status, __WALL);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001964 if (log)
Todd Fiala9be50492014-07-01 16:30:53 +00001965 log->Printf ("ProcessMonitor::%s(bp) waitpid, pid = %" PRIu64 ", status = %d",
1966 __FUNCTION__, static_cast<lldb::pid_t>(wait_pid), status);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001967
Todd Fiala9be50492014-07-01 16:30:53 +00001968 if (wait_pid == -1)
Andrew Kaylor93132f52013-05-28 23:04:25 +00001969 {
1970 // If we got interrupted by a signal (in our process, not the
1971 // inferior) try again.
1972 if (errno == EINTR)
1973 continue;
1974 else
1975 return false; // This is bad, but there's nothing we can do.
1976 }
1977
1978 // If this is a thread exit, we won't get any more information.
1979 if (WIFEXITED(status))
1980 {
1981 m_process->SendMessage(ProcessMessage::Exit(wait_pid, WEXITSTATUS(status)));
Todd Fiala9be50492014-07-01 16:30:53 +00001982 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Andrew Kaylor93132f52013-05-28 23:04:25 +00001983 return true;
1984 continue;
1985 }
1986
1987 siginfo_t info;
1988 int ptrace_err;
1989 if (!GetSignalInfo(wait_pid, &info, ptrace_err))
1990 {
Todd Fiala1b0539c2014-01-27 17:03:57 +00001991 // another signal causing a StopAllThreads may have been received
1992 // before wait_pid's group-stop was processed, handle it now
1993 if (ptrace_err == EINVAL)
Andrew Kaylor93132f52013-05-28 23:04:25 +00001994 {
Todd Fiala1b0539c2014-01-27 17:03:57 +00001995 assert(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001996
Todd Fiala1b0539c2014-01-27 17:03:57 +00001997 if (log)
1998 log->Printf ("ProcessMonitor::%s() resuming from group-stop", __FUNCTION__);
1999 // inferior process is in 'group-stop', so deliver SIGSTOP signal
2000 if (!Resume(wait_pid, SIGSTOP)) {
2001 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
2002 }
2003 continue;
Andrew Kaylor93132f52013-05-28 23:04:25 +00002004 }
Todd Fiala1b0539c2014-01-27 17:03:57 +00002005
2006 if (log)
2007 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed.", __FUNCTION__);
Andrew Kaylor93132f52013-05-28 23:04:25 +00002008 return false;
2009 }
2010
2011 // Handle events from other threads
2012 if (log)
Todd Fiala9be50492014-07-01 16:30:53 +00002013 log->Printf ("ProcessMonitor::%s(bp) handling event, tid == %" PRIu64,
2014 __FUNCTION__, static_cast<lldb::tid_t>(wait_pid));
Andrew Kaylor93132f52013-05-28 23:04:25 +00002015
2016 ProcessMessage message;
2017 if (info.si_signo == SIGTRAP)
2018 message = MonitorSIGTRAP(this, &info, wait_pid);
2019 else
2020 message = MonitorSignal(this, &info, wait_pid);
2021
2022 POSIXThread *thread = static_cast<POSIXThread*>(m_process->GetThreadList().FindThreadByID(wait_pid).get());
2023
2024 // When a new thread is created, we may get a SIGSTOP for the new thread
2025 // just before we get the SIGTRAP that we use to add the thread to our
2026 // process thread list. We don't need to worry about that signal here.
2027 assert(thread || message.GetKind() == ProcessMessage::eSignalMessage);
2028
2029 if (!thread)
2030 {
2031 m_process->SendMessage(message);
2032 continue;
2033 }
2034
2035 switch (message.GetKind())
2036 {
Saleem Abdulrasool6747c7d2014-07-20 05:28:57 +00002037 case ProcessMessage::eExecMessage:
2038 llvm_unreachable("unexpected message");
Michael Sartainc258b302013-09-18 15:32:06 +00002039 case ProcessMessage::eAttachMessage:
Andrew Kaylor93132f52013-05-28 23:04:25 +00002040 case ProcessMessage::eInvalidMessage:
2041 break;
2042
2043 // These need special handling because we don't want to send a
2044 // resume even if we already sent a SIGSTOP to this thread. In
2045 // this case the resume will cause the thread to disappear. It is
2046 // unlikely that we'll ever get eExitMessage here, but the same
2047 // reasoning applies.
2048 case ProcessMessage::eLimboMessage:
2049 case ProcessMessage::eExitMessage:
2050 if (log)
2051 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
2052 // SendMessage will set the thread state as needed.
2053 m_process->SendMessage(message);
2054 // If this is the thread we're waiting for, stop waiting. Even
2055 // though this wasn't the signal we expected, it's the last
2056 // signal we'll see while this thread is alive.
Todd Fiala9be50492014-07-01 16:30:53 +00002057 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Andrew Kaylor93132f52013-05-28 23:04:25 +00002058 return true;
2059 break;
2060
Matt Kopecb2910442013-07-09 15:09:45 +00002061 case ProcessMessage::eSignalMessage:
2062 if (log)
2063 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
2064 if (WSTOPSIG(status) == SIGSTOP)
2065 {
2066 m_process->AddThreadForInitialStopIfNeeded(tid);
2067 thread->SetState(lldb::eStateStopped);
2068 }
2069 else
2070 {
2071 m_process->SendMessage(message);
2072 // This isn't the stop we were expecting, but the thread is
2073 // stopped. SendMessage will handle processing of this event,
2074 // but we need to resume here to get the stop we are waiting
2075 // for (otherwise the thread will stop again immediately when
2076 // we try to resume).
Todd Fiala9be50492014-07-01 16:30:53 +00002077 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Matt Kopecb2910442013-07-09 15:09:45 +00002078 Resume(wait_pid, eResumeSignalNone);
2079 }
2080 break;
2081
Andrew Kaylor93132f52013-05-28 23:04:25 +00002082 case ProcessMessage::eSignalDeliveredMessage:
2083 // This is the stop we're expecting.
Todd Fiala9be50492014-07-01 16:30:53 +00002084 if (static_cast<lldb::tid_t>(wait_pid) == tid &&
2085 WIFSTOPPED(status) &&
2086 WSTOPSIG(status) == SIGSTOP &&
2087 info.si_code == SI_TKILL)
Andrew Kaylor93132f52013-05-28 23:04:25 +00002088 {
2089 if (log)
2090 log->Printf ("ProcessMonitor::%s(bp) received signal, done waiting", __FUNCTION__);
2091 thread->SetState(lldb::eStateStopped);
2092 return true;
2093 }
2094 // else fall-through
Andrew Kaylor93132f52013-05-28 23:04:25 +00002095 case ProcessMessage::eBreakpointMessage:
2096 case ProcessMessage::eTraceMessage:
2097 case ProcessMessage::eWatchpointMessage:
2098 case ProcessMessage::eCrashMessage:
2099 case ProcessMessage::eNewThreadMessage:
2100 if (log)
2101 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
2102 // SendMessage will set the thread state as needed.
2103 m_process->SendMessage(message);
2104 // This isn't the stop we were expecting, but the thread is
2105 // stopped. SendMessage will handle processing of this event,
2106 // but we need to resume here to get the stop we are waiting
2107 // for (otherwise the thread will stop again immediately when
2108 // we try to resume).
Todd Fiala9be50492014-07-01 16:30:53 +00002109 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Andrew Kaylor93132f52013-05-28 23:04:25 +00002110 Resume(wait_pid, eResumeSignalNone);
2111 break;
2112 }
2113 }
2114 return false;
2115}
2116
Stephen Wilson84ffe702011-03-30 15:55:52 +00002117ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00002118ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002119{
2120 ProcessMessage::CrashReason reason;
2121 assert(info->si_signo == SIGSEGV);
2122
2123 reason = ProcessMessage::eInvalidCrashReason;
2124
Greg Clayton542e4072012-09-07 17:49:29 +00002125 switch (info->si_code)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002126 {
2127 default:
2128 assert(false && "unexpected si_code for SIGSEGV");
2129 break;
Matt Kopecf8cfe6b2013-08-09 15:26:56 +00002130 case SI_KERNEL:
2131 // Linux will occasionally send spurious SI_KERNEL codes.
2132 // (this is poorly documented in sigaction)
2133 // One way to get this is via unaligned SIMD loads.
2134 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2135 break;
Stephen Wilson84ffe702011-03-30 15:55:52 +00002136 case SEGV_MAPERR:
2137 reason = ProcessMessage::eInvalidAddress;
2138 break;
2139 case SEGV_ACCERR:
2140 reason = ProcessMessage::ePrivilegedAddress;
2141 break;
2142 }
Greg Clayton542e4072012-09-07 17:49:29 +00002143
Stephen Wilson84ffe702011-03-30 15:55:52 +00002144 return reason;
2145}
2146
2147ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00002148ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002149{
2150 ProcessMessage::CrashReason reason;
2151 assert(info->si_signo == SIGILL);
2152
2153 reason = ProcessMessage::eInvalidCrashReason;
2154
2155 switch (info->si_code)
2156 {
2157 default:
2158 assert(false && "unexpected si_code for SIGILL");
2159 break;
2160 case ILL_ILLOPC:
2161 reason = ProcessMessage::eIllegalOpcode;
2162 break;
2163 case ILL_ILLOPN:
2164 reason = ProcessMessage::eIllegalOperand;
2165 break;
2166 case ILL_ILLADR:
2167 reason = ProcessMessage::eIllegalAddressingMode;
2168 break;
2169 case ILL_ILLTRP:
2170 reason = ProcessMessage::eIllegalTrap;
2171 break;
2172 case ILL_PRVOPC:
2173 reason = ProcessMessage::ePrivilegedOpcode;
2174 break;
2175 case ILL_PRVREG:
2176 reason = ProcessMessage::ePrivilegedRegister;
2177 break;
2178 case ILL_COPROC:
2179 reason = ProcessMessage::eCoprocessorError;
2180 break;
2181 case ILL_BADSTK:
2182 reason = ProcessMessage::eInternalStackError;
2183 break;
2184 }
2185
2186 return reason;
2187}
2188
2189ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00002190ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002191{
2192 ProcessMessage::CrashReason reason;
2193 assert(info->si_signo == SIGFPE);
2194
2195 reason = ProcessMessage::eInvalidCrashReason;
2196
2197 switch (info->si_code)
2198 {
2199 default:
2200 assert(false && "unexpected si_code for SIGFPE");
2201 break;
2202 case FPE_INTDIV:
2203 reason = ProcessMessage::eIntegerDivideByZero;
2204 break;
2205 case FPE_INTOVF:
2206 reason = ProcessMessage::eIntegerOverflow;
2207 break;
2208 case FPE_FLTDIV:
2209 reason = ProcessMessage::eFloatDivideByZero;
2210 break;
2211 case FPE_FLTOVF:
2212 reason = ProcessMessage::eFloatOverflow;
2213 break;
2214 case FPE_FLTUND:
2215 reason = ProcessMessage::eFloatUnderflow;
2216 break;
2217 case FPE_FLTRES:
2218 reason = ProcessMessage::eFloatInexactResult;
2219 break;
2220 case FPE_FLTINV:
2221 reason = ProcessMessage::eFloatInvalidOperation;
2222 break;
2223 case FPE_FLTSUB:
2224 reason = ProcessMessage::eFloatSubscriptRange;
2225 break;
2226 }
2227
2228 return reason;
2229}
2230
2231ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00002232ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002233{
2234 ProcessMessage::CrashReason reason;
2235 assert(info->si_signo == SIGBUS);
2236
2237 reason = ProcessMessage::eInvalidCrashReason;
2238
2239 switch (info->si_code)
2240 {
2241 default:
2242 assert(false && "unexpected si_code for SIGBUS");
2243 break;
2244 case BUS_ADRALN:
2245 reason = ProcessMessage::eIllegalAlignment;
2246 break;
2247 case BUS_ADRERR:
2248 reason = ProcessMessage::eIllegalAddress;
2249 break;
2250 case BUS_OBJERR:
2251 reason = ProcessMessage::eHardwareError;
2252 break;
2253 }
2254
2255 return reason;
2256}
2257
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002258void
Johnny Chen25e68e32011-06-14 19:19:50 +00002259ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002260{
Stephen Wilson570243b2011-01-19 01:37:06 +00002261 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002262
Stephen Wilson570243b2011-01-19 01:37:06 +00002263 // We are finised with the arguments and are ready to go. Sync with the
2264 // parent thread and start serving operations on the inferior.
2265 sem_post(&args->m_semaphore);
2266
Michael Sartain704bf892013-10-09 01:28:57 +00002267 for(;;)
2268 {
Daniel Malea1efb4182013-09-16 23:12:18 +00002269 // wait for next pending operation
Todd Fiala8ce3dee2014-01-24 22:59:22 +00002270 if (sem_wait(&monitor->m_operation_pending))
2271 {
2272 if (errno == EINTR)
2273 continue;
2274 assert(false && "Unexpected errno from sem_wait");
2275 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002276
Daniel Malea1efb4182013-09-16 23:12:18 +00002277 monitor->m_operation->Execute(monitor);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002278
Daniel Malea1efb4182013-09-16 23:12:18 +00002279 // notify calling thread that operation is complete
2280 sem_post(&monitor->m_operation_done);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002281 }
2282}
2283
2284void
2285ProcessMonitor::DoOperation(Operation *op)
2286{
Daniel Malea1efb4182013-09-16 23:12:18 +00002287 Mutex::Locker lock(m_operation_mutex);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002288
Daniel Malea1efb4182013-09-16 23:12:18 +00002289 m_operation = op;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002290
Daniel Malea1efb4182013-09-16 23:12:18 +00002291 // notify operation thread that an operation is ready to be processed
2292 sem_post(&m_operation_pending);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002293
Daniel Malea1efb4182013-09-16 23:12:18 +00002294 // wait for operation to complete
Todd Fiala8ce3dee2014-01-24 22:59:22 +00002295 while (sem_wait(&m_operation_done))
2296 {
2297 if (errno == EINTR)
2298 continue;
2299 assert(false && "Unexpected errno from sem_wait");
2300 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002301}
2302
2303size_t
2304ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
2305 Error &error)
2306{
2307 size_t result;
2308 ReadOperation op(vm_addr, buf, size, error, result);
2309 DoOperation(&op);
2310 return result;
2311}
2312
2313size_t
2314ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
2315 lldb_private::Error &error)
2316{
2317 size_t result;
2318 WriteOperation op(vm_addr, buf, size, error, result);
2319 DoOperation(&op);
2320 return result;
2321}
2322
2323bool
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002324ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
Matt Kopec7de48462013-03-06 17:20:48 +00002325 unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002326{
2327 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002328 ReadRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002329 DoOperation(&op);
2330 return result;
2331}
2332
2333bool
Matt Kopec7de48462013-03-06 17:20:48 +00002334ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002335 const char* reg_name, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002336{
2337 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002338 WriteRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002339 DoOperation(&op);
2340 return result;
2341}
2342
2343bool
Matt Kopec7de48462013-03-06 17:20:48 +00002344ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002345{
2346 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002347 ReadGPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002348 DoOperation(&op);
2349 return result;
2350}
2351
2352bool
Matt Kopec7de48462013-03-06 17:20:48 +00002353ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002354{
2355 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002356 ReadFPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002357 DoOperation(&op);
2358 return result;
2359}
2360
2361bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002362ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2363{
2364 bool result;
2365 ReadRegisterSetOperation op(tid, buf, buf_size, regset, result);
2366 DoOperation(&op);
2367 return result;
2368}
2369
2370bool
Matt Kopec7de48462013-03-06 17:20:48 +00002371ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002372{
2373 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002374 WriteGPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002375 DoOperation(&op);
2376 return result;
2377}
2378
2379bool
Matt Kopec7de48462013-03-06 17:20:48 +00002380ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002381{
2382 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002383 WriteFPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002384 DoOperation(&op);
2385 return result;
2386}
2387
2388bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002389ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2390{
2391 bool result;
2392 WriteRegisterSetOperation op(tid, buf, buf_size, regset, result);
2393 DoOperation(&op);
2394 return result;
2395}
2396
2397bool
Richard Mitton0a558352013-10-17 21:14:00 +00002398ProcessMonitor::ReadThreadPointer(lldb::tid_t tid, lldb::addr_t &value)
2399{
2400 bool result;
2401 ReadThreadPointerOperation op(tid, &value, result);
2402 DoOperation(&op);
2403 return result;
2404}
2405
2406bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002407ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002408{
2409 bool result;
Andrew Kaylor93132f52013-05-28 23:04:25 +00002410 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
2411
2412 if (log)
2413 log->Printf ("ProcessMonitor::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
2414 m_process->GetUnixSignals().GetSignalAsCString (signo));
Stephen Wilson84ffe702011-03-30 15:55:52 +00002415 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002416 DoOperation(&op);
Andrew Kaylor93132f52013-05-28 23:04:25 +00002417 if (log)
2418 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002419 return result;
2420}
2421
2422bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002423ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002424{
2425 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00002426 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002427 DoOperation(&op);
2428 return result;
2429}
2430
2431bool
Ed Maste4e0999b2014-04-01 18:14:06 +00002432ProcessMonitor::Kill()
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002433{
Ed Maste4e0999b2014-04-01 18:14:06 +00002434 return kill(GetPID(), SIGKILL) == 0;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002435}
2436
2437bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00002438ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002439{
2440 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00002441 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002442 DoOperation(&op);
2443 return result;
2444}
2445
2446bool
2447ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2448{
2449 bool result;
2450 EventMessageOperation op(tid, message, result);
2451 DoOperation(&op);
2452 return result;
2453}
2454
Greg Clayton743ecf42012-10-16 20:20:18 +00002455lldb_private::Error
Matt Kopec085d6ce2013-05-31 22:00:07 +00002456ProcessMonitor::Detach(lldb::tid_t tid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002457{
Greg Clayton28041352011-11-29 20:50:10 +00002458 lldb_private::Error error;
Matt Kopec085d6ce2013-05-31 22:00:07 +00002459 if (tid != LLDB_INVALID_THREAD_ID)
2460 {
2461 DetachOperation op(tid, error);
Greg Clayton743ecf42012-10-16 20:20:18 +00002462 DoOperation(&op);
2463 }
Greg Clayton743ecf42012-10-16 20:20:18 +00002464 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00002465}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002466
2467bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002468ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
2469{
Peter Collingbourne62343202011-06-14 03:55:54 +00002470 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002471
2472 if (target_fd == -1)
2473 return false;
2474
Peter Collingbourne62343202011-06-14 03:55:54 +00002475 return (dup2(target_fd, fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002476}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002477
2478void
2479ProcessMonitor::StopMonitoringChildProcess()
2480{
Zachary Turneracee96a2014-09-23 18:32:09 +00002481 if (m_monitor_thread.IsJoinable())
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002482 {
Zachary Turner39de3112014-09-09 20:54:56 +00002483 m_monitor_thread.Cancel();
2484 m_monitor_thread.Join(nullptr);
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002485 }
2486}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002487
2488void
2489ProcessMonitor::StopMonitor()
2490{
2491 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00002492 StopOpThread();
Daniel Malea1efb4182013-09-16 23:12:18 +00002493 sem_destroy(&m_operation_pending);
2494 sem_destroy(&m_operation_done);
2495
Andrew Kaylor5e268992013-09-14 00:17:31 +00002496 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
2497 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
2498 // the descriptor to a ConnectionFileDescriptor object. Consequently
2499 // even though still has the file descriptor, we shouldn't close it here.
Stephen Wilson84ffe702011-03-30 15:55:52 +00002500}
2501
2502void
Greg Clayton743ecf42012-10-16 20:20:18 +00002503ProcessMonitor::StopOpThread()
2504{
Zachary Turneracee96a2014-09-23 18:32:09 +00002505 if (!m_operation_thread.IsJoinable())
Greg Clayton743ecf42012-10-16 20:20:18 +00002506 return;
2507
Zachary Turner39de3112014-09-09 20:54:56 +00002508 m_operation_thread.Cancel();
2509 m_operation_thread.Join(nullptr);
Greg Clayton743ecf42012-10-16 20:20:18 +00002510}