blob: 1cf50453a7488788047b711b3cb11af101b909d7 [file] [log] [blame]
Johnny Chen9ed5b492012-01-05 21:48:15 +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
10// C Includes
11#include <errno.h>
12#include <poll.h>
13#include <string.h>
Ed Mastea02f5532013-07-02 16:45:16 +000014#include <stdint.h>
Johnny Chen9ed5b492012-01-05 21:48:15 +000015#include <unistd.h>
16#include <signal.h>
17#include <sys/ptrace.h>
18#include <sys/socket.h>
19#include <sys/types.h>
20#include <sys/wait.h>
21
22// C++ Includes
23// Other libraries and framework includes
24#include "lldb/Core/Error.h"
25#include "lldb/Core/RegisterValue.h"
26#include "lldb/Core/Scalar.h"
27#include "lldb/Host/Host.h"
28#include "lldb/Target/Thread.h"
29#include "lldb/Target/RegisterContext.h"
30#include "lldb/Utility/PseudoTerminal.h"
31
32
33#include "POSIXThread.h"
34#include "ProcessFreeBSD.h"
35#include "ProcessPOSIXLog.h"
36#include "ProcessMonitor.h"
37
38extern "C" {
39 extern char ** environ;
40 }
41
42using namespace lldb;
43using namespace lldb_private;
44
45// We disable the tracing of ptrace calls for integration builds to
46// avoid the additional indirection and checks.
47#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
48// Wrapper for ptrace to catch errors and log calls.
49
50const char *
51Get_PT_IO_OP(int op)
52{
53 switch (op) {
54 case PIOD_READ_D: return "READ_D";
55 case PIOD_WRITE_D: return "WRITE_D";
56 case PIOD_READ_I: return "READ_I";
57 case PIOD_WRITE_I: return "WRITE_I";
58 default: return "Unknown op";
59 }
60}
61
Matt Kopec7de48462013-03-06 17:20:48 +000062// Wrapper for ptrace to catch errors and log calls.
63// Note that ptrace sets errno on error because -1 is reserved as a valid result.
Johnny Chen9ed5b492012-01-05 21:48:15 +000064extern long
Matt Kopec58c0b962013-03-20 20:34:35 +000065PtraceWrapper(int req, lldb::pid_t pid, void *addr, int data,
Johnny Chen9ed5b492012-01-05 21:48:15 +000066 const char* reqName, const char* file, int line)
67{
68 long int result;
69
Ashok Thirumurthi01186352013-03-28 16:02:31 +000070 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Johnny Chen9ed5b492012-01-05 21:48:15 +000071
72 if (log) {
Ed Mastea708a362013-06-25 14:47:45 +000073 log->Printf("ptrace(%s, %lu, %p, %x) called from file %s line %d",
Johnny Chen9ed5b492012-01-05 21:48:15 +000074 reqName, pid, addr, data, file, line);
75 if (req == PT_IO) {
76 struct ptrace_io_desc *pi = (struct ptrace_io_desc *) addr;
77
78 log->Printf("PT_IO: op=%s offs=%zx size=%ld",
Ed Mastea708a362013-06-25 14:47:45 +000079 Get_PT_IO_OP(pi->piod_op), (size_t)pi->piod_offs, pi->piod_len);
Johnny Chen9ed5b492012-01-05 21:48:15 +000080 }
81 }
82
83 //PtraceDisplayBytes(req, data);
84
85 errno = 0;
Matt Kopecc6672c82013-03-15 20:00:39 +000086 result = ptrace(req, pid, (caddr_t) addr, data);
Johnny Chen9ed5b492012-01-05 21:48:15 +000087
88 //PtraceDisplayBytes(req, data);
89
Matt Kopec7de48462013-03-06 17:20:48 +000090 if (log && errno != 0)
Johnny Chen9ed5b492012-01-05 21:48:15 +000091 {
92 const char* str;
93 switch (errno)
94 {
95 case ESRCH: str = "ESRCH"; break;
96 case EINVAL: str = "EINVAL"; break;
97 case EBUSY: str = "EBUSY"; break;
98 case EPERM: str = "EPERM"; break;
99 default: str = "<unknown>";
100 }
101 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
102 }
103
Ed Maste7d4c0d5b2013-07-22 20:51:08 +0000104#ifdef __amd64__
Johnny Chen9ed5b492012-01-05 21:48:15 +0000105 if (log) {
106 if (req == PT_GETREGS) {
107 struct reg *r = (struct reg *) addr;
108
109 log->Printf("PT_GETREGS: ip=0x%lx", r->r_rip);
110 log->Printf("PT_GETREGS: sp=0x%lx", r->r_rsp);
111 log->Printf("PT_GETREGS: bp=0x%lx", r->r_rbp);
112 log->Printf("PT_GETREGS: ax=0x%lx", r->r_rax);
113 }
114 }
Ed Maste7d4c0d5b2013-07-22 20:51:08 +0000115#endif
Johnny Chen9ed5b492012-01-05 21:48:15 +0000116
117 return result;
118}
119
Matt Kopec7de48462013-03-06 17:20:48 +0000120// Wrapper for ptrace when logging is not required.
121// Sets errno to 0 prior to calling ptrace.
122extern long
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000123PtraceWrapper(int req, lldb::pid_t pid, void *addr, int data)
Matt Kopec7de48462013-03-06 17:20:48 +0000124{
125 long result = 0;
126 errno = 0;
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000127 result = ptrace(req, pid, (caddr_t)addr, data);
Matt Kopec7de48462013-03-06 17:20:48 +0000128 return result;
129}
130
Johnny Chen9ed5b492012-01-05 21:48:15 +0000131#define PTRACE(req, pid, addr, data) \
132 PtraceWrapper((req), (pid), (addr), (data), #req, __FILE__, __LINE__)
133#else
Matt Kopec7de48462013-03-06 17:20:48 +0000134 PtraceWrapper((req), (pid), (addr), (data))
Johnny Chen9ed5b492012-01-05 21:48:15 +0000135#endif
136
137//------------------------------------------------------------------------------
138// Static implementations of ProcessMonitor::ReadMemory and
139// ProcessMonitor::WriteMemory. This enables mutual recursion between these
140// functions without needed to go thru the thread funnel.
141
142static size_t
143DoReadMemory(lldb::pid_t pid, lldb::addr_t vm_addr, void *buf, size_t size,
144 Error &error)
145{
146 struct ptrace_io_desc pi_desc;
147
148 pi_desc.piod_op = PIOD_READ_D;
149 pi_desc.piod_offs = (void *)vm_addr;
150 pi_desc.piod_addr = buf;
151 pi_desc.piod_len = size;
152
153 if (PTRACE(PT_IO, pid, (caddr_t)&pi_desc, 0) < 0)
154 error.SetErrorToErrno();
155 return pi_desc.piod_len;
156}
157
158static size_t
159DoWriteMemory(lldb::pid_t pid, lldb::addr_t vm_addr, const void *buf,
160 size_t size, Error &error)
161{
162 struct ptrace_io_desc pi_desc;
163
164 pi_desc.piod_op = PIOD_WRITE_D;
165 pi_desc.piod_offs = (void *)vm_addr;
166 pi_desc.piod_addr = (void *)buf;
167 pi_desc.piod_len = size;
168
169 if (PTRACE(PT_IO, pid, (caddr_t)&pi_desc, 0) < 0)
170 error.SetErrorToErrno();
171 return pi_desc.piod_len;
172}
173
174// Simple helper function to ensure flags are enabled on the given file
175// descriptor.
176static bool
177EnsureFDFlags(int fd, int flags, Error &error)
178{
179 int status;
180
181 if ((status = fcntl(fd, F_GETFL)) == -1)
182 {
183 error.SetErrorToErrno();
184 return false;
185 }
186
187 if (fcntl(fd, F_SETFL, status | flags) == -1)
188 {
189 error.SetErrorToErrno();
190 return false;
191 }
192
193 return true;
194}
195
196//------------------------------------------------------------------------------
197/// @class Operation
198/// @brief Represents a ProcessMonitor operation.
199///
200/// Under FreeBSD, it is not possible to ptrace() from any other thread but the
201/// one that spawned or attached to the process from the start. Therefore, when
202/// a ProcessMonitor is asked to deliver or change the state of an inferior
203/// process the operation must be "funneled" to a specific thread to perform the
204/// task. The Operation class provides an abstract base for all services the
205/// ProcessMonitor must perform via the single virtual function Execute, thus
206/// encapsulating the code that needs to run in the privileged context.
207class Operation
208{
209public:
Ed Maste5a9a6262013-06-24 14:55:03 +0000210 virtual ~Operation() {}
Johnny Chen9ed5b492012-01-05 21:48:15 +0000211 virtual void Execute(ProcessMonitor *monitor) = 0;
212};
213
214//------------------------------------------------------------------------------
215/// @class ReadOperation
216/// @brief Implements ProcessMonitor::ReadMemory.
217class ReadOperation : public Operation
218{
219public:
220 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
221 Error &error, size_t &result)
222 : m_addr(addr), m_buff(buff), m_size(size),
223 m_error(error), m_result(result)
224 { }
225
226 void Execute(ProcessMonitor *monitor);
227
228private:
229 lldb::addr_t m_addr;
230 void *m_buff;
231 size_t m_size;
232 Error &m_error;
233 size_t &m_result;
234};
235
236void
237ReadOperation::Execute(ProcessMonitor *monitor)
238{
239 lldb::pid_t pid = monitor->GetPID();
240
241 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
242}
243
244//------------------------------------------------------------------------------
Ed Mastea56115f2013-07-17 14:30:26 +0000245/// @class WriteOperation
Johnny Chen9ed5b492012-01-05 21:48:15 +0000246/// @brief Implements ProcessMonitor::WriteMemory.
247class WriteOperation : public Operation
248{
249public:
250 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
251 Error &error, size_t &result)
252 : m_addr(addr), m_buff(buff), m_size(size),
253 m_error(error), m_result(result)
254 { }
255
256 void Execute(ProcessMonitor *monitor);
257
258private:
259 lldb::addr_t m_addr;
260 const void *m_buff;
261 size_t m_size;
262 Error &m_error;
263 size_t &m_result;
264};
265
266void
267WriteOperation::Execute(ProcessMonitor *monitor)
268{
269 lldb::pid_t pid = monitor->GetPID();
270
271 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
272}
273
274//------------------------------------------------------------------------------
275/// @class ReadRegOperation
276/// @brief Implements ProcessMonitor::ReadRegisterValue.
277class ReadRegOperation : public Operation
278{
279public:
Ed Maste6f066412013-07-04 21:47:32 +0000280 ReadRegOperation(lldb::tid_t tid, unsigned offset, unsigned size,
281 RegisterValue &value, bool &result)
282 : m_tid(tid), m_offset(offset), m_size(size),
283 m_value(value), m_result(result)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000284 { }
285
286 void Execute(ProcessMonitor *monitor);
287
288private:
Ed Maste6f066412013-07-04 21:47:32 +0000289 lldb::tid_t m_tid;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000290 unsigned m_offset;
291 unsigned m_size;
292 RegisterValue &m_value;
293 bool &m_result;
294};
295
296void
297ReadRegOperation::Execute(ProcessMonitor *monitor)
298{
Johnny Chen9ed5b492012-01-05 21:48:15 +0000299 struct reg regs;
300 int rc;
301
Ed Maste6f066412013-07-04 21:47:32 +0000302 if ((rc = PTRACE(PT_GETREGS, m_tid, (caddr_t)&regs, 0)) < 0) {
Johnny Chen9ed5b492012-01-05 21:48:15 +0000303 m_result = false;
304 } else {
305 if (m_size == sizeof(uintptr_t))
306 m_value = *(uintptr_t *)(((caddr_t)&regs) + m_offset);
307 else
308 memcpy(&m_value, (((caddr_t)&regs) + m_offset), m_size);
309 m_result = true;
310 }
311}
312
313//------------------------------------------------------------------------------
314/// @class WriteRegOperation
315/// @brief Implements ProcessMonitor::WriteRegisterValue.
316class WriteRegOperation : public Operation
317{
318public:
Ed Maste6f066412013-07-04 21:47:32 +0000319 WriteRegOperation(lldb::tid_t tid, unsigned offset,
320 const RegisterValue &value, bool &result)
321 : m_tid(tid), m_offset(offset),
322 m_value(value), m_result(result)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000323 { }
324
325 void Execute(ProcessMonitor *monitor);
326
327private:
Ed Maste6f066412013-07-04 21:47:32 +0000328 lldb::tid_t m_tid;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000329 unsigned m_offset;
330 const RegisterValue &m_value;
331 bool &m_result;
332};
333
334void
335WriteRegOperation::Execute(ProcessMonitor *monitor)
336{
Johnny Chen9ed5b492012-01-05 21:48:15 +0000337 struct reg regs;
338
Ed Maste6f066412013-07-04 21:47:32 +0000339 if (PTRACE(PT_GETREGS, m_tid, (caddr_t)&regs, 0) < 0) {
Johnny Chen9ed5b492012-01-05 21:48:15 +0000340 m_result = false;
341 return;
342 }
343 *(uintptr_t *)(((caddr_t)&regs) + m_offset) = (uintptr_t)m_value.GetAsUInt64();
Ed Maste6f066412013-07-04 21:47:32 +0000344 if (PTRACE(PT_SETREGS, m_tid, (caddr_t)&regs, 0) < 0)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000345 m_result = false;
346 else
347 m_result = true;
348}
349
350//------------------------------------------------------------------------------
351/// @class ReadGPROperation
352/// @brief Implements ProcessMonitor::ReadGPR.
353class ReadGPROperation : public Operation
354{
355public:
Ed Maste6f066412013-07-04 21:47:32 +0000356 ReadGPROperation(lldb::tid_t tid, void *buf, bool &result)
357 : m_tid(tid), m_buf(buf), m_result(result)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000358 { }
359
360 void Execute(ProcessMonitor *monitor);
361
362private:
Ed Maste6f066412013-07-04 21:47:32 +0000363 lldb::tid_t m_tid;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000364 void *m_buf;
365 bool &m_result;
366};
367
368void
369ReadGPROperation::Execute(ProcessMonitor *monitor)
370{
371 int rc;
372
373 errno = 0;
Ed Maste6f066412013-07-04 21:47:32 +0000374 rc = PTRACE(PT_GETREGS, m_tid, (caddr_t)m_buf, 0);
Johnny Chen9ed5b492012-01-05 21:48:15 +0000375 if (errno != 0)
376 m_result = false;
377 else
378 m_result = true;
379}
380
381//------------------------------------------------------------------------------
382/// @class ReadFPROperation
383/// @brief Implements ProcessMonitor::ReadFPR.
384class ReadFPROperation : public Operation
385{
386public:
Ed Maste6f066412013-07-04 21:47:32 +0000387 ReadFPROperation(lldb::tid_t tid, void *buf, bool &result)
388 : m_tid(tid), m_buf(buf), m_result(result)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000389 { }
390
391 void Execute(ProcessMonitor *monitor);
392
393private:
Ed Maste6f066412013-07-04 21:47:32 +0000394 lldb::tid_t m_tid;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000395 void *m_buf;
396 bool &m_result;
397};
398
399void
400ReadFPROperation::Execute(ProcessMonitor *monitor)
401{
Ed Maste6f066412013-07-04 21:47:32 +0000402 if (PTRACE(PT_GETFPREGS, m_tid, (caddr_t)m_buf, 0) < 0)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000403 m_result = false;
404 else
405 m_result = true;
406}
407
408//------------------------------------------------------------------------------
409/// @class WriteGPROperation
410/// @brief Implements ProcessMonitor::WriteGPR.
411class WriteGPROperation : public Operation
412{
413public:
Ed Maste6f066412013-07-04 21:47:32 +0000414 WriteGPROperation(lldb::tid_t tid, void *buf, bool &result)
415 : m_tid(tid), m_buf(buf), m_result(result)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000416 { }
417
418 void Execute(ProcessMonitor *monitor);
419
420private:
Ed Maste6f066412013-07-04 21:47:32 +0000421 lldb::tid_t m_tid;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000422 void *m_buf;
423 bool &m_result;
424};
425
426void
427WriteGPROperation::Execute(ProcessMonitor *monitor)
428{
Ed Maste6f066412013-07-04 21:47:32 +0000429 if (PTRACE(PT_SETREGS, m_tid, (caddr_t)m_buf, 0) < 0)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000430 m_result = false;
431 else
432 m_result = true;
433}
434
435//------------------------------------------------------------------------------
436/// @class WriteFPROperation
437/// @brief Implements ProcessMonitor::WriteFPR.
438class WriteFPROperation : public Operation
439{
440public:
Ed Maste6f066412013-07-04 21:47:32 +0000441 WriteFPROperation(lldb::tid_t tid, void *buf, bool &result)
442 : m_tid(tid), m_buf(buf), m_result(result)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000443 { }
444
445 void Execute(ProcessMonitor *monitor);
446
447private:
Ed Maste6f066412013-07-04 21:47:32 +0000448 lldb::tid_t m_tid;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000449 void *m_buf;
450 bool &m_result;
451};
452
453void
454WriteFPROperation::Execute(ProcessMonitor *monitor)
455{
Ed Maste6f066412013-07-04 21:47:32 +0000456 if (PTRACE(PT_SETFPREGS, m_tid, (caddr_t)m_buf, 0) < 0)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000457 m_result = false;
458 else
459 m_result = true;
460}
461
462//------------------------------------------------------------------------------
463/// @class ResumeOperation
464/// @brief Implements ProcessMonitor::Resume.
465class ResumeOperation : public Operation
466{
467public:
468 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
469 m_tid(tid), m_signo(signo), m_result(result) { }
470
471 void Execute(ProcessMonitor *monitor);
472
473private:
474 lldb::tid_t m_tid;
475 uint32_t m_signo;
476 bool &m_result;
477};
478
479void
480ResumeOperation::Execute(ProcessMonitor *monitor)
481{
482 int data = 0;
483
484 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
485 data = m_signo;
486
487 if (PTRACE(PT_CONTINUE, m_tid, (caddr_t)1, data))
Ed Mastea02f5532013-07-02 16:45:16 +0000488 {
489 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
490
491 if (log)
492 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, strerror(errno));
Johnny Chen9ed5b492012-01-05 21:48:15 +0000493 m_result = false;
Ed Mastea02f5532013-07-02 16:45:16 +0000494 }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000495 else
496 m_result = true;
497}
498
499//------------------------------------------------------------------------------
Ed Maste428a6782013-06-24 15:04:47 +0000500/// @class SingleStepOperation
Johnny Chen9ed5b492012-01-05 21:48:15 +0000501/// @brief Implements ProcessMonitor::SingleStep.
502class SingleStepOperation : public Operation
503{
504public:
505 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
506 : m_tid(tid), m_signo(signo), m_result(result) { }
507
508 void Execute(ProcessMonitor *monitor);
509
510private:
511 lldb::tid_t m_tid;
512 uint32_t m_signo;
513 bool &m_result;
514};
515
516void
517SingleStepOperation::Execute(ProcessMonitor *monitor)
518{
519 int data = 0;
520
521 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
522 data = m_signo;
523
524 if (PTRACE(PT_STEP, m_tid, NULL, data))
525 m_result = false;
526 else
527 m_result = true;
528}
529
530//------------------------------------------------------------------------------
Ed Maste819e3992013-07-17 14:02:20 +0000531/// @class LwpInfoOperation
532/// @brief Implements ProcessMonitor::GetLwpInfo.
533class LwpInfoOperation : public Operation
Johnny Chen9ed5b492012-01-05 21:48:15 +0000534{
535public:
Ed Maste819e3992013-07-17 14:02:20 +0000536 LwpInfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
Daniel Maleaa35970a2012-11-23 18:09:58 +0000537 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000538
539 void Execute(ProcessMonitor *monitor);
540
541private:
542 lldb::tid_t m_tid;
543 void *m_info;
544 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000545 int &m_err;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000546};
547
548void
Ed Maste819e3992013-07-17 14:02:20 +0000549LwpInfoOperation::Execute(ProcessMonitor *monitor)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000550{
551 struct ptrace_lwpinfo plwp;
552
Daniel Maleaa35970a2012-11-23 18:09:58 +0000553 if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp))) {
Johnny Chen9ed5b492012-01-05 21:48:15 +0000554 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000555 m_err = errno;
556 } else {
Ed Maste819e3992013-07-17 14:02:20 +0000557 memcpy(m_info, &plwp, sizeof(plwp));
Johnny Chen9ed5b492012-01-05 21:48:15 +0000558 m_result = true;
559 }
560}
561
562//------------------------------------------------------------------------------
563/// @class EventMessageOperation
564/// @brief Implements ProcessMonitor::GetEventMessage.
565class EventMessageOperation : public Operation
566{
567public:
568 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
569 : m_tid(tid), m_message(message), m_result(result) { }
570
571 void Execute(ProcessMonitor *monitor);
572
573private:
574 lldb::tid_t m_tid;
575 unsigned long *m_message;
576 bool &m_result;
577};
578
579void
580EventMessageOperation::Execute(ProcessMonitor *monitor)
581{
582 struct ptrace_lwpinfo plwp;
583
584 if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp)))
585 m_result = false;
586 else {
587 if (plwp.pl_flags & PL_FLAG_FORKED) {
588 m_message = (unsigned long *)plwp.pl_child_pid;
589 m_result = true;
590 } else
591 m_result = false;
592 }
593}
594
595//------------------------------------------------------------------------------
596/// @class KillOperation
597/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
598class KillOperation : public Operation
599{
600public:
601 KillOperation(bool &result) : m_result(result) { }
602
603 void Execute(ProcessMonitor *monitor);
604
605private:
606 bool &m_result;
607};
608
609void
610KillOperation::Execute(ProcessMonitor *monitor)
611{
612 lldb::pid_t pid = monitor->GetPID();
613
614 if (PTRACE(PT_KILL, pid, NULL, 0))
615 m_result = false;
616 else
617 m_result = true;
618}
619
620//------------------------------------------------------------------------------
Ed Mastea02f5532013-07-02 16:45:16 +0000621/// @class DetachOperation
Johnny Chen9ed5b492012-01-05 21:48:15 +0000622/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
623class DetachOperation : public Operation
624{
625public:
626 DetachOperation(Error &result) : m_error(result) { }
627
628 void Execute(ProcessMonitor *monitor);
629
630private:
631 Error &m_error;
632};
633
634void
635DetachOperation::Execute(ProcessMonitor *monitor)
636{
637 lldb::pid_t pid = monitor->GetPID();
638
639 if (PTRACE(PT_DETACH, pid, NULL, 0) < 0)
640 m_error.SetErrorToErrno();
641
642}
643
644ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
645 : m_monitor(monitor)
646{
647 sem_init(&m_semaphore, 0, 0);
648}
649
650ProcessMonitor::OperationArgs::~OperationArgs()
651{
652 sem_destroy(&m_semaphore);
653}
654
655ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
656 lldb_private::Module *module,
657 char const **argv,
658 char const **envp,
659 const char *stdin_path,
660 const char *stdout_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000661 const char *stderr_path,
662 const char *working_dir)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000663 : OperationArgs(monitor),
664 m_module(module),
665 m_argv(argv),
666 m_envp(envp),
667 m_stdin_path(stdin_path),
668 m_stdout_path(stdout_path),
Daniel Malea6217d2a2013-01-08 14:49:22 +0000669 m_stderr_path(stderr_path),
670 m_working_dir(working_dir) { }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000671
672ProcessMonitor::LaunchArgs::~LaunchArgs()
673{ }
674
675ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
676 lldb::pid_t pid)
677 : OperationArgs(monitor), m_pid(pid) { }
678
679ProcessMonitor::AttachArgs::~AttachArgs()
680{ }
681
682//------------------------------------------------------------------------------
683/// The basic design of the ProcessMonitor is built around two threads.
684///
685/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
686/// for changes in the debugee state. When a change is detected a
687/// ProcessMessage is sent to the associated ProcessFreeBSD instance. This thread
688/// "drives" state changes in the debugger.
689///
690/// The second thread (@see OperationThread) is responsible for two things 1)
691/// launching or attaching to the inferior process, and then 2) servicing
692/// operations such as register reads/writes, stepping, etc. See the comments
693/// on the Operation class for more info as to why this is needed.
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000694ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen9ed5b492012-01-05 21:48:15 +0000695 Module *module,
696 const char *argv[],
697 const char *envp[],
698 const char *stdin_path,
699 const char *stdout_path,
700 const char *stderr_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000701 const char *working_dir,
Johnny Chen9ed5b492012-01-05 21:48:15 +0000702 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000703 : m_process(static_cast<ProcessFreeBSD *>(process)),
Johnny Chen9ed5b492012-01-05 21:48:15 +0000704 m_operation_thread(LLDB_INVALID_HOST_THREAD),
705 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
706 m_pid(LLDB_INVALID_PROCESS_ID),
707 m_server_mutex(Mutex::eMutexTypeRecursive),
708 m_terminal_fd(-1),
709 m_client_fd(-1),
710 m_server_fd(-1)
711{
Greg Clayton7b0992d2013-04-18 22:45:39 +0000712 std::unique_ptr<LaunchArgs> args;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000713
714 args.reset(new LaunchArgs(this, module, argv, envp,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000715 stdin_path, stdout_path, stderr_path, working_dir));
Johnny Chen9ed5b492012-01-05 21:48:15 +0000716
717
718 // Server/client descriptors.
719 if (!EnableIPC())
720 {
721 error.SetErrorToGenericError();
722 error.SetErrorString("Monitor failed to initialize.");
723 }
724
725 StartLaunchOpThread(args.get(), error);
726 if (!error.Success())
727 return;
728
729WAIT_AGAIN:
730 // Wait for the operation thread to initialize.
731 if (sem_wait(&args->m_semaphore))
732 {
733 if (errno == EINTR)
734 goto WAIT_AGAIN;
735 else
736 {
737 error.SetErrorToErrno();
738 return;
739 }
740 }
741
742 // Check that the launch was a success.
743 if (!args->m_error.Success())
744 {
Ed Mastea02f5532013-07-02 16:45:16 +0000745 StopOpThread();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000746 error = args->m_error;
747 return;
748 }
749
750 // Finally, start monitoring the child process for change in state.
751 m_monitor_thread = Host::StartMonitoringChildProcess(
752 ProcessMonitor::MonitorCallback, this, GetPID(), true);
753 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
754 {
755 error.SetErrorToGenericError();
756 error.SetErrorString("Process launch failed.");
757 return;
758 }
759}
760
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000761ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen9ed5b492012-01-05 21:48:15 +0000762 lldb::pid_t pid,
763 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000764 : m_process(static_cast<ProcessFreeBSD *>(process)),
Johnny Chen9ed5b492012-01-05 21:48:15 +0000765 m_operation_thread(LLDB_INVALID_HOST_THREAD),
766 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
767 m_pid(pid),
768 m_server_mutex(Mutex::eMutexTypeRecursive),
769 m_terminal_fd(-1),
770 m_client_fd(-1),
771 m_server_fd(-1)
772{
Greg Clayton7b0992d2013-04-18 22:45:39 +0000773 std::unique_ptr<AttachArgs> args;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000774
775 args.reset(new AttachArgs(this, pid));
776
777 // Server/client descriptors.
778 if (!EnableIPC())
779 {
780 error.SetErrorToGenericError();
781 error.SetErrorString("Monitor failed to initialize.");
782 }
783
784 StartAttachOpThread(args.get(), error);
785 if (!error.Success())
786 return;
787
788WAIT_AGAIN:
789 // Wait for the operation thread to initialize.
790 if (sem_wait(&args->m_semaphore))
791 {
792 if (errno == EINTR)
793 goto WAIT_AGAIN;
794 else
795 {
796 error.SetErrorToErrno();
797 return;
798 }
799 }
800
Ed Mastea02f5532013-07-02 16:45:16 +0000801 // Check that the attach was a success.
Johnny Chen9ed5b492012-01-05 21:48:15 +0000802 if (!args->m_error.Success())
803 {
Ed Mastea02f5532013-07-02 16:45:16 +0000804 StopOpThread();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000805 error = args->m_error;
806 return;
807 }
808
809 // Finally, start monitoring the child process for change in state.
810 m_monitor_thread = Host::StartMonitoringChildProcess(
811 ProcessMonitor::MonitorCallback, this, GetPID(), true);
812 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
813 {
814 error.SetErrorToGenericError();
815 error.SetErrorString("Process attach failed.");
816 return;
817 }
818}
819
820ProcessMonitor::~ProcessMonitor()
821{
822 StopMonitor();
823}
824
825//------------------------------------------------------------------------------
826// Thread setup and tear down.
827void
828ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
829{
830 static const char *g_thread_name = "lldb.process.freebsd.operation";
831
832 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
833 return;
834
835 m_operation_thread =
836 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
837}
838
Johnny Chen9ed5b492012-01-05 21:48:15 +0000839void *
840ProcessMonitor::LaunchOpThread(void *arg)
841{
842 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
843
844 if (!Launch(args)) {
845 sem_post(&args->m_semaphore);
846 return NULL;
847 }
848
849 ServeOperation(args);
850 return NULL;
851}
852
853bool
854ProcessMonitor::Launch(LaunchArgs *args)
855{
856 ProcessMonitor *monitor = args->m_monitor;
857 ProcessFreeBSD &process = monitor->GetProcess();
858 const char **argv = args->m_argv;
859 const char **envp = args->m_envp;
860 const char *stdin_path = args->m_stdin_path;
861 const char *stdout_path = args->m_stdout_path;
862 const char *stderr_path = args->m_stderr_path;
Daniel Malea6217d2a2013-01-08 14:49:22 +0000863 const char *working_dir = args->m_working_dir;
Ed Mastea02f5532013-07-02 16:45:16 +0000864
865 lldb_utility::PseudoTerminal terminal;
866 const size_t err_len = 1024;
867 char err_str[err_len];
Johnny Chen9ed5b492012-01-05 21:48:15 +0000868 lldb::pid_t pid;
869
Johnny Chen9ed5b492012-01-05 21:48:15 +0000870 // Propagate the environment if one is not supplied.
871 if (envp == NULL || envp[0] == NULL)
872 envp = const_cast<const char **>(environ);
873
Ed Mastea02f5532013-07-02 16:45:16 +0000874 // Pseudo terminal setup.
875 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
876 {
877 args->m_error.SetErrorToGenericError();
878 args->m_error.SetErrorString("Could not open controlling TTY.");
879 goto FINISH;
880 }
881
882 if ((pid = terminal.Fork(err_str, err_len)) == -1)
883 {
884 args->m_error.SetErrorToGenericError();
885 args->m_error.SetErrorString("Process fork failed.");
886 goto FINISH;
887 }
888
Johnny Chen9ed5b492012-01-05 21:48:15 +0000889 // Recognized child exit status codes.
890 enum {
891 ePtraceFailed = 1,
892 eDupStdinFailed,
893 eDupStdoutFailed,
894 eDupStderrFailed,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000895 eChdirFailed,
Johnny Chen9ed5b492012-01-05 21:48:15 +0000896 eExecFailed
897 };
898
Johnny Chen9ed5b492012-01-05 21:48:15 +0000899 // Child process.
900 if (pid == 0)
901 {
902 // Trace this process.
903 if (PTRACE(PT_TRACE_ME, 0, NULL, 0) < 0)
904 exit(ePtraceFailed);
905
906 // Do not inherit setgid powers.
907 setgid(getgid());
908
909 // Let us have our own process group.
910 setpgid(0, 0);
911
912 // Dup file descriptors if needed.
913 //
914 // FIXME: If two or more of the paths are the same we needlessly open
915 // the same file multiple times.
916 if (stdin_path != NULL && stdin_path[0])
917 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
918 exit(eDupStdinFailed);
919
920 if (stdout_path != NULL && stdout_path[0])
921 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
922 exit(eDupStdoutFailed);
923
924 if (stderr_path != NULL && stderr_path[0])
925 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
926 exit(eDupStderrFailed);
927
Daniel Malea6217d2a2013-01-08 14:49:22 +0000928 // Change working directory
929 if (working_dir != NULL && working_dir[0])
930 if (0 != ::chdir(working_dir))
931 exit(eChdirFailed);
932
Johnny Chen9ed5b492012-01-05 21:48:15 +0000933 // Execute. We should never return.
934 execve(argv[0],
935 const_cast<char *const *>(argv),
936 const_cast<char *const *>(envp));
937 exit(eExecFailed);
938 }
939
940 // Wait for the child process to to trap on its call to execve.
941 ::pid_t wpid;
942 int status;
943 if ((wpid = waitpid(pid, &status, 0)) < 0)
944 {
945 args->m_error.SetErrorToErrno();
946 goto FINISH;
947 }
948 else if (WIFEXITED(status))
949 {
950 // open, dup or execve likely failed for some reason.
951 args->m_error.SetErrorToGenericError();
952 switch (WEXITSTATUS(status))
953 {
Ed Maste5d34af32013-06-24 15:09:18 +0000954 case ePtraceFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000955 args->m_error.SetErrorString("Child ptrace failed.");
956 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000957 case eDupStdinFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000958 args->m_error.SetErrorString("Child open stdin failed.");
959 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000960 case eDupStdoutFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000961 args->m_error.SetErrorString("Child open stdout failed.");
962 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000963 case eDupStderrFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000964 args->m_error.SetErrorString("Child open stderr failed.");
965 break;
Daniel Malea6217d2a2013-01-08 14:49:22 +0000966 case eChdirFailed:
967 args->m_error.SetErrorString("Child failed to set working directory.");
968 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000969 case eExecFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000970 args->m_error.SetErrorString("Child exec failed.");
971 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000972 default:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000973 args->m_error.SetErrorString("Child returned unknown exit status.");
974 break;
975 }
976 goto FINISH;
977 }
978 assert(WIFSTOPPED(status) && wpid == pid &&
979 "Could not sync with inferior process.");
980
981#ifdef notyet
982 // Have the child raise an event on exit. This is used to keep the child in
983 // limbo until it is destroyed.
984 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0)
985 {
986 args->m_error.SetErrorToErrno();
987 goto FINISH;
988 }
989#endif
Ed Mastea02f5532013-07-02 16:45:16 +0000990 // Release the master terminal descriptor and pass it off to the
991 // ProcessMonitor instance. Similarly stash the inferior pid.
992 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000993 monitor->m_pid = pid;
994
995 // Set the terminal fd to be in non blocking mode (it simplifies the
996 // implementation of ProcessFreeBSD::GetSTDOUT to have a non-blocking
997 // descriptor to read from).
998 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
999 goto FINISH;
1000
Ed Mastee5441432013-09-03 23:55:30 +00001001 process.SendMessage(ProcessMessage::Attach(pid));
Johnny Chen9ed5b492012-01-05 21:48:15 +00001002
1003FINISH:
1004 return args->m_error.Success();
1005}
1006
1007bool
1008ProcessMonitor::EnableIPC()
1009{
1010 int fd[2];
1011
1012 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
1013 return false;
1014
1015 m_client_fd = fd[0];
1016 m_server_fd = fd[1];
1017 return true;
1018}
1019
1020void
1021ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1022{
1023 static const char *g_thread_name = "lldb.process.freebsd.operation";
1024
1025 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1026 return;
1027
1028 m_operation_thread =
1029 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1030}
1031
Johnny Chen9ed5b492012-01-05 21:48:15 +00001032void *
1033ProcessMonitor::AttachOpThread(void *arg)
1034{
1035 AttachArgs *args = static_cast<AttachArgs*>(arg);
1036
1037 if (!Attach(args))
1038 return NULL;
1039
1040 ServeOperation(args);
1041 return NULL;
1042}
1043
1044bool
1045ProcessMonitor::Attach(AttachArgs *args)
1046{
1047 lldb::pid_t pid = args->m_pid;
1048
1049 ProcessMonitor *monitor = args->m_monitor;
1050 ProcessFreeBSD &process = monitor->GetProcess();
Johnny Chen9ed5b492012-01-05 21:48:15 +00001051
1052 if (pid <= 1)
1053 {
1054 args->m_error.SetErrorToGenericError();
1055 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1056 goto FINISH;
1057 }
1058
1059 // Attach to the requested process.
1060 if (PTRACE(PT_ATTACH, pid, NULL, 0) < 0)
1061 {
1062 args->m_error.SetErrorToErrno();
1063 goto FINISH;
1064 }
1065
1066 int status;
1067 if ((status = waitpid(pid, NULL, 0)) < 0)
1068 {
1069 args->m_error.SetErrorToErrno();
1070 goto FINISH;
1071 }
1072
Ed Mastee5441432013-09-03 23:55:30 +00001073 process.SendMessage(ProcessMessage::Attach(pid));
Johnny Chen9ed5b492012-01-05 21:48:15 +00001074
Ed Mastee5441432013-09-03 23:55:30 +00001075FINISH:
Johnny Chen9ed5b492012-01-05 21:48:15 +00001076 return args->m_error.Success();
1077}
1078
1079bool
1080ProcessMonitor::MonitorCallback(void *callback_baton,
1081 lldb::pid_t pid,
1082 bool exited,
1083 int signal,
1084 int status)
1085{
1086 ProcessMessage message;
1087 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001088 ProcessFreeBSD *process = monitor->m_process;
Ed Mastea02f5532013-07-02 16:45:16 +00001089 assert(process);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001090 bool stop_monitoring;
Ed Maste819e3992013-07-17 14:02:20 +00001091 struct ptrace_lwpinfo plwp;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001092 int ptrace_err;
Johnny Chen9ed5b492012-01-05 21:48:15 +00001093
Ed Mastea02f5532013-07-02 16:45:16 +00001094 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1095
1096 if (exited)
1097 {
1098 if (log)
1099 log->Printf ("ProcessMonitor::%s() got exit signal, tid = %" PRIu64, __FUNCTION__, pid);
1100 message = ProcessMessage::Exit(pid, status);
1101 process->SendMessage(message);
1102 return pid == process->GetID();
1103 }
1104
Ed Maste819e3992013-07-17 14:02:20 +00001105 if (!monitor->GetLwpInfo(pid, &plwp, ptrace_err))
Johnny Chen9ed5b492012-01-05 21:48:15 +00001106 stop_monitoring = true; // pid is gone. Bail.
1107 else {
Ed Maste819e3992013-07-17 14:02:20 +00001108 switch (plwp.pl_siginfo.si_signo)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001109 {
1110 case SIGTRAP:
Ed Maste819e3992013-07-17 14:02:20 +00001111 message = MonitorSIGTRAP(monitor, &plwp.pl_siginfo, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001112 break;
1113
1114 default:
Ed Maste819e3992013-07-17 14:02:20 +00001115 message = MonitorSignal(monitor, &plwp.pl_siginfo, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001116 break;
1117 }
1118
1119 process->SendMessage(message);
1120 stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
1121 }
1122
1123 return stop_monitoring;
1124}
1125
1126ProcessMessage
1127ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
1128 const siginfo_t *info, lldb::pid_t pid)
1129{
1130 ProcessMessage message;
1131
Ed Mastea02f5532013-07-02 16:45:16 +00001132 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1133
Matt Kopec7de48462013-03-06 17:20:48 +00001134 assert(monitor);
1135 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Johnny Chen9ed5b492012-01-05 21:48:15 +00001136
1137 switch (info->si_code)
1138 {
1139 default:
1140 assert(false && "Unexpected SIGTRAP code!");
1141 break;
1142
1143 case (SIGTRAP /* | (PTRACE_EVENT_EXIT << 8) */):
1144 {
1145 // The inferior process is about to exit. Maintain the process in a
1146 // state of "limbo" until we are explicitly commanded to detach,
1147 // destroy, resume, etc.
1148 unsigned long data = 0;
1149 if (!monitor->GetEventMessage(pid, &data))
1150 data = -1;
Ed Mastea02f5532013-07-02 16:45:16 +00001151 if (log)
1152 log->Printf ("ProcessMonitor::%s() received exit? event, data = %lx, pid = %" PRIu64, __FUNCTION__, data, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001153 message = ProcessMessage::Limbo(pid, (data >> 8));
1154 break;
1155 }
1156
1157 case 0:
1158 case TRAP_TRACE:
Ed Mastea02f5532013-07-02 16:45:16 +00001159 if (log)
1160 log->Printf ("ProcessMonitor::%s() received trace event, pid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001161 message = ProcessMessage::Trace(pid);
1162 break;
1163
1164 case SI_KERNEL:
1165 case TRAP_BRKPT:
Ed Mastea02f5532013-07-02 16:45:16 +00001166 if (log)
1167 log->Printf ("ProcessMonitor::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001168 message = ProcessMessage::Break(pid);
1169 break;
1170 }
1171
1172 return message;
1173}
1174
1175ProcessMessage
1176ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
1177 const siginfo_t *info, lldb::pid_t pid)
1178{
1179 ProcessMessage message;
1180 int signo = info->si_signo;
1181
Ed Mastea02f5532013-07-02 16:45:16 +00001182 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1183
Johnny Chen9ed5b492012-01-05 21:48:15 +00001184 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1185 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1186 // kill(2) or raise(3). Similarly for tgkill(2) on FreeBSD.
1187 //
1188 // IOW, user generated signals never generate what we consider to be a
1189 // "crash".
1190 //
1191 // Similarly, ACK signals generated by this monitor.
1192 if (info->si_code == SI_USER)
1193 {
Ed Mastea02f5532013-07-02 16:45:16 +00001194 if (log)
1195 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
1196 __FUNCTION__,
1197 monitor->m_process->GetUnixSignals().GetSignalAsCString (signo),
1198 "SI_USER",
1199 info->si_pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001200 if (info->si_pid == getpid())
1201 return ProcessMessage::SignalDelivered(pid, signo);
1202 else
1203 return ProcessMessage::Signal(pid, signo);
1204 }
1205
Ed Mastea02f5532013-07-02 16:45:16 +00001206 if (log)
1207 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals().GetSignalAsCString (signo));
1208
Johnny Chen9ed5b492012-01-05 21:48:15 +00001209 if (signo == SIGSEGV) {
1210 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1211 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1212 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1213 }
1214
1215 if (signo == SIGILL) {
1216 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1217 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1218 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1219 }
1220
1221 if (signo == SIGFPE) {
1222 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1223 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1224 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1225 }
1226
1227 if (signo == SIGBUS) {
1228 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1229 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1230 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1231 }
1232
1233 // Everything else is "normal" and does not require any special action on
1234 // our part.
1235 return ProcessMessage::Signal(pid, signo);
1236}
1237
1238ProcessMessage::CrashReason
1239ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1240{
1241 ProcessMessage::CrashReason reason;
1242 assert(info->si_signo == SIGSEGV);
1243
1244 reason = ProcessMessage::eInvalidCrashReason;
1245
1246 switch (info->si_code)
1247 {
1248 default:
1249 assert(false && "unexpected si_code for SIGSEGV");
1250 break;
1251 case SEGV_MAPERR:
1252 reason = ProcessMessage::eInvalidAddress;
1253 break;
1254 case SEGV_ACCERR:
1255 reason = ProcessMessage::ePrivilegedAddress;
1256 break;
1257 }
1258
1259 return reason;
1260}
1261
1262ProcessMessage::CrashReason
1263ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
1264{
1265 ProcessMessage::CrashReason reason;
1266 assert(info->si_signo == SIGILL);
1267
1268 reason = ProcessMessage::eInvalidCrashReason;
1269
1270 switch (info->si_code)
1271 {
1272 default:
1273 assert(false && "unexpected si_code for SIGILL");
1274 break;
1275 case ILL_ILLOPC:
1276 reason = ProcessMessage::eIllegalOpcode;
1277 break;
1278 case ILL_ILLOPN:
1279 reason = ProcessMessage::eIllegalOperand;
1280 break;
1281 case ILL_ILLADR:
1282 reason = ProcessMessage::eIllegalAddressingMode;
1283 break;
1284 case ILL_ILLTRP:
1285 reason = ProcessMessage::eIllegalTrap;
1286 break;
1287 case ILL_PRVOPC:
1288 reason = ProcessMessage::ePrivilegedOpcode;
1289 break;
1290 case ILL_PRVREG:
1291 reason = ProcessMessage::ePrivilegedRegister;
1292 break;
1293 case ILL_COPROC:
1294 reason = ProcessMessage::eCoprocessorError;
1295 break;
1296 case ILL_BADSTK:
1297 reason = ProcessMessage::eInternalStackError;
1298 break;
1299 }
1300
1301 return reason;
1302}
1303
1304ProcessMessage::CrashReason
1305ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
1306{
1307 ProcessMessage::CrashReason reason;
1308 assert(info->si_signo == SIGFPE);
1309
1310 reason = ProcessMessage::eInvalidCrashReason;
1311
1312 switch (info->si_code)
1313 {
1314 default:
1315 assert(false && "unexpected si_code for SIGFPE");
1316 break;
1317 case FPE_INTDIV:
1318 reason = ProcessMessage::eIntegerDivideByZero;
1319 break;
1320 case FPE_INTOVF:
1321 reason = ProcessMessage::eIntegerOverflow;
1322 break;
1323 case FPE_FLTDIV:
1324 reason = ProcessMessage::eFloatDivideByZero;
1325 break;
1326 case FPE_FLTOVF:
1327 reason = ProcessMessage::eFloatOverflow;
1328 break;
1329 case FPE_FLTUND:
1330 reason = ProcessMessage::eFloatUnderflow;
1331 break;
1332 case FPE_FLTRES:
1333 reason = ProcessMessage::eFloatInexactResult;
1334 break;
1335 case FPE_FLTINV:
1336 reason = ProcessMessage::eFloatInvalidOperation;
1337 break;
1338 case FPE_FLTSUB:
1339 reason = ProcessMessage::eFloatSubscriptRange;
1340 break;
1341 }
1342
1343 return reason;
1344}
1345
1346ProcessMessage::CrashReason
1347ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
1348{
1349 ProcessMessage::CrashReason reason;
1350 assert(info->si_signo == SIGBUS);
1351
1352 reason = ProcessMessage::eInvalidCrashReason;
1353
1354 switch (info->si_code)
1355 {
1356 default:
1357 assert(false && "unexpected si_code for SIGBUS");
1358 break;
1359 case BUS_ADRALN:
1360 reason = ProcessMessage::eIllegalAlignment;
1361 break;
1362 case BUS_ADRERR:
1363 reason = ProcessMessage::eIllegalAddress;
1364 break;
1365 case BUS_OBJERR:
1366 reason = ProcessMessage::eHardwareError;
1367 break;
1368 }
1369
1370 return reason;
1371}
1372
1373void
1374ProcessMonitor::ServeOperation(OperationArgs *args)
1375{
1376 int status;
1377 pollfd fdset;
1378
1379 ProcessMonitor *monitor = args->m_monitor;
1380
1381 fdset.fd = monitor->m_server_fd;
1382 fdset.events = POLLIN | POLLPRI;
1383 fdset.revents = 0;
1384
1385 // We are finised with the arguments and are ready to go. Sync with the
1386 // parent thread and start serving operations on the inferior.
1387 sem_post(&args->m_semaphore);
1388
1389 for (;;)
1390 {
1391 if ((status = poll(&fdset, 1, -1)) < 0)
1392 {
1393 switch (errno)
1394 {
1395 default:
1396 assert(false && "Unexpected poll() failure!");
1397 continue;
1398
1399 case EINTR: continue; // Just poll again.
1400 case EBADF: return; // Connection terminated.
1401 }
1402 }
1403
1404 assert(status == 1 && "Too many descriptors!");
1405
1406 if (fdset.revents & POLLIN)
1407 {
1408 Operation *op = NULL;
1409
1410 READ_AGAIN:
1411 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1412 {
1413 // There is only one acceptable failure.
1414 assert(errno == EINTR);
1415 goto READ_AGAIN;
1416 }
Ed Mastea02f5532013-07-02 16:45:16 +00001417 if (status == 0)
1418 continue; // Poll again. The connection probably terminated.
Johnny Chen9ed5b492012-01-05 21:48:15 +00001419 assert(status == sizeof(op));
1420 op->Execute(monitor);
1421 write(fdset.fd, &op, sizeof(op));
1422 }
1423 }
1424}
1425
1426void
1427ProcessMonitor::DoOperation(Operation *op)
1428{
1429 int status;
1430 Operation *ack = NULL;
1431 Mutex::Locker lock(m_server_mutex);
1432
1433 // FIXME: Do proper error checking here.
1434 write(m_client_fd, &op, sizeof(op));
1435
1436READ_AGAIN:
1437 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1438 {
1439 // If interrupted by a signal handler try again. Otherwise the monitor
1440 // thread probably died and we have a stale file descriptor -- abort the
1441 // operation.
1442 if (errno == EINTR)
1443 goto READ_AGAIN;
1444 return;
1445 }
1446
1447 assert(status == sizeof(ack));
1448 assert(ack == op && "Invalid monitor thread response!");
1449}
1450
1451size_t
1452ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1453 Error &error)
1454{
1455 size_t result;
1456 ReadOperation op(vm_addr, buf, size, error, result);
1457 DoOperation(&op);
1458 return result;
1459}
1460
1461size_t
1462ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1463 lldb_private::Error &error)
1464{
1465 size_t result;
1466 WriteOperation op(vm_addr, buf, size, error, result);
1467 DoOperation(&op);
1468 return result;
1469}
1470
1471bool
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00001472ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +00001473 unsigned size, RegisterValue &value)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001474{
1475 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001476 ReadRegOperation op(tid, offset, size, value, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001477 DoOperation(&op);
1478 return result;
1479}
1480
1481bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001482ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00001483 const char* reg_name, const RegisterValue &value)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001484{
1485 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001486 WriteRegOperation op(tid, offset, value, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001487 DoOperation(&op);
1488 return result;
1489}
1490
1491bool
Matt Kopec7de48462013-03-06 17:20:48 +00001492ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001493{
1494 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001495 ReadGPROperation op(tid, buf, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001496 DoOperation(&op);
1497 return result;
1498}
1499
1500bool
Matt Kopec7de48462013-03-06 17:20:48 +00001501ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001502{
1503 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001504 ReadFPROperation op(tid, buf, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001505 DoOperation(&op);
1506 return result;
1507}
1508
1509bool
Ed Maste5d34af32013-06-24 15:09:18 +00001510ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1511{
1512 return false;
1513}
1514
1515bool
Matt Kopec7de48462013-03-06 17:20:48 +00001516ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001517{
1518 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001519 WriteGPROperation op(tid, buf, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001520 DoOperation(&op);
1521 return result;
1522}
1523
1524bool
Matt Kopec7de48462013-03-06 17:20:48 +00001525ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001526{
1527 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001528 WriteFPROperation op(tid, buf, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001529 DoOperation(&op);
1530 return result;
1531}
1532
1533bool
Ed Maste5d34af32013-06-24 15:09:18 +00001534ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1535{
1536 return false;
1537}
1538
1539bool
Johnny Chen9ed5b492012-01-05 21:48:15 +00001540ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
1541{
1542 bool result;
Ed Mastea02f5532013-07-02 16:45:16 +00001543 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1544
1545 if (log)
1546 log->Printf ("ProcessMonitor::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
1547 m_process->GetUnixSignals().GetSignalAsCString (signo));
Johnny Chen9ed5b492012-01-05 21:48:15 +00001548 ResumeOperation op(tid, signo, result);
1549 DoOperation(&op);
Ed Mastea02f5532013-07-02 16:45:16 +00001550 if (log)
1551 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
Johnny Chen9ed5b492012-01-05 21:48:15 +00001552 return result;
1553}
1554
1555bool
1556ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
1557{
1558 bool result;
1559 SingleStepOperation op(tid, signo, result);
1560 DoOperation(&op);
1561 return result;
1562}
1563
1564bool
1565ProcessMonitor::BringProcessIntoLimbo()
1566{
1567 bool result;
1568 KillOperation op(result);
1569 DoOperation(&op);
1570 return result;
1571}
1572
1573bool
Ed Maste819e3992013-07-17 14:02:20 +00001574ProcessMonitor::GetLwpInfo(lldb::tid_t tid, void *lwpinfo, int &ptrace_err)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001575{
1576 bool result;
Ed Maste819e3992013-07-17 14:02:20 +00001577 LwpInfoOperation op(tid, lwpinfo, result, ptrace_err);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001578 DoOperation(&op);
1579 return result;
1580}
1581
1582bool
1583ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1584{
1585 bool result;
1586 EventMessageOperation op(tid, message, result);
1587 DoOperation(&op);
1588 return result;
1589}
1590
Ed Mastea02f5532013-07-02 16:45:16 +00001591lldb_private::Error
Matt Kopecedee1822013-06-03 19:48:53 +00001592ProcessMonitor::Detach(lldb::tid_t tid)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001593{
Ed Mastea02f5532013-07-02 16:45:16 +00001594 lldb_private::Error error;
1595 if (tid != LLDB_INVALID_THREAD_ID)
1596 {
1597 DetachOperation op(error);
1598 DoOperation(&op);
1599 }
1600 return error;
Johnny Chen9ed5b492012-01-05 21:48:15 +00001601}
1602
1603bool
1604ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1605{
1606 int target_fd = open(path, flags, 0666);
1607
1608 if (target_fd == -1)
1609 return false;
1610
1611 return (dup2(target_fd, fd) == -1) ? false : true;
1612}
1613
1614void
1615ProcessMonitor::StopMonitoringChildProcess()
1616{
1617 lldb::thread_result_t thread_result;
1618
1619 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
1620 {
1621 Host::ThreadCancel(m_monitor_thread, NULL);
1622 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1623 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1624 }
1625}
1626
1627void
1628ProcessMonitor::StopMonitor()
1629{
1630 StopMonitoringChildProcess();
Ed Mastea02f5532013-07-02 16:45:16 +00001631 StopOpThread();
Johnny Chen9ed5b492012-01-05 21:48:15 +00001632 CloseFD(m_client_fd);
1633 CloseFD(m_server_fd);
Andrew Kaylor5e268992013-09-14 00:17:31 +00001634 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
1635 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
1636 // the descriptor to a ConnectionFileDescriptor object. Consequently
1637 // even though still has the file descriptor, we shouldn't close it here.
Johnny Chen9ed5b492012-01-05 21:48:15 +00001638}
1639
Andrew Kaylord4d54992013-09-17 00:30:24 +00001640// FIXME: On Linux, when a new thread is created, we receive to notifications,
1641// (1) a SIGTRAP|PTRACE_EVENT_CLONE from the main process thread with the
1642// child thread id as additional information, and (2) a SIGSTOP|SI_USER from
1643// the new child thread indicating that it has is stopped because we attached.
1644// We have no guarantee of the order in which these arrive, but we need both
1645// before we are ready to proceed. We currently keep a list of threads which
1646// have sent the initial SIGSTOP|SI_USER event. Then when we receive the
1647// SIGTRAP|PTRACE_EVENT_CLONE notification, if the initial stop has not occurred
1648// we call ProcessMonitor::WaitForInitialTIDStop() to wait for it.
1649//
1650// Right now, the above logic is in ProcessPOSIX, so we need a definition of
1651// this function in the FreeBSD ProcessMonitor implementation even if it isn't
1652// logically needed.
1653//
1654// We really should figure out what actually happens on FreeBSD and move the
1655// Linux-specific logic out of ProcessPOSIX as needed.
1656
1657bool
1658ProcessMonitor::WaitForInitialTIDStop(lldb::tid_t tid)
1659{
1660 return true;
1661}
1662
Johnny Chen9ed5b492012-01-05 21:48:15 +00001663void
Ed Mastea02f5532013-07-02 16:45:16 +00001664ProcessMonitor::StopOpThread()
1665{
1666 lldb::thread_result_t result;
1667
1668 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1669 return;
1670
1671 Host::ThreadCancel(m_operation_thread, NULL);
1672 Host::ThreadJoin(m_operation_thread, &result, NULL);
1673 m_operation_thread = LLDB_INVALID_HOST_THREAD;
1674}
1675
1676void
Johnny Chen9ed5b492012-01-05 21:48:15 +00001677ProcessMonitor::CloseFD(int &fd)
1678{
1679 if (fd != -1)
1680 {
1681 close(fd);
1682 fd = -1;
1683 }
1684}