blob: e77a8a5a9581ec48fbb778716935d8e28ced508c [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>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000019
20// C++ Includes
21// Other libraries and framework includes
Johnny Chen0d5f2d42011-10-18 18:09:30 +000022#include "lldb/Core/Debugger.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000023#include "lldb/Core/Error.h"
Johnny Chen13e8e1c2011-05-13 21:29:50 +000024#include "lldb/Core/RegisterValue.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000025#include "lldb/Core/Scalar.h"
26#include "lldb/Host/Host.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000027#include "lldb/Host/HostNativeThread.h"
Zachary Turner39de3112014-09-09 20:54:56 +000028#include "lldb/Host/HostThread.h"
29#include "lldb/Host/ThreadLauncher.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000030#include "lldb/Target/Thread.h"
31#include "lldb/Target/RegisterContext.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000032#include "lldb/Target/UnixSignals.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000033#include "lldb/Utility/PseudoTerminal.h"
34
Chaoren Lin28e57422015-02-03 01:51:25 +000035#include "Plugins/Process/POSIX/CrashReason.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000036#include "Plugins/Process/POSIX/POSIXThread.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000037#include "ProcessLinux.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000038#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000039#include "ProcessMonitor.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000040#include "Procfs.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000041
Tamas Berghammerd8584872015-02-06 10:57:40 +000042// System includes - They have to be included after framework includes because they define some
43// macros which collide with variable names in other modules
Vince Harron8b335672015-05-12 01:10:56 +000044
45#include "lldb/Host/linux/Personality.h"
46#include "lldb/Host/linux/Ptrace.h"
47#include "lldb/Host/linux/Signalfd.h"
48#include "lldb/Host/android/Android.h"
49
Tamas Berghammerd8584872015-02-06 10:57:40 +000050#include <sys/socket.h>
51#include <sys/syscall.h>
52#include <sys/types.h>
53#include <sys/uio.h>
54#include <sys/user.h>
55#include <sys/wait.h>
56
Todd Fiala0bce1b62014-08-17 00:10:50 +000057#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Matt Kopec58c0b962013-03-20 20:34:35 +000058
Matt Kopece9ea0da2013-05-07 19:29:28 +000059// Support hardware breakpoints in case it has not been defined
60#ifndef TRAP_HWBKPT
61 #define TRAP_HWBKPT 4
62#endif
63
Andrew Kaylor93132f52013-05-28 23:04:25 +000064// Try to define a macro to encapsulate the tgkill syscall
65// fall back on kill() if tgkill isn't available
Chaoren Linc9346592015-02-28 00:20:16 +000066#define tgkill(pid, tid, sig) \
67 syscall(SYS_tgkill, static_cast<::pid_t>(pid), static_cast<::pid_t>(tid), sig)
Andrew Kaylor93132f52013-05-28 23:04:25 +000068
Stephen Wilsone6f9f662010-07-24 02:19:04 +000069using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000070using namespace lldb_private::process_linux;
Stephen Wilsone6f9f662010-07-24 02:19:04 +000071
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000072static Operation* EXIT_OPERATION = nullptr;
73
Johnny Chen0d5f2d42011-10-18 18:09:30 +000074// FIXME: this code is host-dependent with respect to types and
75// endianness and needs to be fixed. For example, lldb::addr_t is
76// hard-coded to uint64_t, but on a 32-bit Linux host, ptrace requires
77// 32-bit pointer arguments. This code uses casts to work around the
78// problem.
79
80// We disable the tracing of ptrace calls for integration builds to
81// avoid the additional indirection and checks.
82#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
83
Greg Clayton386ff182011-11-05 01:09:16 +000084static void
85DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
86{
87 uint8_t *ptr = (uint8_t *)bytes;
88 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
89 for(uint32_t i=0; i<loop_count; i++)
90 {
91 s.Printf ("[%x]", *ptr);
92 ptr++;
93 }
94}
95
Matt Kopec58c0b962013-03-20 20:34:35 +000096static void PtraceDisplayBytes(int &req, void *data, size_t data_size)
Greg Clayton386ff182011-11-05 01:09:16 +000097{
98 StreamString buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +000099 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
Johnny Chen30213ff2012-01-05 19:17:38 +0000100 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
Greg Clayton386ff182011-11-05 01:09:16 +0000101
102 if (verbose_log)
103 {
104 switch(req)
105 {
106 case PTRACE_POKETEXT:
107 {
108 DisplayBytes(buf, &data, 8);
109 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
110 break;
111 }
Greg Clayton542e4072012-09-07 17:49:29 +0000112 case PTRACE_POKEDATA:
Greg Clayton386ff182011-11-05 01:09:16 +0000113 {
114 DisplayBytes(buf, &data, 8);
115 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
116 break;
117 }
Greg Clayton542e4072012-09-07 17:49:29 +0000118 case PTRACE_POKEUSER:
Greg Clayton386ff182011-11-05 01:09:16 +0000119 {
120 DisplayBytes(buf, &data, 8);
121 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
122 break;
123 }
Todd Fiala6ac1be42014-08-21 16:34:03 +0000124#if !defined (__arm64__) && !defined (__aarch64__)
Greg Clayton542e4072012-09-07 17:49:29 +0000125 case PTRACE_SETREGS:
Greg Clayton386ff182011-11-05 01:09:16 +0000126 {
Matt Kopec7de48462013-03-06 17:20:48 +0000127 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000128 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
129 break;
130 }
131 case PTRACE_SETFPREGS:
132 {
Matt Kopec7de48462013-03-06 17:20:48 +0000133 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000134 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
135 break;
136 }
Todd Fialad35f2b92014-06-23 15:59:04 +0000137#endif
Greg Clayton542e4072012-09-07 17:49:29 +0000138 case PTRACE_SETSIGINFO:
Greg Clayton386ff182011-11-05 01:09:16 +0000139 {
140 DisplayBytes(buf, data, sizeof(siginfo_t));
141 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
142 break;
143 }
Matt Kopec58c0b962013-03-20 20:34:35 +0000144 case PTRACE_SETREGSET:
145 {
146 // Extract iov_base from data, which is a pointer to the struct IOVEC
147 DisplayBytes(buf, *(void **)data, data_size);
148 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
149 break;
150 }
Greg Clayton386ff182011-11-05 01:09:16 +0000151 default:
152 {
153 }
154 }
155 }
156}
157
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000158// Wrapper for ptrace to catch errors and log calls.
Ashok Thirumurthi762fbd02013-03-27 21:09:30 +0000159// 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 +0000160extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000161PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000162 const char* reqName, const char* file, int line)
163{
Greg Clayton386ff182011-11-05 01:09:16 +0000164 long int result;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000165
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000166 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
Greg Clayton386ff182011-11-05 01:09:16 +0000167
Matt Kopec7de48462013-03-06 17:20:48 +0000168 PtraceDisplayBytes(req, data, data_size);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000169
170 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000171 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala4507f062014-02-27 20:46:12 +0000172 result = ptrace(static_cast<__ptrace_request>(req), static_cast<pid_t>(pid), *(unsigned int *)addr, data);
Matt Kopec58c0b962013-03-20 20:34:35 +0000173 else
Todd Fiala4507f062014-02-27 20:46:12 +0000174 result = ptrace(static_cast<__ptrace_request>(req), static_cast<pid_t>(pid), addr, data);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000175
Ed Mastec099c952014-02-24 14:07:45 +0000176 if (log)
177 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
178 reqName, pid, addr, data, data_size, result, file, line);
179
Matt Kopec7de48462013-03-06 17:20:48 +0000180 PtraceDisplayBytes(req, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000181
Matt Kopec7de48462013-03-06 17:20:48 +0000182 if (log && errno != 0)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000183 {
184 const char* str;
185 switch (errno)
186 {
187 case ESRCH: str = "ESRCH"; break;
188 case EINVAL: str = "EINVAL"; break;
189 case EBUSY: str = "EBUSY"; break;
190 case EPERM: str = "EPERM"; break;
191 default: str = "<unknown>";
192 }
193 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
194 }
195
196 return result;
197}
198
Matt Kopec7de48462013-03-06 17:20:48 +0000199// Wrapper for ptrace when logging is not required.
200// Sets errno to 0 prior to calling ptrace.
201extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000202PtraceWrapper(int req, pid_t pid, void *addr, void *data, size_t data_size)
Matt Kopec7de48462013-03-06 17:20:48 +0000203{
Matt Kopec58c0b962013-03-20 20:34:35 +0000204 long result = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000205 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000206 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
207 result = ptrace(static_cast<__ptrace_request>(req), pid, *(unsigned int *)addr, data);
208 else
209 result = ptrace(static_cast<__ptrace_request>(req), pid, addr, data);
Matt Kopec7de48462013-03-06 17:20:48 +0000210 return result;
211}
212
213#define PTRACE(req, pid, addr, data, data_size) \
214 PtraceWrapper((req), (pid), (addr), (data), (data_size), #req, __FILE__, __LINE__)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000215#else
Matt Kopec7de48462013-03-06 17:20:48 +0000216 PtraceWrapper((req), (pid), (addr), (data), (data_size))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000217#endif
218
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000219//------------------------------------------------------------------------------
220// Static implementations of ProcessMonitor::ReadMemory and
221// ProcessMonitor::WriteMemory. This enables mutual recursion between these
222// functions without needed to go thru the thread funnel.
223
224static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000225DoReadMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000226 lldb::addr_t vm_addr, void *buf, size_t size, Error &error)
227{
Greg Clayton542e4072012-09-07 17:49:29 +0000228 // ptrace word size is determined by the host, not the child
229 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000230 unsigned char *dst = static_cast<unsigned char*>(buf);
231 size_t bytes_read;
232 size_t remainder;
233 long data;
234
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000235 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000236 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000237 ProcessPOSIXLog::IncNestLevel();
238 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000239 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000240 pid, word_size, (void*)vm_addr, buf, size);
241
242 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000243 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
244 {
245 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000246 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, NULL, 0);
247 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000248 {
249 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000250 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000251 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000252 return bytes_read;
253 }
254
255 remainder = size - bytes_read;
256 remainder = remainder > word_size ? word_size : remainder;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000257
258 // Copy the data into our buffer
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000259 for (unsigned i = 0; i < remainder; ++i)
260 dst[i] = ((data >> i*8) & 0xFF);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000261
Johnny Chen30213ff2012-01-05 19:17:38 +0000262 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
263 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
264 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
265 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Daniel Maleac63dddd2012-12-14 21:07:07 +0000266 {
267 uintptr_t print_dst = 0;
268 // Format bytes from data by moving into print_dst for log output
269 for (unsigned i = 0; i < remainder; ++i)
270 print_dst |= (((data >> i*8) & 0xFF) << i*8);
271 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
272 (void*)vm_addr, print_dst, (unsigned long)data);
273 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000274
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000275 vm_addr += word_size;
276 dst += word_size;
277 }
278
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000279 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000280 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000281 return bytes_read;
282}
283
284static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000285DoWriteMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000286 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
287{
Greg Clayton542e4072012-09-07 17:49:29 +0000288 // ptrace word size is determined by the host, not the child
289 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000290 const unsigned char *src = static_cast<const unsigned char*>(buf);
291 size_t bytes_written = 0;
292 size_t remainder;
293
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000294 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000295 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000296 ProcessPOSIXLog::IncNestLevel();
297 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000298 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000299 pid, word_size, (void*)vm_addr, buf, size);
300
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000301 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
302 {
303 remainder = size - bytes_written;
304 remainder = remainder > word_size ? word_size : remainder;
305
306 if (remainder == word_size)
307 {
308 unsigned long data = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000309 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000310 for (unsigned i = 0; i < word_size; ++i)
311 data |= (unsigned long)src[i] << i*8;
312
Johnny Chen30213ff2012-01-05 19:17:38 +0000313 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
314 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
315 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
316 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000317 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
318 (void*)vm_addr, *(unsigned long*)src, data);
319
Matt Kopec7de48462013-03-06 17:20:48 +0000320 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000321 {
322 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000323 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000324 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000325 return bytes_written;
326 }
327 }
328 else
329 {
330 unsigned char buff[8];
Greg Clayton542e4072012-09-07 17:49:29 +0000331 if (DoReadMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000332 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000333 {
334 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000335 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000336 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000337 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000338
339 memcpy(buff, src, remainder);
340
Greg Clayton542e4072012-09-07 17:49:29 +0000341 if (DoWriteMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000342 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000343 {
344 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000345 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000346 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000347 }
348
Johnny Chen30213ff2012-01-05 19:17:38 +0000349 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
350 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
351 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
352 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000353 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Vince Harrond7e6a4f2015-05-13 00:25:54 +0000354 (void*)vm_addr, *(const unsigned long*)src, *(const unsigned long*)buff);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000355 }
356
357 vm_addr += word_size;
358 src += word_size;
359 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000360 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000361 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000362 return bytes_written;
363}
364
Stephen Wilson26977162011-03-23 02:14:42 +0000365// Simple helper function to ensure flags are enabled on the given file
366// descriptor.
367static bool
368EnsureFDFlags(int fd, int flags, Error &error)
369{
370 int status;
371
372 if ((status = fcntl(fd, F_GETFL)) == -1)
373 {
374 error.SetErrorToErrno();
375 return false;
376 }
377
378 if (fcntl(fd, F_SETFL, status | flags) == -1)
379 {
380 error.SetErrorToErrno();
381 return false;
382 }
383
384 return true;
385}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000386
387//------------------------------------------------------------------------------
388/// @class Operation
389/// @brief Represents a ProcessMonitor operation.
390///
391/// Under Linux, it is not possible to ptrace() from any other thread but the
392/// one that spawned or attached to the process from the start. Therefore, when
393/// a ProcessMonitor is asked to deliver or change the state of an inferior
394/// process the operation must be "funneled" to a specific thread to perform the
395/// task. The Operation class provides an abstract base for all services the
396/// ProcessMonitor must perform via the single virtual function Execute, thus
397/// encapsulating the code that needs to run in the privileged context.
398class Operation
399{
400public:
Daniel Maleadd15b782013-05-13 17:32:07 +0000401 virtual ~Operation() {}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000402 virtual void Execute(ProcessMonitor *monitor) = 0;
403};
404
405//------------------------------------------------------------------------------
406/// @class ReadOperation
407/// @brief Implements ProcessMonitor::ReadMemory.
408class ReadOperation : public Operation
409{
410public:
411 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
412 Error &error, size_t &result)
413 : m_addr(addr), m_buff(buff), m_size(size),
414 m_error(error), m_result(result)
415 { }
416
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000417 void Execute(ProcessMonitor *monitor) override;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000418
419private:
420 lldb::addr_t m_addr;
421 void *m_buff;
422 size_t m_size;
423 Error &m_error;
424 size_t &m_result;
425};
426
427void
428ReadOperation::Execute(ProcessMonitor *monitor)
429{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000430 lldb::pid_t pid = monitor->GetPID();
431
Greg Clayton542e4072012-09-07 17:49:29 +0000432 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000433}
434
435//------------------------------------------------------------------------------
Ed Mastea56115f2013-07-17 14:30:26 +0000436/// @class WriteOperation
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000437/// @brief Implements ProcessMonitor::WriteMemory.
438class WriteOperation : public Operation
439{
440public:
441 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
442 Error &error, size_t &result)
443 : m_addr(addr), m_buff(buff), m_size(size),
444 m_error(error), m_result(result)
445 { }
446
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000447 void Execute(ProcessMonitor *monitor) override;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000448
449private:
450 lldb::addr_t m_addr;
451 const void *m_buff;
452 size_t m_size;
453 Error &m_error;
454 size_t &m_result;
455};
456
457void
458WriteOperation::Execute(ProcessMonitor *monitor)
459{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000460 lldb::pid_t pid = monitor->GetPID();
461
Greg Clayton542e4072012-09-07 17:49:29 +0000462 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000463}
464
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000465
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000466//------------------------------------------------------------------------------
467/// @class ReadRegOperation
468/// @brief Implements ProcessMonitor::ReadRegisterValue.
469class ReadRegOperation : public Operation
470{
471public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000472 ReadRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000473 RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000474 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000475 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000476 { }
477
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000478 void Execute(ProcessMonitor *monitor) override;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000479
480private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000481 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000482 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000483 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000484 RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000485 bool &m_result;
486};
487
488void
489ReadRegOperation::Execute(ProcessMonitor *monitor)
490{
Todd Fiala49131cf2014-09-12 16:57:28 +0000491#if defined (__arm64__) || defined (__aarch64__)
492 if (m_offset > sizeof(struct user_pt_regs))
493 {
494 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
495 if (offset > sizeof(struct user_fpsimd_state))
496 {
497 m_result = false;
498 }
499 else
500 {
501 elf_fpregset_t regs;
502 int regset = NT_FPREGSET;
503 struct iovec ioVec;
504
505 ioVec.iov_base = &regs;
506 ioVec.iov_len = sizeof regs;
507 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
508 m_result = false;
509 else
510 {
511 m_result = true;
512 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, monitor->GetProcess().GetByteOrder());
513 }
514 }
515 }
516 else
517 {
518 elf_gregset_t regs;
519 int regset = NT_PRSTATUS;
520 struct iovec ioVec;
521
522 ioVec.iov_base = &regs;
523 ioVec.iov_len = sizeof regs;
524 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
525 m_result = false;
526 else
527 {
528 m_result = true;
529 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, monitor->GetProcess().GetByteOrder());
530 }
531 }
532#else
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000533 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000534
535 // Set errno to zero so that we can detect a failed peek.
536 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000537 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, NULL, 0);
538 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000539 m_result = false;
540 else
541 {
542 m_value = data;
543 m_result = true;
544 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000545 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000546 log->Printf ("ProcessMonitor::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000547 m_reg_name, data);
Todd Fiala49131cf2014-09-12 16:57:28 +0000548#endif
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000549}
550
Omair Javaidea8c25a802015-05-15 06:29:58 +0000551#if defined (__arm64__) || defined (__aarch64__)
552 //------------------------------------------------------------------------------
553 /// @class ReadDBGROperation
554 /// @brief Implements NativeProcessLinux::ReadDBGR.
555 class ReadDBGROperation : public Operation
556 {
557 public:
558 ReadDBGROperation(lldb::tid_t tid, unsigned int &count_wp, unsigned int &count_bp)
559 : m_tid(tid),
560 m_count_wp(count_wp),
561 m_count_bp(count_bp)
562 { }
563
564 void Execute(ProcessMonitor *monitor) override;
565
566 private:
567 lldb::tid_t m_tid;
568 unsigned int &m_count_wp;
569 unsigned int &m_count_bp;
570 };
571
572 void
573 ReadDBGROperation::Execute(ProcessMonitor *monitor)
574 {
575 int regset = NT_ARM_HW_WATCH;
576 struct iovec ioVec;
577 struct user_hwdebug_state dreg_state;
578
579 ioVec.iov_base = &dreg_state;
580 ioVec.iov_len = sizeof (dreg_state);
581
582 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, ioVec.iov_len);
583
584 m_count_wp = dreg_state.dbg_info & 0xff;
585 regset = NT_ARM_HW_BREAK;
586
587 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, ioVec.iov_len);
588 m_count_bp = dreg_state.dbg_info & 0xff;
589 }
590#endif
591
592#if defined (__arm64__) || defined (__aarch64__)
593 //------------------------------------------------------------------------------
594 /// @class WriteDBGROperation
595 /// @brief Implements NativeProcessLinux::WriteFPR.
596 class WriteDBGROperation : public Operation
597 {
598 public:
599 WriteDBGROperation(lldb::tid_t tid, lldb::addr_t *addr_buf, uint32_t *cntrl_buf, int type, int count)
600 : m_tid(tid),
601 m_addr_buf(addr_buf),
602 m_cntrl_buf(cntrl_buf),
603 m_type(type),
604 m_count(count)
605 { }
606
607 void Execute(ProcessMonitor *monitor) override;
608
609 private:
610 lldb::tid_t m_tid;
611 lldb::addr_t *m_addr_buf;
612 uint32_t *m_cntrl_buf;
613 int m_type;
614 int m_count;
615 };
616
617 void
618 WriteDBGROperation::Execute(ProcessMonitor *monitor)
619 {
620 struct iovec ioVec;
621 struct user_hwdebug_state dreg_state;
622
623 memset (&dreg_state, 0, sizeof (dreg_state));
Vince Harron341eda42015-05-16 00:26:20 +0000624 ioVec.iov_base = &dreg_state;
625 ioVec.iov_len = sizeof(dreg_state);
Omair Javaidea8c25a802015-05-15 06:29:58 +0000626
627 if (m_type == 0)
628 m_type = NT_ARM_HW_WATCH;
629 else
630 m_type = NT_ARM_HW_BREAK;
631
632 for (int i = 0; i < m_count; i++)
633 {
634 dreg_state.dbg_regs[i].addr = m_addr_buf[i];
635 dreg_state.dbg_regs[i].ctrl = m_cntrl_buf[i];
636 }
637
638 PTRACE(PTRACE_SETREGSET, m_tid, &m_type, &ioVec, ioVec.iov_len);
639 }
640#endif//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000641/// @class WriteRegOperation
642/// @brief Implements ProcessMonitor::WriteRegisterValue.
643class WriteRegOperation : public Operation
644{
645public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000646 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000647 const RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000648 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000649 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000650 { }
651
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000652 void Execute(ProcessMonitor *monitor) override;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000653
654private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000655 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000656 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000657 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000658 const RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000659 bool &m_result;
660};
661
662void
663WriteRegOperation::Execute(ProcessMonitor *monitor)
664{
Todd Fiala49131cf2014-09-12 16:57:28 +0000665#if defined (__arm64__) || defined (__aarch64__)
666 if (m_offset > sizeof(struct user_pt_regs))
667 {
668 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
669 if (offset > sizeof(struct user_fpsimd_state))
670 {
671 m_result = false;
672 }
673 else
674 {
675 elf_fpregset_t regs;
676 int regset = NT_FPREGSET;
677 struct iovec ioVec;
678
679 ioVec.iov_base = &regs;
680 ioVec.iov_len = sizeof regs;
681 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
682 m_result = false;
683 else
684 {
685 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
686 if (PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
687 m_result = false;
688 else
689 m_result = true;
690 }
691 }
692 }
693 else
694 {
695 elf_gregset_t regs;
696 int regset = NT_PRSTATUS;
697 struct iovec ioVec;
698
699 ioVec.iov_base = &regs;
700 ioVec.iov_len = sizeof regs;
701 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
702 m_result = false;
703 else
704 {
705 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
706 if (PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs) < 0)
707 m_result = false;
708 else
709 m_result = true;
710 }
711 }
712#else
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000713 void* buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000714 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000715
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000716 buf = (void*) m_value.GetAsUInt64();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000717
718 if (log)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000719 log->Printf ("ProcessMonitor::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Matt Kopec7de48462013-03-06 17:20:48 +0000720 if (PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000721 m_result = false;
722 else
723 m_result = true;
Todd Fiala49131cf2014-09-12 16:57:28 +0000724#endif
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000725}
726
727//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000728/// @class ReadGPROperation
729/// @brief Implements ProcessMonitor::ReadGPR.
730class ReadGPROperation : public Operation
731{
732public:
Matt Kopec7de48462013-03-06 17:20:48 +0000733 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
734 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000735 { }
736
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000737 void Execute(ProcessMonitor *monitor) override;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000738
739private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000740 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000741 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000742 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000743 bool &m_result;
744};
745
746void
747ReadGPROperation::Execute(ProcessMonitor *monitor)
748{
Todd Fiala6ac1be42014-08-21 16:34:03 +0000749#if defined (__arm64__) || defined (__aarch64__)
750 int regset = NT_PRSTATUS;
751 struct iovec ioVec;
752
753 ioVec.iov_base = m_buf;
754 ioVec.iov_len = m_buf_size;
755 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000756 m_result = false;
757 else
758 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000759#else
Todd Fiala6ac1be42014-08-21 16:34:03 +0000760 if (PTRACE(PTRACE_GETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
761 m_result = false;
762 else
763 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000764#endif
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000765}
766
767//------------------------------------------------------------------------------
768/// @class ReadFPROperation
769/// @brief Implements ProcessMonitor::ReadFPR.
770class ReadFPROperation : public Operation
771{
772public:
Matt Kopec7de48462013-03-06 17:20:48 +0000773 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
774 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000775 { }
776
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000777 void Execute(ProcessMonitor *monitor) override;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000778
779private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000780 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000781 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000782 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000783 bool &m_result;
784};
785
786void
787ReadFPROperation::Execute(ProcessMonitor *monitor)
788{
Todd Fiala6ac1be42014-08-21 16:34:03 +0000789#if defined (__arm64__) || defined (__aarch64__)
790 int regset = NT_FPREGSET;
791 struct iovec ioVec;
792
793 ioVec.iov_base = m_buf;
794 ioVec.iov_len = m_buf_size;
795 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000796 m_result = false;
797 else
798 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000799#else
Todd Fiala6ac1be42014-08-21 16:34:03 +0000800 if (PTRACE(PTRACE_GETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
801 m_result = false;
802 else
803 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000804#endif
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000805}
806
807//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000808/// @class ReadRegisterSetOperation
809/// @brief Implements ProcessMonitor::ReadRegisterSet.
810class ReadRegisterSetOperation : public Operation
811{
812public:
813 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
814 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
815 { }
816
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000817 void Execute(ProcessMonitor *monitor) override;
Matt Kopec58c0b962013-03-20 20:34:35 +0000818
819private:
820 lldb::tid_t m_tid;
821 void *m_buf;
822 size_t m_buf_size;
823 const unsigned int m_regset;
824 bool &m_result;
825};
826
827void
828ReadRegisterSetOperation::Execute(ProcessMonitor *monitor)
829{
830 if (PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
831 m_result = false;
832 else
833 m_result = true;
834}
835
836//------------------------------------------------------------------------------
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000837/// @class WriteGPROperation
838/// @brief Implements ProcessMonitor::WriteGPR.
839class WriteGPROperation : public Operation
840{
841public:
Matt Kopec7de48462013-03-06 17:20:48 +0000842 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
843 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000844 { }
845
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000846 void Execute(ProcessMonitor *monitor) override;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000847
848private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000849 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000850 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000851 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000852 bool &m_result;
853};
854
855void
856WriteGPROperation::Execute(ProcessMonitor *monitor)
857{
Todd Fiala6ac1be42014-08-21 16:34:03 +0000858#if defined (__arm64__) || defined (__aarch64__)
859 int regset = NT_PRSTATUS;
860 struct iovec ioVec;
861
862 ioVec.iov_base = m_buf;
863 ioVec.iov_len = m_buf_size;
864 if (PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000865 m_result = false;
866 else
867 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000868#else
Todd Fiala6ac1be42014-08-21 16:34:03 +0000869 if (PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
870 m_result = false;
871 else
872 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000873#endif
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000874}
875
876//------------------------------------------------------------------------------
877/// @class WriteFPROperation
878/// @brief Implements ProcessMonitor::WriteFPR.
879class WriteFPROperation : public Operation
880{
881public:
Matt Kopec7de48462013-03-06 17:20:48 +0000882 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
883 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000884 { }
885
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000886 void Execute(ProcessMonitor *monitor) override;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000887
888private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000889 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000890 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000891 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000892 bool &m_result;
893};
894
895void
896WriteFPROperation::Execute(ProcessMonitor *monitor)
897{
Todd Fiala6ac1be42014-08-21 16:34:03 +0000898#if defined (__arm64__) || defined (__aarch64__)
899 int regset = NT_FPREGSET;
900 struct iovec ioVec;
901
902 ioVec.iov_base = m_buf;
903 ioVec.iov_len = m_buf_size;
904 if (PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000905 m_result = false;
906 else
907 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000908#else
Todd Fiala6ac1be42014-08-21 16:34:03 +0000909 if (PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
910 m_result = false;
911 else
912 m_result = true;
Todd Fialad35f2b92014-06-23 15:59:04 +0000913#endif
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000914}
915
916//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000917/// @class WriteRegisterSetOperation
918/// @brief Implements ProcessMonitor::WriteRegisterSet.
919class WriteRegisterSetOperation : public Operation
920{
921public:
922 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
923 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
924 { }
925
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000926 void Execute(ProcessMonitor *monitor) override;
Matt Kopec58c0b962013-03-20 20:34:35 +0000927
928private:
929 lldb::tid_t m_tid;
930 void *m_buf;
931 size_t m_buf_size;
932 const unsigned int m_regset;
933 bool &m_result;
934};
935
936void
937WriteRegisterSetOperation::Execute(ProcessMonitor *monitor)
938{
939 if (PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
940 m_result = false;
941 else
942 m_result = true;
943}
944
945//------------------------------------------------------------------------------
Richard Mitton0a558352013-10-17 21:14:00 +0000946/// @class ReadThreadPointerOperation
947/// @brief Implements ProcessMonitor::ReadThreadPointer.
948class ReadThreadPointerOperation : public Operation
949{
950public:
951 ReadThreadPointerOperation(lldb::tid_t tid, lldb::addr_t *addr, bool &result)
952 : m_tid(tid), m_addr(addr), m_result(result)
953 { }
954
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000955 void Execute(ProcessMonitor *monitor) override;
Richard Mitton0a558352013-10-17 21:14:00 +0000956
957private:
958 lldb::tid_t m_tid;
959 lldb::addr_t *m_addr;
960 bool &m_result;
961};
962
963void
964ReadThreadPointerOperation::Execute(ProcessMonitor *monitor)
965{
966 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
967 if (log)
968 log->Printf ("ProcessMonitor::%s()", __FUNCTION__);
969
970 // The process for getting the thread area on Linux is
971 // somewhat... obscure. There's several different ways depending on
972 // what arch you're on, and what kernel version you have.
973
974 const ArchSpec& arch = monitor->GetProcess().GetTarget().GetArchitecture();
975 switch(arch.GetMachine())
976 {
Todd Fiala42079682014-08-27 16:05:26 +0000977 case llvm::Triple::aarch64:
978 {
Todd Fialadbec1ff2014-09-04 16:08:20 +0000979 int regset = LLDB_PTRACE_NT_ARM_TLS;
Todd Fiala42079682014-08-27 16:05:26 +0000980 struct iovec ioVec;
981
982 ioVec.iov_base = m_addr;
983 ioVec.iov_len = sizeof(lldb::addr_t);
984 if (PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, ioVec.iov_len) < 0)
985 m_result = false;
986 else
987 m_result = true;
988 break;
989 }
Todd Fiala720cd3f2014-06-16 14:49:28 +0000990#if defined(__i386__) || defined(__x86_64__)
991 // Note that struct user below has a field named i387 which is x86-specific.
992 // Therefore, this case should be compiled only for x86-based systems.
Richard Mitton0a558352013-10-17 21:14:00 +0000993 case llvm::Triple::x86:
994 {
995 // Find the GS register location for our host architecture.
996 size_t gs_user_offset = offsetof(struct user, regs);
997#ifdef __x86_64__
998 gs_user_offset += offsetof(struct user_regs_struct, gs);
999#endif
1000#ifdef __i386__
1001 gs_user_offset += offsetof(struct user_regs_struct, xgs);
1002#endif
1003
1004 // Read the GS register value to get the selector.
1005 errno = 0;
1006 long gs = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)gs_user_offset, NULL, 0);
1007 if (errno)
1008 {
1009 m_result = false;
1010 break;
1011 }
1012
1013 // Read the LDT base for that selector.
1014 uint32_t tmp[4];
1015 m_result = (PTRACE(PTRACE_GET_THREAD_AREA, m_tid, (void *)(gs >> 3), &tmp, 0) == 0);
1016 *m_addr = tmp[1];
1017 break;
1018 }
Todd Fiala720cd3f2014-06-16 14:49:28 +00001019#endif
Richard Mitton0a558352013-10-17 21:14:00 +00001020 case llvm::Triple::x86_64:
1021 // Read the FS register base.
1022 m_result = (PTRACE(PTRACE_ARCH_PRCTL, m_tid, m_addr, (void *)ARCH_GET_FS, 0) == 0);
1023 break;
1024 default:
1025 m_result = false;
1026 break;
1027 }
1028}
1029
1030//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001031/// @class ResumeOperation
1032/// @brief Implements ProcessMonitor::Resume.
1033class ResumeOperation : public Operation
1034{
1035public:
Stephen Wilson84ffe702011-03-30 15:55:52 +00001036 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
1037 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001038
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001039 void Execute(ProcessMonitor *monitor) override;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001040
1041private:
1042 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001043 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001044 bool &m_result;
1045};
1046
1047void
1048ResumeOperation::Execute(ProcessMonitor *monitor)
1049{
Daniel Maleaa85e6b62012-12-07 22:21:08 +00001050 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001051
1052 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
1053 data = m_signo;
1054
Matt Kopec7de48462013-03-06 17:20:48 +00001055 if (PTRACE(PTRACE_CONT, m_tid, NULL, (void*)data, 0))
Andrew Kaylor93132f52013-05-28 23:04:25 +00001056 {
1057 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1058
1059 if (log)
1060 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, strerror(errno));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001061 m_result = false;
Andrew Kaylor93132f52013-05-28 23:04:25 +00001062 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001063 else
1064 m_result = true;
1065}
1066
1067//------------------------------------------------------------------------------
Ed Maste428a6782013-06-24 15:04:47 +00001068/// @class SingleStepOperation
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001069/// @brief Implements ProcessMonitor::SingleStep.
1070class SingleStepOperation : public Operation
1071{
1072public:
Stephen Wilson84ffe702011-03-30 15:55:52 +00001073 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
1074 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001075
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001076 void Execute(ProcessMonitor *monitor) override;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001077
1078private:
1079 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001080 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001081 bool &m_result;
1082};
1083
1084void
1085SingleStepOperation::Execute(ProcessMonitor *monitor)
1086{
Daniel Maleaa85e6b62012-12-07 22:21:08 +00001087 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001088
1089 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
1090 data = m_signo;
1091
Matt Kopec7de48462013-03-06 17:20:48 +00001092 if (PTRACE(PTRACE_SINGLESTEP, m_tid, NULL, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001093 m_result = false;
1094 else
1095 m_result = true;
1096}
1097
1098//------------------------------------------------------------------------------
1099/// @class SiginfoOperation
1100/// @brief Implements ProcessMonitor::GetSignalInfo.
1101class SiginfoOperation : public Operation
1102{
1103public:
Daniel Maleaa35970a2012-11-23 18:09:58 +00001104 SiginfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
1105 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001106
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001107 void Execute(ProcessMonitor *monitor) override;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001108
1109private:
1110 lldb::tid_t m_tid;
1111 void *m_info;
1112 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001113 int &m_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001114};
1115
1116void
1117SiginfoOperation::Execute(ProcessMonitor *monitor)
1118{
Matt Kopec7de48462013-03-06 17:20:48 +00001119 if (PTRACE(PTRACE_GETSIGINFO, m_tid, NULL, m_info, 0)) {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001120 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001121 m_err = errno;
1122 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001123 else
1124 m_result = true;
1125}
1126
1127//------------------------------------------------------------------------------
1128/// @class EventMessageOperation
1129/// @brief Implements ProcessMonitor::GetEventMessage.
1130class EventMessageOperation : public Operation
1131{
1132public:
1133 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
1134 : m_tid(tid), m_message(message), m_result(result) { }
1135
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001136 void Execute(ProcessMonitor *monitor) override;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001137
1138private:
1139 lldb::tid_t m_tid;
1140 unsigned long *m_message;
1141 bool &m_result;
1142};
1143
1144void
1145EventMessageOperation::Execute(ProcessMonitor *monitor)
1146{
Matt Kopec7de48462013-03-06 17:20:48 +00001147 if (PTRACE(PTRACE_GETEVENTMSG, m_tid, NULL, m_message, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001148 m_result = false;
1149 else
1150 m_result = true;
1151}
1152
1153//------------------------------------------------------------------------------
Ed Maste263c9282014-03-17 17:45:53 +00001154/// @class DetachOperation
1155/// @brief Implements ProcessMonitor::Detach.
Greg Clayton28041352011-11-29 20:50:10 +00001156class DetachOperation : public Operation
1157{
1158public:
Matt Kopec085d6ce2013-05-31 22:00:07 +00001159 DetachOperation(lldb::tid_t tid, Error &result) : m_tid(tid), m_error(result) { }
Greg Clayton28041352011-11-29 20:50:10 +00001160
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001161 void Execute(ProcessMonitor *monitor) override;
Greg Clayton28041352011-11-29 20:50:10 +00001162
1163private:
Matt Kopec085d6ce2013-05-31 22:00:07 +00001164 lldb::tid_t m_tid;
Greg Clayton28041352011-11-29 20:50:10 +00001165 Error &m_error;
1166};
1167
1168void
1169DetachOperation::Execute(ProcessMonitor *monitor)
1170{
Matt Kopec085d6ce2013-05-31 22:00:07 +00001171 if (ptrace(PT_DETACH, m_tid, NULL, 0) < 0)
Greg Clayton28041352011-11-29 20:50:10 +00001172 m_error.SetErrorToErrno();
Greg Clayton28041352011-11-29 20:50:10 +00001173}
1174
Johnny Chen25e68e32011-06-14 19:19:50 +00001175ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
1176 : m_monitor(monitor)
1177{
1178 sem_init(&m_semaphore, 0, 0);
1179}
1180
1181ProcessMonitor::OperationArgs::~OperationArgs()
1182{
1183 sem_destroy(&m_semaphore);
1184}
1185
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001186ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
1187 lldb_private::Module *module,
1188 char const **argv,
1189 char const **envp,
1190 const char *stdin_path,
1191 const char *stdout_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001192 const char *stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001193 const char *working_dir,
1194 const lldb_private::ProcessLaunchInfo &launch_info)
Johnny Chen25e68e32011-06-14 19:19:50 +00001195 : OperationArgs(monitor),
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001196 m_module(module),
1197 m_argv(argv),
1198 m_envp(envp),
1199 m_stdin_path(stdin_path),
1200 m_stdout_path(stdout_path),
Daniel Malea6217d2a2013-01-08 14:49:22 +00001201 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001202 m_working_dir(working_dir),
1203 m_launch_info(launch_info)
1204{
1205}
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001206
1207ProcessMonitor::LaunchArgs::~LaunchArgs()
Johnny Chen25e68e32011-06-14 19:19:50 +00001208{ }
1209
1210ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
1211 lldb::pid_t pid)
1212 : OperationArgs(monitor), m_pid(pid) { }
1213
1214ProcessMonitor::AttachArgs::~AttachArgs()
1215{ }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001216
1217//------------------------------------------------------------------------------
1218/// The basic design of the ProcessMonitor is built around two threads.
1219///
1220/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
1221/// for changes in the debugee state. When a change is detected a
1222/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
1223/// "drives" state changes in the debugger.
1224///
1225/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +00001226/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001227/// operations such as register reads/writes, stepping, etc. See the comments
1228/// on the Operation class for more info as to why this is needed.
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001229ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001230 Module *module,
1231 const char *argv[],
1232 const char *envp[],
1233 const char *stdin_path,
1234 const char *stdout_path,
1235 const char *stderr_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001236 const char *working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001237 const lldb_private::ProcessLaunchInfo &launch_info,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001238 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001239 : m_process(static_cast<ProcessLinux *>(process)),
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001240 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +00001241 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001242 m_pid(LLDB_INVALID_PROCESS_ID),
1243 m_terminal_fd(-1),
Daniel Malea1efb4182013-09-16 23:12:18 +00001244 m_operation(0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001245{
Daniel Malea1efb4182013-09-16 23:12:18 +00001246 std::unique_ptr<LaunchArgs> args(new LaunchArgs(this, module, argv, envp,
1247 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001248 working_dir, launch_info));
Stephen Wilson57740ec2011-01-15 00:12:41 +00001249
Daniel Malea1efb4182013-09-16 23:12:18 +00001250 sem_init(&m_operation_pending, 0, 0);
1251 sem_init(&m_operation_done, 0, 0);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001252
Johnny Chen25e68e32011-06-14 19:19:50 +00001253 StartLaunchOpThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001254 if (!error.Success())
1255 return;
1256
1257WAIT_AGAIN:
1258 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +00001259 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001260 {
1261 if (errno == EINTR)
1262 goto WAIT_AGAIN;
1263 else
1264 {
1265 error.SetErrorToErrno();
1266 return;
1267 }
1268 }
1269
1270 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +00001271 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001272 {
Greg Clayton743ecf42012-10-16 20:20:18 +00001273 StopOpThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +00001274 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001275 return;
1276 }
1277
1278 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +00001279 m_monitor_thread = Host::StartMonitoringChildProcess(
1280 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001281 if (!m_monitor_thread.IsJoinable())
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001282 {
1283 error.SetErrorToGenericError();
1284 error.SetErrorString("Process launch failed.");
1285 return;
1286 }
1287}
1288
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001289ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen25e68e32011-06-14 19:19:50 +00001290 lldb::pid_t pid,
1291 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001292 : m_process(static_cast<ProcessLinux *>(process)),
Johnny Chen25e68e32011-06-14 19:19:50 +00001293 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +00001294 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Johnny Chen25e68e32011-06-14 19:19:50 +00001295 m_pid(LLDB_INVALID_PROCESS_ID),
1296 m_terminal_fd(-1),
Daniel Malea1efb4182013-09-16 23:12:18 +00001297 m_operation(0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001298{
Daniel Malea1efb4182013-09-16 23:12:18 +00001299 sem_init(&m_operation_pending, 0, 0);
1300 sem_init(&m_operation_done, 0, 0);
Johnny Chen25e68e32011-06-14 19:19:50 +00001301
Daniel Malea1efb4182013-09-16 23:12:18 +00001302 std::unique_ptr<AttachArgs> args(new AttachArgs(this, pid));
Johnny Chen25e68e32011-06-14 19:19:50 +00001303
1304 StartAttachOpThread(args.get(), error);
1305 if (!error.Success())
1306 return;
1307
1308WAIT_AGAIN:
1309 // Wait for the operation thread to initialize.
1310 if (sem_wait(&args->m_semaphore))
1311 {
1312 if (errno == EINTR)
1313 goto WAIT_AGAIN;
1314 else
1315 {
1316 error.SetErrorToErrno();
1317 return;
1318 }
1319 }
1320
Greg Clayton743ecf42012-10-16 20:20:18 +00001321 // Check that the attach was a success.
Johnny Chen25e68e32011-06-14 19:19:50 +00001322 if (!args->m_error.Success())
1323 {
Greg Clayton743ecf42012-10-16 20:20:18 +00001324 StopOpThread();
Johnny Chen25e68e32011-06-14 19:19:50 +00001325 error = args->m_error;
1326 return;
1327 }
1328
1329 // Finally, start monitoring the child process for change in state.
1330 m_monitor_thread = Host::StartMonitoringChildProcess(
1331 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Zachary Turneracee96a2014-09-23 18:32:09 +00001332 if (!m_monitor_thread.IsJoinable())
Johnny Chen25e68e32011-06-14 19:19:50 +00001333 {
1334 error.SetErrorToGenericError();
1335 error.SetErrorString("Process attach failed.");
1336 return;
1337 }
1338}
1339
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001340ProcessMonitor::~ProcessMonitor()
1341{
Stephen Wilson84ffe702011-03-30 15:55:52 +00001342 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001343}
1344
1345//------------------------------------------------------------------------------
1346// Thread setup and tear down.
1347void
Johnny Chen25e68e32011-06-14 19:19:50 +00001348ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001349{
1350 static const char *g_thread_name = "lldb.process.linux.operation";
1351
Zachary Turneracee96a2014-09-23 18:32:09 +00001352 if (m_operation_thread.IsJoinable())
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001353 return;
1354
Zachary Turner39de3112014-09-09 20:54:56 +00001355 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001356}
1357
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001358void *
Johnny Chen25e68e32011-06-14 19:19:50 +00001359ProcessMonitor::LaunchOpThread(void *arg)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001360{
1361 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1362
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001363 if (!Launch(args)) {
1364 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001365 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001366 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001367
Stephen Wilson570243b2011-01-19 01:37:06 +00001368 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001369 return NULL;
1370}
1371
1372bool
1373ProcessMonitor::Launch(LaunchArgs *args)
1374{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001375 assert (args && "null args");
1376 if (!args)
1377 return false;
1378
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001379 ProcessMonitor *monitor = args->m_monitor;
1380 ProcessLinux &process = monitor->GetProcess();
1381 const char **argv = args->m_argv;
1382 const char **envp = args->m_envp;
1383 const char *stdin_path = args->m_stdin_path;
1384 const char *stdout_path = args->m_stdout_path;
1385 const char *stderr_path = args->m_stderr_path;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001386 const char *working_dir = args->m_working_dir;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001387
1388 lldb_utility::PseudoTerminal terminal;
1389 const size_t err_len = 1024;
1390 char err_str[err_len];
1391 lldb::pid_t pid;
1392
1393 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001394 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001395
Stephen Wilson57740ec2011-01-15 00:12:41 +00001396 // Propagate the environment if one is not supplied.
1397 if (envp == NULL || envp[0] == NULL)
1398 envp = const_cast<const char **>(environ);
1399
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001400 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t>(-1))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001401 {
1402 args->m_error.SetErrorToGenericError();
1403 args->m_error.SetErrorString("Process fork failed.");
1404 goto FINISH;
1405 }
1406
Peter Collingbourne6a520222011-06-14 03:55:58 +00001407 // Recognized child exit status codes.
1408 enum {
1409 ePtraceFailed = 1,
1410 eDupStdinFailed,
1411 eDupStdoutFailed,
1412 eDupStderrFailed,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001413 eChdirFailed,
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001414 eExecFailed,
1415 eSetGidFailed
Peter Collingbourne6a520222011-06-14 03:55:58 +00001416 };
1417
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001418 // Child process.
1419 if (pid == 0)
1420 {
1421 // Trace this process.
Matt Kopec7de48462013-03-06 17:20:48 +00001422 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL, 0) < 0)
Peter Collingbourne6a520222011-06-14 03:55:58 +00001423 exit(ePtraceFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001424
Pavel Labath493c3a12015-02-04 10:36:57 +00001425 // terminal has already dupped the tty descriptors to stdin/out/err.
1426 // This closes original fd from which they were copied (and avoids
1427 // leaking descriptors to the debugged process.
1428 terminal.CloseSlaveFileDescriptor();
1429
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001430 // Do not inherit setgid powers.
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001431 if (setgid(getgid()) != 0)
1432 exit(eSetGidFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001433
1434 // Let us have our own process group.
1435 setpgid(0, 0);
1436
Greg Clayton710dd5a2011-01-08 20:28:42 +00001437 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001438 //
1439 // FIXME: If two or more of the paths are the same we needlessly open
1440 // the same file multiple times.
1441 if (stdin_path != NULL && stdin_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001442 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001443 exit(eDupStdinFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001444
1445 if (stdout_path != NULL && stdout_path[0])
1446 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001447 exit(eDupStdoutFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001448
1449 if (stderr_path != NULL && stderr_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001450 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001451 exit(eDupStderrFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001452
Daniel Malea6217d2a2013-01-08 14:49:22 +00001453 // Change working directory
1454 if (working_dir != NULL && working_dir[0])
1455 if (0 != ::chdir(working_dir))
1456 exit(eChdirFailed);
1457
Todd Fiala0bce1b62014-08-17 00:10:50 +00001458 // Disable ASLR if requested.
1459 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1460 {
1461 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1462 if (old_personality == -1)
1463 {
1464 if (log)
1465 log->Printf ("ProcessMonitor::%s retrieval of Linux personality () failed: %s. Cannot disable ASLR.", __FUNCTION__, strerror (errno));
1466 }
1467 else
1468 {
1469 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1470 if (new_personality == -1)
1471 {
1472 if (log)
1473 log->Printf ("ProcessMonitor::%s setting of Linux personality () to disable ASLR failed, ignoring: %s", __FUNCTION__, strerror (errno));
1474
1475 }
1476 else
1477 {
1478 if (log)
Todd Fiala850f9a22014-09-19 18:27:45 +00001479 log->Printf ("ProcessMonitor::%s disabling ASLR: SUCCESS", __FUNCTION__);
Todd Fiala0bce1b62014-08-17 00:10:50 +00001480
1481 }
1482 }
1483 }
1484
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001485 // Execute. We should never return.
1486 execve(argv[0],
1487 const_cast<char *const *>(argv),
1488 const_cast<char *const *>(envp));
Peter Collingbourne6a520222011-06-14 03:55:58 +00001489 exit(eExecFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001490 }
1491
1492 // Wait for the child process to to trap on its call to execve.
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001493 lldb::pid_t wpid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001494 ::pid_t raw_pid;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001495 int status;
Todd Fialaaf245d12014-06-30 21:05:18 +00001496
1497 raw_pid = waitpid(pid, &status, 0);
1498 wpid = static_cast <lldb::pid_t> (raw_pid);
1499 if (raw_pid < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001500 {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001501 args->m_error.SetErrorToErrno();
1502 goto FINISH;
1503 }
Peter Collingbourne6a520222011-06-14 03:55:58 +00001504 else if (WIFEXITED(status))
1505 {
1506 // open, dup or execve likely failed for some reason.
1507 args->m_error.SetErrorToGenericError();
1508 switch (WEXITSTATUS(status))
1509 {
Greg Clayton542e4072012-09-07 17:49:29 +00001510 case ePtraceFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001511 args->m_error.SetErrorString("Child ptrace failed.");
1512 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001513 case eDupStdinFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001514 args->m_error.SetErrorString("Child open stdin failed.");
1515 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001516 case eDupStdoutFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001517 args->m_error.SetErrorString("Child open stdout failed.");
1518 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001519 case eDupStderrFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001520 args->m_error.SetErrorString("Child open stderr failed.");
1521 break;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001522 case eChdirFailed:
1523 args->m_error.SetErrorString("Child failed to set working directory.");
1524 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001525 case eExecFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001526 args->m_error.SetErrorString("Child exec failed.");
1527 break;
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001528 case eSetGidFailed:
1529 args->m_error.SetErrorString("Child setgid failed.");
1530 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001531 default:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001532 args->m_error.SetErrorString("Child returned unknown exit status.");
1533 break;
1534 }
1535 goto FINISH;
1536 }
1537 assert(WIFSTOPPED(status) && wpid == pid &&
1538 "Could not sync with inferior process.");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001539
Matt Kopec085d6ce2013-05-31 22:00:07 +00001540 if (!SetDefaultPtraceOpts(pid))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001541 {
1542 args->m_error.SetErrorToErrno();
1543 goto FINISH;
1544 }
1545
1546 // Release the master terminal descriptor and pass it off to the
1547 // ProcessMonitor instance. Similarly stash the inferior pid.
1548 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1549 monitor->m_pid = pid;
1550
Stephen Wilson26977162011-03-23 02:14:42 +00001551 // Set the terminal fd to be in non blocking mode (it simplifies the
1552 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1553 // descriptor to read from).
1554 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1555 goto FINISH;
1556
Johnny Chen30213ff2012-01-05 19:17:38 +00001557 // Update the process thread list with this new thread.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001558 // FIXME: should we be letting UpdateThreadList handle this?
1559 // FIXME: by using pids instead of tids, we can only support one thread.
Michael Sartain9f822cd2013-07-31 23:27:46 +00001560 inferior.reset(process.CreateNewPOSIXThread(process, pid));
Matt Kopecfb6ab542013-07-10 20:53:11 +00001561
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001562 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001563 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001564 process.GetThreadList().AddThread(inferior);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001565
Matt Kopecb2910442013-07-09 15:09:45 +00001566 process.AddThreadForInitialStopIfNeeded(pid);
1567
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001568 // Let our process instance know the thread has stopped.
1569 process.SendMessage(ProcessMessage::Trace(pid));
1570
1571FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001572 return args->m_error.Success();
1573}
1574
Johnny Chen25e68e32011-06-14 19:19:50 +00001575void
1576ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1577{
1578 static const char *g_thread_name = "lldb.process.linux.operation";
1579
Zachary Turneracee96a2014-09-23 18:32:09 +00001580 if (m_operation_thread.IsJoinable())
Johnny Chen25e68e32011-06-14 19:19:50 +00001581 return;
1582
Zachary Turner39de3112014-09-09 20:54:56 +00001583 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
Johnny Chen25e68e32011-06-14 19:19:50 +00001584}
1585
Johnny Chen25e68e32011-06-14 19:19:50 +00001586void *
1587ProcessMonitor::AttachOpThread(void *arg)
1588{
1589 AttachArgs *args = static_cast<AttachArgs*>(arg);
1590
Greg Clayton743ecf42012-10-16 20:20:18 +00001591 if (!Attach(args)) {
1592 sem_post(&args->m_semaphore);
Johnny Chen25e68e32011-06-14 19:19:50 +00001593 return NULL;
Greg Clayton743ecf42012-10-16 20:20:18 +00001594 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001595
1596 ServeOperation(args);
1597 return NULL;
1598}
1599
1600bool
1601ProcessMonitor::Attach(AttachArgs *args)
1602{
1603 lldb::pid_t pid = args->m_pid;
1604
1605 ProcessMonitor *monitor = args->m_monitor;
1606 ProcessLinux &process = monitor->GetProcess();
Johnny Chen25e68e32011-06-14 19:19:50 +00001607 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001608 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen25e68e32011-06-14 19:19:50 +00001609
Matt Kopec085d6ce2013-05-31 22:00:07 +00001610 // Use a map to keep track of the threads which we have attached/need to attach.
1611 Host::TidMap tids_to_attach;
Johnny Chen25e68e32011-06-14 19:19:50 +00001612 if (pid <= 1)
1613 {
1614 args->m_error.SetErrorToGenericError();
1615 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1616 goto FINISH;
1617 }
1618
Matt Kopec085d6ce2013-05-31 22:00:07 +00001619 while (Host::FindProcessThreads(pid, tids_to_attach))
Johnny Chen25e68e32011-06-14 19:19:50 +00001620 {
Matt Kopec085d6ce2013-05-31 22:00:07 +00001621 for (Host::TidMap::iterator it = tids_to_attach.begin();
1622 it != tids_to_attach.end(); ++it)
1623 {
1624 if (it->second == false)
1625 {
1626 lldb::tid_t tid = it->first;
1627
1628 // Attach to the requested process.
1629 // An attach will cause the thread to stop with a SIGSTOP.
1630 if (PTRACE(PTRACE_ATTACH, tid, NULL, NULL, 0) < 0)
1631 {
1632 // No such thread. The thread may have exited.
1633 // More error handling may be needed.
1634 if (errno == ESRCH)
1635 {
1636 tids_to_attach.erase(it);
1637 continue;
1638 }
1639 else
1640 {
1641 args->m_error.SetErrorToErrno();
1642 goto FINISH;
1643 }
1644 }
1645
Todd Fiala9be50492014-07-01 16:30:53 +00001646 ::pid_t wpid;
Matt Kopec085d6ce2013-05-31 22:00:07 +00001647 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1648 // At this point we should have a thread stopped if waitpid succeeds.
Todd Fiala9be50492014-07-01 16:30:53 +00001649 if ((wpid = waitpid(tid, NULL, __WALL)) < 0)
Matt Kopec085d6ce2013-05-31 22:00:07 +00001650 {
1651 // No such thread. The thread may have exited.
1652 // More error handling may be needed.
1653 if (errno == ESRCH)
1654 {
1655 tids_to_attach.erase(it);
1656 continue;
1657 }
1658 else
1659 {
1660 args->m_error.SetErrorToErrno();
1661 goto FINISH;
1662 }
1663 }
1664
1665 if (!SetDefaultPtraceOpts(tid))
1666 {
1667 args->m_error.SetErrorToErrno();
1668 goto FINISH;
1669 }
1670
1671 // Update the process thread list with the attached thread.
Michael Sartain9f822cd2013-07-31 23:27:46 +00001672 inferior.reset(process.CreateNewPOSIXThread(process, tid));
Matt Kopecfb6ab542013-07-10 20:53:11 +00001673
Matt Kopec085d6ce2013-05-31 22:00:07 +00001674 if (log)
1675 log->Printf ("ProcessMonitor::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1676 process.GetThreadList().AddThread(inferior);
1677 it->second = true;
Matt Kopecb2910442013-07-09 15:09:45 +00001678 process.AddThreadForInitialStopIfNeeded(tid);
Matt Kopec085d6ce2013-05-31 22:00:07 +00001679 }
1680 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001681 }
1682
Matt Kopec085d6ce2013-05-31 22:00:07 +00001683 if (tids_to_attach.size() > 0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001684 {
Matt Kopec085d6ce2013-05-31 22:00:07 +00001685 monitor->m_pid = pid;
1686 // Let our process instance know the thread has stopped.
1687 process.SendMessage(ProcessMessage::Trace(pid));
Johnny Chen25e68e32011-06-14 19:19:50 +00001688 }
Matt Kopec085d6ce2013-05-31 22:00:07 +00001689 else
1690 {
1691 args->m_error.SetErrorToGenericError();
1692 args->m_error.SetErrorString("No such process.");
1693 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001694
1695 FINISH:
1696 return args->m_error.Success();
1697}
1698
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001699bool
Matt Kopec085d6ce2013-05-31 22:00:07 +00001700ProcessMonitor::SetDefaultPtraceOpts(lldb::pid_t pid)
1701{
1702 long ptrace_opts = 0;
1703
1704 // Have the child raise an event on exit. This is used to keep the child in
1705 // limbo until it is destroyed.
1706 ptrace_opts |= PTRACE_O_TRACEEXIT;
1707
1708 // Have the tracer trace threads which spawn in the inferior process.
1709 // TODO: if we want to support tracing the inferiors' child, add the
1710 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1711 ptrace_opts |= PTRACE_O_TRACECLONE;
1712
1713 // Have the tracer notify us before execve returns
1714 // (needed to disable legacy SIGTRAP generation)
1715 ptrace_opts |= PTRACE_O_TRACEEXEC;
1716
1717 return PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)ptrace_opts, 0) >= 0;
1718}
1719
1720bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001721ProcessMonitor::MonitorCallback(void *callback_baton,
1722 lldb::pid_t pid,
Peter Collingbourne2c67b9a2011-11-21 00:10:19 +00001723 bool exited,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001724 int signal,
1725 int status)
1726{
1727 ProcessMessage message;
1728 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001729 ProcessLinux *process = monitor->m_process;
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001730 assert(process);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001731 bool stop_monitoring;
1732 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001733 int ptrace_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001734
Andrew Kaylor93132f52013-05-28 23:04:25 +00001735 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1736
1737 if (exited)
1738 {
1739 if (log)
1740 log->Printf ("ProcessMonitor::%s() got exit signal, tid = %" PRIu64, __FUNCTION__, pid);
1741 message = ProcessMessage::Exit(pid, status);
1742 process->SendMessage(message);
1743 return pid == process->GetID();
1744 }
1745
Daniel Maleaa35970a2012-11-23 18:09:58 +00001746 if (!monitor->GetSignalInfo(pid, &info, ptrace_err)) {
1747 if (ptrace_err == EINVAL) {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001748 if (log)
1749 log->Printf ("ProcessMonitor::%s() resuming from group-stop", __FUNCTION__);
Daniel Maleaa35970a2012-11-23 18:09:58 +00001750 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1751 if (!monitor->Resume(pid, SIGSTOP)) {
1752 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1753 }
1754 stop_monitoring = false;
1755 } else {
1756 // ptrace(GETSIGINFO) failed (but not due to group-stop). Most likely,
1757 // this means the child pid is gone (or not being debugged) therefore
Andrew Kaylor93132f52013-05-28 23:04:25 +00001758 // stop the monitor thread if this is the main pid.
1759 if (log)
1760 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d",
1761 __FUNCTION__, strerror(ptrace_err), pid, signal, status);
1762 stop_monitoring = pid == monitor->m_process->GetID();
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +00001763 // If we are going to stop monitoring, we need to notify our process object
1764 if (stop_monitoring)
1765 {
1766 message = ProcessMessage::Exit(pid, status);
1767 process->SendMessage(message);
1768 }
Daniel Maleaa35970a2012-11-23 18:09:58 +00001769 }
1770 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00001771 else {
1772 switch (info.si_signo)
1773 {
1774 case SIGTRAP:
1775 message = MonitorSIGTRAP(monitor, &info, pid);
1776 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001777
Stephen Wilson84ffe702011-03-30 15:55:52 +00001778 default:
1779 message = MonitorSignal(monitor, &info, pid);
1780 break;
1781 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001782
Stephen Wilson84ffe702011-03-30 15:55:52 +00001783 process->SendMessage(message);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001784 stop_monitoring = false;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001785 }
1786
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001787 return stop_monitoring;
1788}
1789
1790ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +00001791ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001792 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001793{
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001794 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001795
Andrew Kaylor93132f52013-05-28 23:04:25 +00001796 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1797
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001798 assert(monitor);
1799 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001800
Stephen Wilson84ffe702011-03-30 15:55:52 +00001801 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001802 {
1803 default:
1804 assert(false && "Unexpected SIGTRAP code!");
1805 break;
1806
Matt Kopeca360d7e2013-05-17 19:27:47 +00001807 // TODO: these two cases are required if we want to support tracing
1808 // of the inferiors' children
1809 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1810 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1811
Matt Kopec650648f2013-01-08 16:30:18 +00001812 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1813 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001814 if (log)
1815 log->Printf ("ProcessMonitor::%s() received thread creation event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
1816
Matt Kopec650648f2013-01-08 16:30:18 +00001817 unsigned long tid = 0;
1818 if (!monitor->GetEventMessage(pid, &tid))
1819 tid = -1;
1820 message = ProcessMessage::NewThread(pid, tid);
1821 break;
1822 }
1823
Matt Kopeca360d7e2013-05-17 19:27:47 +00001824 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Matt Kopec718be872013-10-09 19:39:55 +00001825 if (log)
1826 log->Printf ("ProcessMonitor::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
1827
1828 message = ProcessMessage::Exec(pid);
Matt Kopeca360d7e2013-05-17 19:27:47 +00001829 break;
1830
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001831 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1832 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001833 // The inferior process or one of its threads is about to exit.
1834 // Maintain the process or thread in a state of "limbo" until we are
1835 // explicitly commanded to detach, destroy, resume, etc.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001836 unsigned long data = 0;
1837 if (!monitor->GetEventMessage(pid, &data))
1838 data = -1;
Andrew Kaylor93132f52013-05-28 23:04:25 +00001839 if (log)
Matt Kopecb2910442013-07-09 15:09:45 +00001840 log->Printf ("ProcessMonitor::%s() received limbo event, data = %lx, pid = %" PRIu64, __FUNCTION__, data, pid);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001841 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001842 break;
1843 }
1844
1845 case 0:
1846 case TRAP_TRACE:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001847 if (log)
1848 log->Printf ("ProcessMonitor::%s() received trace event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001849 message = ProcessMessage::Trace(pid);
1850 break;
1851
1852 case SI_KERNEL:
1853 case TRAP_BRKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001854 if (log)
1855 log->Printf ("ProcessMonitor::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001856 message = ProcessMessage::Break(pid);
1857 break;
Matt Kopece9ea0da2013-05-07 19:29:28 +00001858
1859 case TRAP_HWBKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001860 if (log)
1861 log->Printf ("ProcessMonitor::%s() received watchpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Matt Kopece9ea0da2013-05-07 19:29:28 +00001862 message = ProcessMessage::Watch(pid, (lldb::addr_t)info->si_addr);
1863 break;
Matt Kopec4a32bf52013-07-11 20:01:22 +00001864
1865 case SIGTRAP:
1866 case (SIGTRAP | 0x80):
1867 if (log)
1868 log->Printf ("ProcessMonitor::%s() received system call stop event, pid = %" PRIu64, __FUNCTION__, pid);
1869 // Ignore these signals until we know more about them
1870 monitor->Resume(pid, eResumeSignalNone);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001871 }
1872
1873 return message;
1874}
1875
Stephen Wilson84ffe702011-03-30 15:55:52 +00001876ProcessMessage
1877ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001878 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001879{
1880 ProcessMessage message;
1881 int signo = info->si_signo;
1882
Andrew Kaylor93132f52013-05-28 23:04:25 +00001883 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1884
Stephen Wilson84ffe702011-03-30 15:55:52 +00001885 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1886 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1887 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1888 //
1889 // IOW, user generated signals never generate what we consider to be a
1890 // "crash".
1891 //
1892 // Similarly, ACK signals generated by this monitor.
1893 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1894 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001895 if (log)
Matt Kopecef143712013-06-03 18:00:07 +00001896 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
Andrew Kaylor93132f52013-05-28 23:04:25 +00001897 __FUNCTION__,
1898 monitor->m_process->GetUnixSignals().GetSignalAsCString (signo),
1899 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1900 info->si_pid);
1901
Stephen Wilson84ffe702011-03-30 15:55:52 +00001902 if (info->si_pid == getpid())
1903 return ProcessMessage::SignalDelivered(pid, signo);
1904 else
1905 return ProcessMessage::Signal(pid, signo);
1906 }
1907
Andrew Kaylor93132f52013-05-28 23:04:25 +00001908 if (log)
1909 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals().GetSignalAsCString (signo));
1910
Chaoren Lin28e57422015-02-03 01:51:25 +00001911 switch (signo)
1912 {
1913 case SIGSEGV:
1914 case SIGILL:
1915 case SIGFPE:
1916 case SIGBUS:
Stephen Wilson84ffe702011-03-30 15:55:52 +00001917 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
Chaoren Lin28e57422015-02-03 01:51:25 +00001918 const auto reason = GetCrashReason(*info);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001919 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1920 }
1921
1922 // Everything else is "normal" and does not require any special action on
1923 // our part.
1924 return ProcessMessage::Signal(pid, signo);
1925}
1926
Andrew Kaylord4d54992013-09-17 00:30:24 +00001927// On Linux, when a new thread is created, we receive to notifications,
1928// (1) a SIGTRAP|PTRACE_EVENT_CLONE from the main process thread with the
1929// child thread id as additional information, and (2) a SIGSTOP|SI_USER from
1930// the new child thread indicating that it has is stopped because we attached.
1931// We have no guarantee of the order in which these arrive, but we need both
1932// before we are ready to proceed. We currently keep a list of threads which
1933// have sent the initial SIGSTOP|SI_USER event. Then when we receive the
1934// SIGTRAP|PTRACE_EVENT_CLONE notification, if the initial stop has not occurred
1935// we call ProcessMonitor::WaitForInitialTIDStop() to wait for it.
1936
1937bool
1938ProcessMonitor::WaitForInitialTIDStop(lldb::tid_t tid)
1939{
1940 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1941 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001942 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waiting for thread to stop...", __FUNCTION__, tid);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001943
1944 // Wait for the thread to stop
1945 while (true)
1946 {
1947 int status = -1;
1948 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001949 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waitpid...", __FUNCTION__, tid);
Todd Fiala9be50492014-07-01 16:30:53 +00001950 ::pid_t wait_pid = waitpid(tid, &status, __WALL);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001951 if (status == -1)
1952 {
1953 // If we got interrupted by a signal (in our process, not the
1954 // inferior) try again.
1955 if (errno == EINTR)
1956 continue;
1957 else
1958 {
1959 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001960 log->Printf("ProcessMonitor::%s(%" PRIu64 ") waitpid error -- %s", __FUNCTION__, tid, strerror(errno));
Andrew Kaylord4d54992013-09-17 00:30:24 +00001961 return false; // This is bad, but there's nothing we can do.
1962 }
1963 }
1964
1965 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001966 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waitpid, status = %d", __FUNCTION__, tid, status);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001967
Todd Fiala9be50492014-07-01 16:30:53 +00001968 assert(static_cast<lldb::tid_t>(wait_pid) == tid);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001969
1970 siginfo_t info;
1971 int ptrace_err;
1972 if (!GetSignalInfo(wait_pid, &info, ptrace_err))
1973 {
1974 if (log)
1975 {
1976 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed. errno=%d (%s)", __FUNCTION__, ptrace_err, strerror(ptrace_err));
1977 }
1978 return false;
1979 }
1980
1981 // If this is a thread exit, we won't get any more information.
1982 if (WIFEXITED(status))
1983 {
1984 m_process->SendMessage(ProcessMessage::Exit(wait_pid, WEXITSTATUS(status)));
Todd Fiala9be50492014-07-01 16:30:53 +00001985 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Andrew Kaylord4d54992013-09-17 00:30:24 +00001986 return true;
1987 continue;
1988 }
1989
1990 assert(info.si_code == SI_USER);
1991 assert(WSTOPSIG(status) == SIGSTOP);
1992
1993 if (log)
1994 log->Printf ("ProcessMonitor::%s(bp) received thread stop signal", __FUNCTION__);
1995 m_process->AddThreadForInitialStopIfNeeded(wait_pid);
1996 return true;
1997 }
1998 return false;
1999}
2000
Andrew Kaylor93132f52013-05-28 23:04:25 +00002001bool
2002ProcessMonitor::StopThread(lldb::tid_t tid)
2003{
2004 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
2005
2006 // FIXME: Try to use tgkill or tkill
2007 int ret = tgkill(m_pid, tid, SIGSTOP);
2008 if (log)
2009 log->Printf ("ProcessMonitor::%s(bp) stopping thread, tid = %" PRIu64 ", ret = %d", __FUNCTION__, tid, ret);
2010
2011 // This can happen if a thread exited while we were trying to stop it. That's OK.
2012 // We'll get the signal for that later.
2013 if (ret < 0)
2014 return false;
2015
2016 // Wait for the thread to stop
2017 while (true)
2018 {
2019 int status = -1;
2020 if (log)
2021 log->Printf ("ProcessMonitor::%s(bp) waitpid...", __FUNCTION__);
Todd Fiala9be50492014-07-01 16:30:53 +00002022 ::pid_t wait_pid = ::waitpid (-1*getpgid(m_pid), &status, __WALL);
Andrew Kaylor93132f52013-05-28 23:04:25 +00002023 if (log)
Todd Fiala9be50492014-07-01 16:30:53 +00002024 log->Printf ("ProcessMonitor::%s(bp) waitpid, pid = %" PRIu64 ", status = %d",
2025 __FUNCTION__, static_cast<lldb::pid_t>(wait_pid), status);
Andrew Kaylor93132f52013-05-28 23:04:25 +00002026
Todd Fiala9be50492014-07-01 16:30:53 +00002027 if (wait_pid == -1)
Andrew Kaylor93132f52013-05-28 23:04:25 +00002028 {
2029 // If we got interrupted by a signal (in our process, not the
2030 // inferior) try again.
2031 if (errno == EINTR)
2032 continue;
2033 else
2034 return false; // This is bad, but there's nothing we can do.
2035 }
2036
2037 // If this is a thread exit, we won't get any more information.
2038 if (WIFEXITED(status))
2039 {
2040 m_process->SendMessage(ProcessMessage::Exit(wait_pid, WEXITSTATUS(status)));
Todd Fiala9be50492014-07-01 16:30:53 +00002041 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Andrew Kaylor93132f52013-05-28 23:04:25 +00002042 return true;
2043 continue;
2044 }
2045
2046 siginfo_t info;
2047 int ptrace_err;
2048 if (!GetSignalInfo(wait_pid, &info, ptrace_err))
2049 {
Todd Fiala1b0539c2014-01-27 17:03:57 +00002050 // another signal causing a StopAllThreads may have been received
2051 // before wait_pid's group-stop was processed, handle it now
2052 if (ptrace_err == EINVAL)
Andrew Kaylor93132f52013-05-28 23:04:25 +00002053 {
Todd Fiala1b0539c2014-01-27 17:03:57 +00002054 assert(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);
Andrew Kaylor93132f52013-05-28 23:04:25 +00002055
Todd Fiala1b0539c2014-01-27 17:03:57 +00002056 if (log)
2057 log->Printf ("ProcessMonitor::%s() resuming from group-stop", __FUNCTION__);
2058 // inferior process is in 'group-stop', so deliver SIGSTOP signal
2059 if (!Resume(wait_pid, SIGSTOP)) {
2060 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
2061 }
2062 continue;
Andrew Kaylor93132f52013-05-28 23:04:25 +00002063 }
Todd Fiala1b0539c2014-01-27 17:03:57 +00002064
2065 if (log)
2066 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed.", __FUNCTION__);
Andrew Kaylor93132f52013-05-28 23:04:25 +00002067 return false;
2068 }
2069
2070 // Handle events from other threads
2071 if (log)
Todd Fiala9be50492014-07-01 16:30:53 +00002072 log->Printf ("ProcessMonitor::%s(bp) handling event, tid == %" PRIu64,
2073 __FUNCTION__, static_cast<lldb::tid_t>(wait_pid));
Andrew Kaylor93132f52013-05-28 23:04:25 +00002074
2075 ProcessMessage message;
2076 if (info.si_signo == SIGTRAP)
2077 message = MonitorSIGTRAP(this, &info, wait_pid);
2078 else
2079 message = MonitorSignal(this, &info, wait_pid);
2080
2081 POSIXThread *thread = static_cast<POSIXThread*>(m_process->GetThreadList().FindThreadByID(wait_pid).get());
2082
2083 // When a new thread is created, we may get a SIGSTOP for the new thread
2084 // just before we get the SIGTRAP that we use to add the thread to our
2085 // process thread list. We don't need to worry about that signal here.
2086 assert(thread || message.GetKind() == ProcessMessage::eSignalMessage);
2087
2088 if (!thread)
2089 {
2090 m_process->SendMessage(message);
2091 continue;
2092 }
2093
2094 switch (message.GetKind())
2095 {
Saleem Abdulrasool6747c7d2014-07-20 05:28:57 +00002096 case ProcessMessage::eExecMessage:
2097 llvm_unreachable("unexpected message");
Michael Sartainc258b302013-09-18 15:32:06 +00002098 case ProcessMessage::eAttachMessage:
Andrew Kaylor93132f52013-05-28 23:04:25 +00002099 case ProcessMessage::eInvalidMessage:
2100 break;
2101
2102 // These need special handling because we don't want to send a
2103 // resume even if we already sent a SIGSTOP to this thread. In
2104 // this case the resume will cause the thread to disappear. It is
2105 // unlikely that we'll ever get eExitMessage here, but the same
2106 // reasoning applies.
2107 case ProcessMessage::eLimboMessage:
2108 case ProcessMessage::eExitMessage:
2109 if (log)
2110 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
2111 // SendMessage will set the thread state as needed.
2112 m_process->SendMessage(message);
2113 // If this is the thread we're waiting for, stop waiting. Even
2114 // though this wasn't the signal we expected, it's the last
2115 // signal we'll see while this thread is alive.
Todd Fiala9be50492014-07-01 16:30:53 +00002116 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Andrew Kaylor93132f52013-05-28 23:04:25 +00002117 return true;
2118 break;
2119
Matt Kopecb2910442013-07-09 15:09:45 +00002120 case ProcessMessage::eSignalMessage:
2121 if (log)
2122 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
2123 if (WSTOPSIG(status) == SIGSTOP)
2124 {
2125 m_process->AddThreadForInitialStopIfNeeded(tid);
2126 thread->SetState(lldb::eStateStopped);
2127 }
2128 else
2129 {
2130 m_process->SendMessage(message);
2131 // This isn't the stop we were expecting, but the thread is
2132 // stopped. SendMessage will handle processing of this event,
2133 // but we need to resume here to get the stop we are waiting
2134 // for (otherwise the thread will stop again immediately when
2135 // we try to resume).
Todd Fiala9be50492014-07-01 16:30:53 +00002136 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Matt Kopecb2910442013-07-09 15:09:45 +00002137 Resume(wait_pid, eResumeSignalNone);
2138 }
2139 break;
2140
Andrew Kaylor93132f52013-05-28 23:04:25 +00002141 case ProcessMessage::eSignalDeliveredMessage:
2142 // This is the stop we're expecting.
Todd Fiala9be50492014-07-01 16:30:53 +00002143 if (static_cast<lldb::tid_t>(wait_pid) == tid &&
2144 WIFSTOPPED(status) &&
2145 WSTOPSIG(status) == SIGSTOP &&
2146 info.si_code == SI_TKILL)
Andrew Kaylor93132f52013-05-28 23:04:25 +00002147 {
2148 if (log)
2149 log->Printf ("ProcessMonitor::%s(bp) received signal, done waiting", __FUNCTION__);
2150 thread->SetState(lldb::eStateStopped);
2151 return true;
2152 }
2153 // else fall-through
Andrew Kaylor93132f52013-05-28 23:04:25 +00002154 case ProcessMessage::eBreakpointMessage:
2155 case ProcessMessage::eTraceMessage:
2156 case ProcessMessage::eWatchpointMessage:
2157 case ProcessMessage::eCrashMessage:
2158 case ProcessMessage::eNewThreadMessage:
2159 if (log)
2160 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
2161 // SendMessage will set the thread state as needed.
2162 m_process->SendMessage(message);
2163 // This isn't the stop we were expecting, but the thread is
2164 // stopped. SendMessage will handle processing of this event,
2165 // but we need to resume here to get the stop we are waiting
2166 // for (otherwise the thread will stop again immediately when
2167 // we try to resume).
Todd Fiala9be50492014-07-01 16:30:53 +00002168 if (static_cast<lldb::tid_t>(wait_pid) == tid)
Andrew Kaylor93132f52013-05-28 23:04:25 +00002169 Resume(wait_pid, eResumeSignalNone);
2170 break;
2171 }
2172 }
2173 return false;
2174}
2175
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002176void
Johnny Chen25e68e32011-06-14 19:19:50 +00002177ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002178{
Stephen Wilson570243b2011-01-19 01:37:06 +00002179 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002180
Stephen Wilson570243b2011-01-19 01:37:06 +00002181 // We are finised with the arguments and are ready to go. Sync with the
2182 // parent thread and start serving operations on the inferior.
2183 sem_post(&args->m_semaphore);
2184
Michael Sartain704bf892013-10-09 01:28:57 +00002185 for(;;)
2186 {
Daniel Malea1efb4182013-09-16 23:12:18 +00002187 // wait for next pending operation
Todd Fiala8ce3dee2014-01-24 22:59:22 +00002188 if (sem_wait(&monitor->m_operation_pending))
2189 {
2190 if (errno == EINTR)
2191 continue;
2192 assert(false && "Unexpected errno from sem_wait");
2193 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002194
Daniel Malea1efb4182013-09-16 23:12:18 +00002195 monitor->m_operation->Execute(monitor);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002196
Daniel Malea1efb4182013-09-16 23:12:18 +00002197 // notify calling thread that operation is complete
2198 sem_post(&monitor->m_operation_done);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002199 }
2200}
2201
2202void
2203ProcessMonitor::DoOperation(Operation *op)
2204{
Daniel Malea1efb4182013-09-16 23:12:18 +00002205 Mutex::Locker lock(m_operation_mutex);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002206
Daniel Malea1efb4182013-09-16 23:12:18 +00002207 m_operation = op;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002208
Daniel Malea1efb4182013-09-16 23:12:18 +00002209 // notify operation thread that an operation is ready to be processed
2210 sem_post(&m_operation_pending);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002211
Daniel Malea1efb4182013-09-16 23:12:18 +00002212 // wait for operation to complete
Todd Fiala8ce3dee2014-01-24 22:59:22 +00002213 while (sem_wait(&m_operation_done))
2214 {
2215 if (errno == EINTR)
2216 continue;
2217 assert(false && "Unexpected errno from sem_wait");
2218 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002219}
2220
2221size_t
2222ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
2223 Error &error)
2224{
2225 size_t result;
2226 ReadOperation op(vm_addr, buf, size, error, result);
2227 DoOperation(&op);
2228 return result;
2229}
2230
2231size_t
2232ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
2233 lldb_private::Error &error)
2234{
2235 size_t result;
2236 WriteOperation op(vm_addr, buf, size, error, result);
2237 DoOperation(&op);
2238 return result;
2239}
2240
2241bool
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002242ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
Matt Kopec7de48462013-03-06 17:20:48 +00002243 unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002244{
2245 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002246 ReadRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002247 DoOperation(&op);
2248 return result;
2249}
2250
Omair Javaidea8c25a802015-05-15 06:29:58 +00002251#if defined (__arm64__) || defined (__aarch64__)
2252
2253bool
2254ProcessMonitor::ReadHardwareDebugInfo (lldb::tid_t tid, unsigned int &watch_count , unsigned int &break_count)
2255{
2256 bool result = true;
2257 ReadDBGROperation op(tid, watch_count, break_count);
2258 DoOperation(&op);
2259 return result;
2260}
2261
2262bool
2263ProcessMonitor::WriteHardwareDebugRegs (lldb::tid_t tid, lldb::addr_t *addr_buf, uint32_t *cntrl_buf, int type, int count)
2264{
2265 bool result = true;
2266 WriteDBGROperation op(tid, addr_buf, cntrl_buf, type, count);
2267 DoOperation(&op);
2268 return result;
2269}
2270
2271#endif
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002272bool
Matt Kopec7de48462013-03-06 17:20:48 +00002273ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002274 const char* reg_name, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002275{
2276 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002277 WriteRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002278 DoOperation(&op);
2279 return result;
2280}
2281
2282bool
Matt Kopec7de48462013-03-06 17:20:48 +00002283ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002284{
2285 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002286 ReadGPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002287 DoOperation(&op);
2288 return result;
2289}
2290
2291bool
Matt Kopec7de48462013-03-06 17:20:48 +00002292ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002293{
2294 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002295 ReadFPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002296 DoOperation(&op);
2297 return result;
2298}
2299
2300bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002301ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2302{
2303 bool result;
2304 ReadRegisterSetOperation op(tid, buf, buf_size, regset, result);
2305 DoOperation(&op);
2306 return result;
2307}
2308
2309bool
Matt Kopec7de48462013-03-06 17:20:48 +00002310ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002311{
2312 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002313 WriteGPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002314 DoOperation(&op);
2315 return result;
2316}
2317
2318bool
Matt Kopec7de48462013-03-06 17:20:48 +00002319ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002320{
2321 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002322 WriteFPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002323 DoOperation(&op);
2324 return result;
2325}
2326
2327bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002328ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2329{
2330 bool result;
2331 WriteRegisterSetOperation op(tid, buf, buf_size, regset, result);
2332 DoOperation(&op);
2333 return result;
2334}
2335
2336bool
Richard Mitton0a558352013-10-17 21:14:00 +00002337ProcessMonitor::ReadThreadPointer(lldb::tid_t tid, lldb::addr_t &value)
2338{
2339 bool result;
2340 ReadThreadPointerOperation op(tid, &value, result);
2341 DoOperation(&op);
2342 return result;
2343}
2344
2345bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002346ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002347{
2348 bool result;
Andrew Kaylor93132f52013-05-28 23:04:25 +00002349 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
2350
2351 if (log)
2352 log->Printf ("ProcessMonitor::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
2353 m_process->GetUnixSignals().GetSignalAsCString (signo));
Stephen Wilson84ffe702011-03-30 15:55:52 +00002354 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002355 DoOperation(&op);
Andrew Kaylor93132f52013-05-28 23:04:25 +00002356 if (log)
2357 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002358 return result;
2359}
2360
2361bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002362ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002363{
2364 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00002365 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002366 DoOperation(&op);
2367 return result;
2368}
2369
2370bool
Ed Maste4e0999b2014-04-01 18:14:06 +00002371ProcessMonitor::Kill()
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002372{
Ed Maste4e0999b2014-04-01 18:14:06 +00002373 return kill(GetPID(), SIGKILL) == 0;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002374}
2375
2376bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00002377ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002378{
2379 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00002380 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002381 DoOperation(&op);
2382 return result;
2383}
2384
2385bool
2386ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2387{
2388 bool result;
2389 EventMessageOperation op(tid, message, result);
2390 DoOperation(&op);
2391 return result;
2392}
2393
Greg Clayton743ecf42012-10-16 20:20:18 +00002394lldb_private::Error
Matt Kopec085d6ce2013-05-31 22:00:07 +00002395ProcessMonitor::Detach(lldb::tid_t tid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002396{
Greg Clayton28041352011-11-29 20:50:10 +00002397 lldb_private::Error error;
Matt Kopec085d6ce2013-05-31 22:00:07 +00002398 if (tid != LLDB_INVALID_THREAD_ID)
2399 {
2400 DetachOperation op(tid, error);
Greg Clayton743ecf42012-10-16 20:20:18 +00002401 DoOperation(&op);
2402 }
Greg Clayton743ecf42012-10-16 20:20:18 +00002403 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00002404}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002405
2406bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002407ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
2408{
Peter Collingbourne62343202011-06-14 03:55:54 +00002409 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002410
2411 if (target_fd == -1)
2412 return false;
2413
Pavel Labath493c3a12015-02-04 10:36:57 +00002414 if (dup2(target_fd, fd) == -1)
2415 return false;
2416
2417 return (close(target_fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002418}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002419
2420void
2421ProcessMonitor::StopMonitoringChildProcess()
2422{
Zachary Turneracee96a2014-09-23 18:32:09 +00002423 if (m_monitor_thread.IsJoinable())
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002424 {
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00002425 ::pthread_kill(m_monitor_thread.GetNativeThread().GetSystemHandle(), SIGUSR1);
Zachary Turner39de3112014-09-09 20:54:56 +00002426 m_monitor_thread.Join(nullptr);
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002427 }
2428}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002429
2430void
2431ProcessMonitor::StopMonitor()
2432{
2433 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00002434 StopOpThread();
Daniel Malea1efb4182013-09-16 23:12:18 +00002435 sem_destroy(&m_operation_pending);
2436 sem_destroy(&m_operation_done);
Pavel Labath3a2da9e2015-02-06 11:32:52 +00002437 if (m_terminal_fd >= 0) {
2438 close(m_terminal_fd);
2439 m_terminal_fd = -1;
2440 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00002441}
2442
2443void
Greg Clayton743ecf42012-10-16 20:20:18 +00002444ProcessMonitor::StopOpThread()
2445{
Zachary Turneracee96a2014-09-23 18:32:09 +00002446 if (!m_operation_thread.IsJoinable())
Greg Clayton743ecf42012-10-16 20:20:18 +00002447 return;
2448
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +00002449 DoOperation(EXIT_OPERATION);
Zachary Turner39de3112014-09-09 20:54:56 +00002450 m_operation_thread.Join(nullptr);
Greg Clayton743ecf42012-10-16 20:20:18 +00002451}