blob: a8ba86ead1374ecdd9638e6d944725c7cd71e272 [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
104 if (log) {
105 if (req == PT_GETREGS) {
106 struct reg *r = (struct reg *) addr;
107
108 log->Printf("PT_GETREGS: ip=0x%lx", r->r_rip);
109 log->Printf("PT_GETREGS: sp=0x%lx", r->r_rsp);
110 log->Printf("PT_GETREGS: bp=0x%lx", r->r_rbp);
111 log->Printf("PT_GETREGS: ax=0x%lx", r->r_rax);
112 }
113 }
114
115 return result;
116}
117
Matt Kopec7de48462013-03-06 17:20:48 +0000118// Wrapper for ptrace when logging is not required.
119// Sets errno to 0 prior to calling ptrace.
120extern long
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000121PtraceWrapper(int req, lldb::pid_t pid, void *addr, int data)
Matt Kopec7de48462013-03-06 17:20:48 +0000122{
123 long result = 0;
124 errno = 0;
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000125 result = ptrace(req, pid, (caddr_t)addr, data);
Matt Kopec7de48462013-03-06 17:20:48 +0000126 return result;
127}
128
Johnny Chen9ed5b492012-01-05 21:48:15 +0000129#define PTRACE(req, pid, addr, data) \
130 PtraceWrapper((req), (pid), (addr), (data), #req, __FILE__, __LINE__)
131#else
Matt Kopec7de48462013-03-06 17:20:48 +0000132 PtraceWrapper((req), (pid), (addr), (data))
Johnny Chen9ed5b492012-01-05 21:48:15 +0000133#endif
134
135//------------------------------------------------------------------------------
136// Static implementations of ProcessMonitor::ReadMemory and
137// ProcessMonitor::WriteMemory. This enables mutual recursion between these
138// functions without needed to go thru the thread funnel.
139
140static size_t
141DoReadMemory(lldb::pid_t pid, lldb::addr_t vm_addr, void *buf, size_t size,
142 Error &error)
143{
144 struct ptrace_io_desc pi_desc;
145
146 pi_desc.piod_op = PIOD_READ_D;
147 pi_desc.piod_offs = (void *)vm_addr;
148 pi_desc.piod_addr = buf;
149 pi_desc.piod_len = size;
150
151 if (PTRACE(PT_IO, pid, (caddr_t)&pi_desc, 0) < 0)
152 error.SetErrorToErrno();
153 return pi_desc.piod_len;
154}
155
156static size_t
157DoWriteMemory(lldb::pid_t pid, lldb::addr_t vm_addr, const void *buf,
158 size_t size, Error &error)
159{
160 struct ptrace_io_desc pi_desc;
161
162 pi_desc.piod_op = PIOD_WRITE_D;
163 pi_desc.piod_offs = (void *)vm_addr;
164 pi_desc.piod_addr = (void *)buf;
165 pi_desc.piod_len = size;
166
167 if (PTRACE(PT_IO, pid, (caddr_t)&pi_desc, 0) < 0)
168 error.SetErrorToErrno();
169 return pi_desc.piod_len;
170}
171
172// Simple helper function to ensure flags are enabled on the given file
173// descriptor.
174static bool
175EnsureFDFlags(int fd, int flags, Error &error)
176{
177 int status;
178
179 if ((status = fcntl(fd, F_GETFL)) == -1)
180 {
181 error.SetErrorToErrno();
182 return false;
183 }
184
185 if (fcntl(fd, F_SETFL, status | flags) == -1)
186 {
187 error.SetErrorToErrno();
188 return false;
189 }
190
191 return true;
192}
193
194//------------------------------------------------------------------------------
195/// @class Operation
196/// @brief Represents a ProcessMonitor operation.
197///
198/// Under FreeBSD, it is not possible to ptrace() from any other thread but the
199/// one that spawned or attached to the process from the start. Therefore, when
200/// a ProcessMonitor is asked to deliver or change the state of an inferior
201/// process the operation must be "funneled" to a specific thread to perform the
202/// task. The Operation class provides an abstract base for all services the
203/// ProcessMonitor must perform via the single virtual function Execute, thus
204/// encapsulating the code that needs to run in the privileged context.
205class Operation
206{
207public:
Ed Maste5a9a6262013-06-24 14:55:03 +0000208 virtual ~Operation() {}
Johnny Chen9ed5b492012-01-05 21:48:15 +0000209 virtual void Execute(ProcessMonitor *monitor) = 0;
210};
211
212//------------------------------------------------------------------------------
213/// @class ReadOperation
214/// @brief Implements ProcessMonitor::ReadMemory.
215class ReadOperation : public Operation
216{
217public:
218 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
219 Error &error, size_t &result)
220 : m_addr(addr), m_buff(buff), m_size(size),
221 m_error(error), m_result(result)
222 { }
223
224 void Execute(ProcessMonitor *monitor);
225
226private:
227 lldb::addr_t m_addr;
228 void *m_buff;
229 size_t m_size;
230 Error &m_error;
231 size_t &m_result;
232};
233
234void
235ReadOperation::Execute(ProcessMonitor *monitor)
236{
237 lldb::pid_t pid = monitor->GetPID();
238
239 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
240}
241
242//------------------------------------------------------------------------------
Ed Mastea56115f2013-07-17 14:30:26 +0000243/// @class WriteOperation
Johnny Chen9ed5b492012-01-05 21:48:15 +0000244/// @brief Implements ProcessMonitor::WriteMemory.
245class WriteOperation : public Operation
246{
247public:
248 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
249 Error &error, size_t &result)
250 : m_addr(addr), m_buff(buff), m_size(size),
251 m_error(error), m_result(result)
252 { }
253
254 void Execute(ProcessMonitor *monitor);
255
256private:
257 lldb::addr_t m_addr;
258 const void *m_buff;
259 size_t m_size;
260 Error &m_error;
261 size_t &m_result;
262};
263
264void
265WriteOperation::Execute(ProcessMonitor *monitor)
266{
267 lldb::pid_t pid = monitor->GetPID();
268
269 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
270}
271
272//------------------------------------------------------------------------------
273/// @class ReadRegOperation
274/// @brief Implements ProcessMonitor::ReadRegisterValue.
275class ReadRegOperation : public Operation
276{
277public:
Ed Maste6f066412013-07-04 21:47:32 +0000278 ReadRegOperation(lldb::tid_t tid, unsigned offset, unsigned size,
279 RegisterValue &value, bool &result)
280 : m_tid(tid), m_offset(offset), m_size(size),
281 m_value(value), m_result(result)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000282 { }
283
284 void Execute(ProcessMonitor *monitor);
285
286private:
Ed Maste6f066412013-07-04 21:47:32 +0000287 lldb::tid_t m_tid;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000288 unsigned m_offset;
289 unsigned m_size;
290 RegisterValue &m_value;
291 bool &m_result;
292};
293
294void
295ReadRegOperation::Execute(ProcessMonitor *monitor)
296{
Johnny Chen9ed5b492012-01-05 21:48:15 +0000297 struct reg regs;
298 int rc;
299
Ed Maste6f066412013-07-04 21:47:32 +0000300 if ((rc = PTRACE(PT_GETREGS, m_tid, (caddr_t)&regs, 0)) < 0) {
Johnny Chen9ed5b492012-01-05 21:48:15 +0000301 m_result = false;
302 } else {
303 if (m_size == sizeof(uintptr_t))
304 m_value = *(uintptr_t *)(((caddr_t)&regs) + m_offset);
305 else
306 memcpy(&m_value, (((caddr_t)&regs) + m_offset), m_size);
307 m_result = true;
308 }
309}
310
311//------------------------------------------------------------------------------
312/// @class WriteRegOperation
313/// @brief Implements ProcessMonitor::WriteRegisterValue.
314class WriteRegOperation : public Operation
315{
316public:
Ed Maste6f066412013-07-04 21:47:32 +0000317 WriteRegOperation(lldb::tid_t tid, unsigned offset,
318 const RegisterValue &value, bool &result)
319 : m_tid(tid), m_offset(offset),
320 m_value(value), m_result(result)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000321 { }
322
323 void Execute(ProcessMonitor *monitor);
324
325private:
Ed Maste6f066412013-07-04 21:47:32 +0000326 lldb::tid_t m_tid;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000327 unsigned m_offset;
328 const RegisterValue &m_value;
329 bool &m_result;
330};
331
332void
333WriteRegOperation::Execute(ProcessMonitor *monitor)
334{
Johnny Chen9ed5b492012-01-05 21:48:15 +0000335 struct reg regs;
336
Ed Maste6f066412013-07-04 21:47:32 +0000337 if (PTRACE(PT_GETREGS, m_tid, (caddr_t)&regs, 0) < 0) {
Johnny Chen9ed5b492012-01-05 21:48:15 +0000338 m_result = false;
339 return;
340 }
341 *(uintptr_t *)(((caddr_t)&regs) + m_offset) = (uintptr_t)m_value.GetAsUInt64();
Ed Maste6f066412013-07-04 21:47:32 +0000342 if (PTRACE(PT_SETREGS, m_tid, (caddr_t)&regs, 0) < 0)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000343 m_result = false;
344 else
345 m_result = true;
346}
347
348//------------------------------------------------------------------------------
349/// @class ReadGPROperation
350/// @brief Implements ProcessMonitor::ReadGPR.
351class ReadGPROperation : public Operation
352{
353public:
Ed Maste6f066412013-07-04 21:47:32 +0000354 ReadGPROperation(lldb::tid_t tid, void *buf, bool &result)
355 : m_tid(tid), m_buf(buf), m_result(result)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000356 { }
357
358 void Execute(ProcessMonitor *monitor);
359
360private:
Ed Maste6f066412013-07-04 21:47:32 +0000361 lldb::tid_t m_tid;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000362 void *m_buf;
363 bool &m_result;
364};
365
366void
367ReadGPROperation::Execute(ProcessMonitor *monitor)
368{
369 int rc;
370
371 errno = 0;
Ed Maste6f066412013-07-04 21:47:32 +0000372 rc = PTRACE(PT_GETREGS, m_tid, (caddr_t)m_buf, 0);
Johnny Chen9ed5b492012-01-05 21:48:15 +0000373 if (errno != 0)
374 m_result = false;
375 else
376 m_result = true;
377}
378
379//------------------------------------------------------------------------------
380/// @class ReadFPROperation
381/// @brief Implements ProcessMonitor::ReadFPR.
382class ReadFPROperation : public Operation
383{
384public:
Ed Maste6f066412013-07-04 21:47:32 +0000385 ReadFPROperation(lldb::tid_t tid, void *buf, bool &result)
386 : m_tid(tid), m_buf(buf), m_result(result)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000387 { }
388
389 void Execute(ProcessMonitor *monitor);
390
391private:
Ed Maste6f066412013-07-04 21:47:32 +0000392 lldb::tid_t m_tid;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000393 void *m_buf;
394 bool &m_result;
395};
396
397void
398ReadFPROperation::Execute(ProcessMonitor *monitor)
399{
Ed Maste6f066412013-07-04 21:47:32 +0000400 if (PTRACE(PT_GETFPREGS, m_tid, (caddr_t)m_buf, 0) < 0)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000401 m_result = false;
402 else
403 m_result = true;
404}
405
406//------------------------------------------------------------------------------
407/// @class WriteGPROperation
408/// @brief Implements ProcessMonitor::WriteGPR.
409class WriteGPROperation : public Operation
410{
411public:
Ed Maste6f066412013-07-04 21:47:32 +0000412 WriteGPROperation(lldb::tid_t tid, void *buf, bool &result)
413 : m_tid(tid), m_buf(buf), m_result(result)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000414 { }
415
416 void Execute(ProcessMonitor *monitor);
417
418private:
Ed Maste6f066412013-07-04 21:47:32 +0000419 lldb::tid_t m_tid;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000420 void *m_buf;
421 bool &m_result;
422};
423
424void
425WriteGPROperation::Execute(ProcessMonitor *monitor)
426{
Ed Maste6f066412013-07-04 21:47:32 +0000427 if (PTRACE(PT_SETREGS, m_tid, (caddr_t)m_buf, 0) < 0)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000428 m_result = false;
429 else
430 m_result = true;
431}
432
433//------------------------------------------------------------------------------
434/// @class WriteFPROperation
435/// @brief Implements ProcessMonitor::WriteFPR.
436class WriteFPROperation : public Operation
437{
438public:
Ed Maste6f066412013-07-04 21:47:32 +0000439 WriteFPROperation(lldb::tid_t tid, void *buf, bool &result)
440 : m_tid(tid), m_buf(buf), m_result(result)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000441 { }
442
443 void Execute(ProcessMonitor *monitor);
444
445private:
Ed Maste6f066412013-07-04 21:47:32 +0000446 lldb::tid_t m_tid;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000447 void *m_buf;
448 bool &m_result;
449};
450
451void
452WriteFPROperation::Execute(ProcessMonitor *monitor)
453{
Ed Maste6f066412013-07-04 21:47:32 +0000454 if (PTRACE(PT_SETFPREGS, m_tid, (caddr_t)m_buf, 0) < 0)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000455 m_result = false;
456 else
457 m_result = true;
458}
459
460//------------------------------------------------------------------------------
461/// @class ResumeOperation
462/// @brief Implements ProcessMonitor::Resume.
463class ResumeOperation : public Operation
464{
465public:
466 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
467 m_tid(tid), m_signo(signo), m_result(result) { }
468
469 void Execute(ProcessMonitor *monitor);
470
471private:
472 lldb::tid_t m_tid;
473 uint32_t m_signo;
474 bool &m_result;
475};
476
477void
478ResumeOperation::Execute(ProcessMonitor *monitor)
479{
480 int data = 0;
481
482 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
483 data = m_signo;
484
485 if (PTRACE(PT_CONTINUE, m_tid, (caddr_t)1, data))
Ed Mastea02f5532013-07-02 16:45:16 +0000486 {
487 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
488
489 if (log)
490 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, strerror(errno));
Johnny Chen9ed5b492012-01-05 21:48:15 +0000491 m_result = false;
Ed Mastea02f5532013-07-02 16:45:16 +0000492 }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000493 else
494 m_result = true;
495}
496
497//------------------------------------------------------------------------------
Ed Maste428a6782013-06-24 15:04:47 +0000498/// @class SingleStepOperation
Johnny Chen9ed5b492012-01-05 21:48:15 +0000499/// @brief Implements ProcessMonitor::SingleStep.
500class SingleStepOperation : public Operation
501{
502public:
503 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
504 : m_tid(tid), m_signo(signo), m_result(result) { }
505
506 void Execute(ProcessMonitor *monitor);
507
508private:
509 lldb::tid_t m_tid;
510 uint32_t m_signo;
511 bool &m_result;
512};
513
514void
515SingleStepOperation::Execute(ProcessMonitor *monitor)
516{
517 int data = 0;
518
519 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
520 data = m_signo;
521
522 if (PTRACE(PT_STEP, m_tid, NULL, data))
523 m_result = false;
524 else
525 m_result = true;
526}
527
528//------------------------------------------------------------------------------
Ed Maste819e3992013-07-17 14:02:20 +0000529/// @class LwpInfoOperation
530/// @brief Implements ProcessMonitor::GetLwpInfo.
531class LwpInfoOperation : public Operation
Johnny Chen9ed5b492012-01-05 21:48:15 +0000532{
533public:
Ed Maste819e3992013-07-17 14:02:20 +0000534 LwpInfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
Daniel Maleaa35970a2012-11-23 18:09:58 +0000535 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000536
537 void Execute(ProcessMonitor *monitor);
538
539private:
540 lldb::tid_t m_tid;
541 void *m_info;
542 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000543 int &m_err;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000544};
545
546void
Ed Maste819e3992013-07-17 14:02:20 +0000547LwpInfoOperation::Execute(ProcessMonitor *monitor)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000548{
549 struct ptrace_lwpinfo plwp;
550
Daniel Maleaa35970a2012-11-23 18:09:58 +0000551 if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp))) {
Johnny Chen9ed5b492012-01-05 21:48:15 +0000552 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000553 m_err = errno;
554 } else {
Ed Maste819e3992013-07-17 14:02:20 +0000555 memcpy(m_info, &plwp, sizeof(plwp));
Johnny Chen9ed5b492012-01-05 21:48:15 +0000556 m_result = true;
557 }
558}
559
560//------------------------------------------------------------------------------
561/// @class EventMessageOperation
562/// @brief Implements ProcessMonitor::GetEventMessage.
563class EventMessageOperation : public Operation
564{
565public:
566 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
567 : m_tid(tid), m_message(message), m_result(result) { }
568
569 void Execute(ProcessMonitor *monitor);
570
571private:
572 lldb::tid_t m_tid;
573 unsigned long *m_message;
574 bool &m_result;
575};
576
577void
578EventMessageOperation::Execute(ProcessMonitor *monitor)
579{
580 struct ptrace_lwpinfo plwp;
581
582 if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp)))
583 m_result = false;
584 else {
585 if (plwp.pl_flags & PL_FLAG_FORKED) {
586 m_message = (unsigned long *)plwp.pl_child_pid;
587 m_result = true;
588 } else
589 m_result = false;
590 }
591}
592
593//------------------------------------------------------------------------------
594/// @class KillOperation
595/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
596class KillOperation : public Operation
597{
598public:
599 KillOperation(bool &result) : m_result(result) { }
600
601 void Execute(ProcessMonitor *monitor);
602
603private:
604 bool &m_result;
605};
606
607void
608KillOperation::Execute(ProcessMonitor *monitor)
609{
610 lldb::pid_t pid = monitor->GetPID();
611
612 if (PTRACE(PT_KILL, pid, NULL, 0))
613 m_result = false;
614 else
615 m_result = true;
616}
617
618//------------------------------------------------------------------------------
Ed Mastea02f5532013-07-02 16:45:16 +0000619/// @class DetachOperation
Johnny Chen9ed5b492012-01-05 21:48:15 +0000620/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
621class DetachOperation : public Operation
622{
623public:
624 DetachOperation(Error &result) : m_error(result) { }
625
626 void Execute(ProcessMonitor *monitor);
627
628private:
629 Error &m_error;
630};
631
632void
633DetachOperation::Execute(ProcessMonitor *monitor)
634{
635 lldb::pid_t pid = monitor->GetPID();
636
637 if (PTRACE(PT_DETACH, pid, NULL, 0) < 0)
638 m_error.SetErrorToErrno();
639
640}
641
642ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
643 : m_monitor(monitor)
644{
645 sem_init(&m_semaphore, 0, 0);
646}
647
648ProcessMonitor::OperationArgs::~OperationArgs()
649{
650 sem_destroy(&m_semaphore);
651}
652
653ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
654 lldb_private::Module *module,
655 char const **argv,
656 char const **envp,
657 const char *stdin_path,
658 const char *stdout_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000659 const char *stderr_path,
660 const char *working_dir)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000661 : OperationArgs(monitor),
662 m_module(module),
663 m_argv(argv),
664 m_envp(envp),
665 m_stdin_path(stdin_path),
666 m_stdout_path(stdout_path),
Daniel Malea6217d2a2013-01-08 14:49:22 +0000667 m_stderr_path(stderr_path),
668 m_working_dir(working_dir) { }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000669
670ProcessMonitor::LaunchArgs::~LaunchArgs()
671{ }
672
673ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
674 lldb::pid_t pid)
675 : OperationArgs(monitor), m_pid(pid) { }
676
677ProcessMonitor::AttachArgs::~AttachArgs()
678{ }
679
680//------------------------------------------------------------------------------
681/// The basic design of the ProcessMonitor is built around two threads.
682///
683/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
684/// for changes in the debugee state. When a change is detected a
685/// ProcessMessage is sent to the associated ProcessFreeBSD instance. This thread
686/// "drives" state changes in the debugger.
687///
688/// The second thread (@see OperationThread) is responsible for two things 1)
689/// launching or attaching to the inferior process, and then 2) servicing
690/// operations such as register reads/writes, stepping, etc. See the comments
691/// on the Operation class for more info as to why this is needed.
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000692ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen9ed5b492012-01-05 21:48:15 +0000693 Module *module,
694 const char *argv[],
695 const char *envp[],
696 const char *stdin_path,
697 const char *stdout_path,
698 const char *stderr_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000699 const char *working_dir,
Johnny Chen9ed5b492012-01-05 21:48:15 +0000700 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000701 : m_process(static_cast<ProcessFreeBSD *>(process)),
Johnny Chen9ed5b492012-01-05 21:48:15 +0000702 m_operation_thread(LLDB_INVALID_HOST_THREAD),
703 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
704 m_pid(LLDB_INVALID_PROCESS_ID),
705 m_server_mutex(Mutex::eMutexTypeRecursive),
706 m_terminal_fd(-1),
707 m_client_fd(-1),
708 m_server_fd(-1)
709{
Greg Clayton7b0992d2013-04-18 22:45:39 +0000710 std::unique_ptr<LaunchArgs> args;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000711
712 args.reset(new LaunchArgs(this, module, argv, envp,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000713 stdin_path, stdout_path, stderr_path, working_dir));
Johnny Chen9ed5b492012-01-05 21:48:15 +0000714
715
716 // Server/client descriptors.
717 if (!EnableIPC())
718 {
719 error.SetErrorToGenericError();
720 error.SetErrorString("Monitor failed to initialize.");
721 }
722
723 StartLaunchOpThread(args.get(), error);
724 if (!error.Success())
725 return;
726
727WAIT_AGAIN:
728 // Wait for the operation thread to initialize.
729 if (sem_wait(&args->m_semaphore))
730 {
731 if (errno == EINTR)
732 goto WAIT_AGAIN;
733 else
734 {
735 error.SetErrorToErrno();
736 return;
737 }
738 }
739
740 // Check that the launch was a success.
741 if (!args->m_error.Success())
742 {
Ed Mastea02f5532013-07-02 16:45:16 +0000743 StopOpThread();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000744 error = args->m_error;
745 return;
746 }
747
748 // Finally, start monitoring the child process for change in state.
749 m_monitor_thread = Host::StartMonitoringChildProcess(
750 ProcessMonitor::MonitorCallback, this, GetPID(), true);
751 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
752 {
753 error.SetErrorToGenericError();
754 error.SetErrorString("Process launch failed.");
755 return;
756 }
757}
758
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000759ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen9ed5b492012-01-05 21:48:15 +0000760 lldb::pid_t pid,
761 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000762 : m_process(static_cast<ProcessFreeBSD *>(process)),
Johnny Chen9ed5b492012-01-05 21:48:15 +0000763 m_operation_thread(LLDB_INVALID_HOST_THREAD),
764 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
765 m_pid(pid),
766 m_server_mutex(Mutex::eMutexTypeRecursive),
767 m_terminal_fd(-1),
768 m_client_fd(-1),
769 m_server_fd(-1)
770{
Greg Clayton7b0992d2013-04-18 22:45:39 +0000771 std::unique_ptr<AttachArgs> args;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000772
773 args.reset(new AttachArgs(this, pid));
774
775 // Server/client descriptors.
776 if (!EnableIPC())
777 {
778 error.SetErrorToGenericError();
779 error.SetErrorString("Monitor failed to initialize.");
780 }
781
782 StartAttachOpThread(args.get(), error);
783 if (!error.Success())
784 return;
785
786WAIT_AGAIN:
787 // Wait for the operation thread to initialize.
788 if (sem_wait(&args->m_semaphore))
789 {
790 if (errno == EINTR)
791 goto WAIT_AGAIN;
792 else
793 {
794 error.SetErrorToErrno();
795 return;
796 }
797 }
798
Ed Mastea02f5532013-07-02 16:45:16 +0000799 // Check that the attach was a success.
Johnny Chen9ed5b492012-01-05 21:48:15 +0000800 if (!args->m_error.Success())
801 {
Ed Mastea02f5532013-07-02 16:45:16 +0000802 StopOpThread();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000803 error = args->m_error;
804 return;
805 }
806
807 // Finally, start monitoring the child process for change in state.
808 m_monitor_thread = Host::StartMonitoringChildProcess(
809 ProcessMonitor::MonitorCallback, this, GetPID(), true);
810 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
811 {
812 error.SetErrorToGenericError();
813 error.SetErrorString("Process attach failed.");
814 return;
815 }
816}
817
818ProcessMonitor::~ProcessMonitor()
819{
820 StopMonitor();
821}
822
823//------------------------------------------------------------------------------
824// Thread setup and tear down.
825void
826ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
827{
828 static const char *g_thread_name = "lldb.process.freebsd.operation";
829
830 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
831 return;
832
833 m_operation_thread =
834 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
835}
836
Johnny Chen9ed5b492012-01-05 21:48:15 +0000837void *
838ProcessMonitor::LaunchOpThread(void *arg)
839{
840 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
841
842 if (!Launch(args)) {
843 sem_post(&args->m_semaphore);
844 return NULL;
845 }
846
847 ServeOperation(args);
848 return NULL;
849}
850
851bool
852ProcessMonitor::Launch(LaunchArgs *args)
853{
854 ProcessMonitor *monitor = args->m_monitor;
855 ProcessFreeBSD &process = monitor->GetProcess();
Greg Clayton29d19302012-02-27 18:40:48 +0000856 lldb::ProcessSP processSP = process.shared_from_this();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000857 const char **argv = args->m_argv;
858 const char **envp = args->m_envp;
859 const char *stdin_path = args->m_stdin_path;
860 const char *stdout_path = args->m_stdout_path;
861 const char *stderr_path = args->m_stderr_path;
Daniel Malea6217d2a2013-01-08 14:49:22 +0000862 const char *working_dir = args->m_working_dir;
Ed Mastea02f5532013-07-02 16:45:16 +0000863
864 lldb_utility::PseudoTerminal terminal;
865 const size_t err_len = 1024;
866 char err_str[err_len];
Johnny Chen9ed5b492012-01-05 21:48:15 +0000867 lldb::pid_t pid;
868
869 lldb::ThreadSP inferior;
Ed Mastea02f5532013-07-02 16:45:16 +0000870 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen9ed5b492012-01-05 21:48:15 +0000871
872 // Propagate the environment if one is not supplied.
873 if (envp == NULL || envp[0] == NULL)
874 envp = const_cast<const char **>(environ);
875
Ed Mastea02f5532013-07-02 16:45:16 +0000876 // Pseudo terminal setup.
877 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
878 {
879 args->m_error.SetErrorToGenericError();
880 args->m_error.SetErrorString("Could not open controlling TTY.");
881 goto FINISH;
882 }
883
884 if ((pid = terminal.Fork(err_str, err_len)) == -1)
885 {
886 args->m_error.SetErrorToGenericError();
887 args->m_error.SetErrorString("Process fork failed.");
888 goto FINISH;
889 }
890
Johnny Chen9ed5b492012-01-05 21:48:15 +0000891 // Recognized child exit status codes.
892 enum {
893 ePtraceFailed = 1,
894 eDupStdinFailed,
895 eDupStdoutFailed,
896 eDupStderrFailed,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000897 eChdirFailed,
Johnny Chen9ed5b492012-01-05 21:48:15 +0000898 eExecFailed
899 };
900
Johnny Chen9ed5b492012-01-05 21:48:15 +0000901 // Child process.
902 if (pid == 0)
903 {
904 // Trace this process.
905 if (PTRACE(PT_TRACE_ME, 0, NULL, 0) < 0)
906 exit(ePtraceFailed);
907
908 // Do not inherit setgid powers.
909 setgid(getgid());
910
911 // Let us have our own process group.
912 setpgid(0, 0);
913
914 // Dup file descriptors if needed.
915 //
916 // FIXME: If two or more of the paths are the same we needlessly open
917 // the same file multiple times.
918 if (stdin_path != NULL && stdin_path[0])
919 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
920 exit(eDupStdinFailed);
921
922 if (stdout_path != NULL && stdout_path[0])
923 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
924 exit(eDupStdoutFailed);
925
926 if (stderr_path != NULL && stderr_path[0])
927 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
928 exit(eDupStderrFailed);
929
Daniel Malea6217d2a2013-01-08 14:49:22 +0000930 // Change working directory
931 if (working_dir != NULL && working_dir[0])
932 if (0 != ::chdir(working_dir))
933 exit(eChdirFailed);
934
Johnny Chen9ed5b492012-01-05 21:48:15 +0000935 // Execute. We should never return.
936 execve(argv[0],
937 const_cast<char *const *>(argv),
938 const_cast<char *const *>(envp));
939 exit(eExecFailed);
940 }
941
942 // Wait for the child process to to trap on its call to execve.
943 ::pid_t wpid;
944 int status;
945 if ((wpid = waitpid(pid, &status, 0)) < 0)
946 {
947 args->m_error.SetErrorToErrno();
948 goto FINISH;
949 }
950 else if (WIFEXITED(status))
951 {
952 // open, dup or execve likely failed for some reason.
953 args->m_error.SetErrorToGenericError();
954 switch (WEXITSTATUS(status))
955 {
Ed Maste5d34af32013-06-24 15:09:18 +0000956 case ePtraceFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000957 args->m_error.SetErrorString("Child ptrace failed.");
958 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000959 case eDupStdinFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000960 args->m_error.SetErrorString("Child open stdin failed.");
961 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000962 case eDupStdoutFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000963 args->m_error.SetErrorString("Child open stdout failed.");
964 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000965 case eDupStderrFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000966 args->m_error.SetErrorString("Child open stderr failed.");
967 break;
Daniel Malea6217d2a2013-01-08 14:49:22 +0000968 case eChdirFailed:
969 args->m_error.SetErrorString("Child failed to set working directory.");
970 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000971 case eExecFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000972 args->m_error.SetErrorString("Child exec failed.");
973 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000974 default:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000975 args->m_error.SetErrorString("Child returned unknown exit status.");
976 break;
977 }
978 goto FINISH;
979 }
980 assert(WIFSTOPPED(status) && wpid == pid &&
981 "Could not sync with inferior process.");
982
983#ifdef notyet
984 // Have the child raise an event on exit. This is used to keep the child in
985 // limbo until it is destroyed.
986 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0)
987 {
988 args->m_error.SetErrorToErrno();
989 goto FINISH;
990 }
991#endif
Ed Mastea02f5532013-07-02 16:45:16 +0000992 // Release the master terminal descriptor and pass it off to the
993 // ProcessMonitor instance. Similarly stash the inferior pid.
994 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000995 monitor->m_pid = pid;
996
997 // Set the terminal fd to be in non blocking mode (it simplifies the
998 // implementation of ProcessFreeBSD::GetSTDOUT to have a non-blocking
999 // descriptor to read from).
1000 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1001 goto FINISH;
1002
1003 // Update the process thread list with this new thread.
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +00001004 inferior.reset(new POSIXThread(*processSP, pid));
Ed Mastea02f5532013-07-02 16:45:16 +00001005 if (log)
1006 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001007 process.GetThreadList().AddThread(inferior);
1008
1009 // Let our process instance know the thread has stopped.
1010 process.SendMessage(ProcessMessage::Trace(pid));
1011
1012FINISH:
1013 return args->m_error.Success();
1014}
1015
1016bool
1017ProcessMonitor::EnableIPC()
1018{
1019 int fd[2];
1020
1021 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
1022 return false;
1023
1024 m_client_fd = fd[0];
1025 m_server_fd = fd[1];
1026 return true;
1027}
1028
1029void
1030ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1031{
1032 static const char *g_thread_name = "lldb.process.freebsd.operation";
1033
1034 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1035 return;
1036
1037 m_operation_thread =
1038 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1039}
1040
Johnny Chen9ed5b492012-01-05 21:48:15 +00001041void *
1042ProcessMonitor::AttachOpThread(void *arg)
1043{
1044 AttachArgs *args = static_cast<AttachArgs*>(arg);
1045
1046 if (!Attach(args))
1047 return NULL;
1048
1049 ServeOperation(args);
1050 return NULL;
1051}
1052
1053bool
1054ProcessMonitor::Attach(AttachArgs *args)
1055{
1056 lldb::pid_t pid = args->m_pid;
1057
1058 ProcessMonitor *monitor = args->m_monitor;
1059 ProcessFreeBSD &process = monitor->GetProcess();
Greg Clayton29d19302012-02-27 18:40:48 +00001060 lldb::ProcessSP processSP = process.shared_from_this();
Johnny Chen9ed5b492012-01-05 21:48:15 +00001061 ThreadList &tl = process.GetThreadList();
1062 lldb::ThreadSP inferior;
1063
1064 if (pid <= 1)
1065 {
1066 args->m_error.SetErrorToGenericError();
1067 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1068 goto FINISH;
1069 }
1070
1071 // Attach to the requested process.
1072 if (PTRACE(PT_ATTACH, pid, NULL, 0) < 0)
1073 {
1074 args->m_error.SetErrorToErrno();
1075 goto FINISH;
1076 }
1077
1078 int status;
1079 if ((status = waitpid(pid, NULL, 0)) < 0)
1080 {
1081 args->m_error.SetErrorToErrno();
1082 goto FINISH;
1083 }
1084
1085 // Update the process thread list with the attached thread.
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +00001086 inferior.reset(new POSIXThread(*processSP, pid));
Johnny Chen9ed5b492012-01-05 21:48:15 +00001087 tl.AddThread(inferior);
1088
1089 // Let our process instance know the thread has stopped.
1090 process.SendMessage(ProcessMessage::Trace(pid));
1091
1092 FINISH:
1093 return args->m_error.Success();
1094}
1095
1096bool
1097ProcessMonitor::MonitorCallback(void *callback_baton,
1098 lldb::pid_t pid,
1099 bool exited,
1100 int signal,
1101 int status)
1102{
1103 ProcessMessage message;
1104 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001105 ProcessFreeBSD *process = monitor->m_process;
Ed Mastea02f5532013-07-02 16:45:16 +00001106 assert(process);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001107 bool stop_monitoring;
Ed Maste819e3992013-07-17 14:02:20 +00001108 struct ptrace_lwpinfo plwp;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001109 int ptrace_err;
Johnny Chen9ed5b492012-01-05 21:48:15 +00001110
Ed Mastea02f5532013-07-02 16:45:16 +00001111 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1112
1113 if (exited)
1114 {
1115 if (log)
1116 log->Printf ("ProcessMonitor::%s() got exit signal, tid = %" PRIu64, __FUNCTION__, pid);
1117 message = ProcessMessage::Exit(pid, status);
1118 process->SendMessage(message);
1119 return pid == process->GetID();
1120 }
1121
Ed Maste819e3992013-07-17 14:02:20 +00001122 if (!monitor->GetLwpInfo(pid, &plwp, ptrace_err))
Johnny Chen9ed5b492012-01-05 21:48:15 +00001123 stop_monitoring = true; // pid is gone. Bail.
1124 else {
Ed Maste819e3992013-07-17 14:02:20 +00001125 switch (plwp.pl_siginfo.si_signo)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001126 {
1127 case SIGTRAP:
Ed Maste819e3992013-07-17 14:02:20 +00001128 message = MonitorSIGTRAP(monitor, &plwp.pl_siginfo, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001129 break;
1130
1131 default:
Ed Maste819e3992013-07-17 14:02:20 +00001132 message = MonitorSignal(monitor, &plwp.pl_siginfo, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001133 break;
1134 }
1135
1136 process->SendMessage(message);
1137 stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
1138 }
1139
1140 return stop_monitoring;
1141}
1142
1143ProcessMessage
1144ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
1145 const siginfo_t *info, lldb::pid_t pid)
1146{
1147 ProcessMessage message;
1148
Ed Mastea02f5532013-07-02 16:45:16 +00001149 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1150
Matt Kopec7de48462013-03-06 17:20:48 +00001151 assert(monitor);
1152 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Johnny Chen9ed5b492012-01-05 21:48:15 +00001153
1154 switch (info->si_code)
1155 {
1156 default:
1157 assert(false && "Unexpected SIGTRAP code!");
1158 break;
1159
1160 case (SIGTRAP /* | (PTRACE_EVENT_EXIT << 8) */):
1161 {
1162 // The inferior process is about to exit. Maintain the process in a
1163 // state of "limbo" until we are explicitly commanded to detach,
1164 // destroy, resume, etc.
1165 unsigned long data = 0;
1166 if (!monitor->GetEventMessage(pid, &data))
1167 data = -1;
Ed Mastea02f5532013-07-02 16:45:16 +00001168 if (log)
1169 log->Printf ("ProcessMonitor::%s() received exit? event, data = %lx, pid = %" PRIu64, __FUNCTION__, data, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001170 message = ProcessMessage::Limbo(pid, (data >> 8));
1171 break;
1172 }
1173
1174 case 0:
1175 case TRAP_TRACE:
Ed Mastea02f5532013-07-02 16:45:16 +00001176 if (log)
1177 log->Printf ("ProcessMonitor::%s() received trace event, pid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001178 message = ProcessMessage::Trace(pid);
1179 break;
1180
1181 case SI_KERNEL:
1182 case TRAP_BRKPT:
Ed Mastea02f5532013-07-02 16:45:16 +00001183 if (log)
1184 log->Printf ("ProcessMonitor::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001185 message = ProcessMessage::Break(pid);
1186 break;
1187 }
1188
1189 return message;
1190}
1191
1192ProcessMessage
1193ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
1194 const siginfo_t *info, lldb::pid_t pid)
1195{
1196 ProcessMessage message;
1197 int signo = info->si_signo;
1198
Ed Mastea02f5532013-07-02 16:45:16 +00001199 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1200
Johnny Chen9ed5b492012-01-05 21:48:15 +00001201 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1202 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1203 // kill(2) or raise(3). Similarly for tgkill(2) on FreeBSD.
1204 //
1205 // IOW, user generated signals never generate what we consider to be a
1206 // "crash".
1207 //
1208 // Similarly, ACK signals generated by this monitor.
1209 if (info->si_code == SI_USER)
1210 {
Ed Mastea02f5532013-07-02 16:45:16 +00001211 if (log)
1212 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
1213 __FUNCTION__,
1214 monitor->m_process->GetUnixSignals().GetSignalAsCString (signo),
1215 "SI_USER",
1216 info->si_pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001217 if (info->si_pid == getpid())
1218 return ProcessMessage::SignalDelivered(pid, signo);
1219 else
1220 return ProcessMessage::Signal(pid, signo);
1221 }
1222
Ed Mastea02f5532013-07-02 16:45:16 +00001223 if (log)
1224 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals().GetSignalAsCString (signo));
1225
Johnny Chen9ed5b492012-01-05 21:48:15 +00001226 if (signo == SIGSEGV) {
1227 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1228 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1229 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1230 }
1231
1232 if (signo == SIGILL) {
1233 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1234 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1235 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1236 }
1237
1238 if (signo == SIGFPE) {
1239 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1240 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1241 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1242 }
1243
1244 if (signo == SIGBUS) {
1245 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1246 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1247 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1248 }
1249
1250 // Everything else is "normal" and does not require any special action on
1251 // our part.
1252 return ProcessMessage::Signal(pid, signo);
1253}
1254
1255ProcessMessage::CrashReason
1256ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1257{
1258 ProcessMessage::CrashReason reason;
1259 assert(info->si_signo == SIGSEGV);
1260
1261 reason = ProcessMessage::eInvalidCrashReason;
1262
1263 switch (info->si_code)
1264 {
1265 default:
1266 assert(false && "unexpected si_code for SIGSEGV");
1267 break;
1268 case SEGV_MAPERR:
1269 reason = ProcessMessage::eInvalidAddress;
1270 break;
1271 case SEGV_ACCERR:
1272 reason = ProcessMessage::ePrivilegedAddress;
1273 break;
1274 }
1275
1276 return reason;
1277}
1278
1279ProcessMessage::CrashReason
1280ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
1281{
1282 ProcessMessage::CrashReason reason;
1283 assert(info->si_signo == SIGILL);
1284
1285 reason = ProcessMessage::eInvalidCrashReason;
1286
1287 switch (info->si_code)
1288 {
1289 default:
1290 assert(false && "unexpected si_code for SIGILL");
1291 break;
1292 case ILL_ILLOPC:
1293 reason = ProcessMessage::eIllegalOpcode;
1294 break;
1295 case ILL_ILLOPN:
1296 reason = ProcessMessage::eIllegalOperand;
1297 break;
1298 case ILL_ILLADR:
1299 reason = ProcessMessage::eIllegalAddressingMode;
1300 break;
1301 case ILL_ILLTRP:
1302 reason = ProcessMessage::eIllegalTrap;
1303 break;
1304 case ILL_PRVOPC:
1305 reason = ProcessMessage::ePrivilegedOpcode;
1306 break;
1307 case ILL_PRVREG:
1308 reason = ProcessMessage::ePrivilegedRegister;
1309 break;
1310 case ILL_COPROC:
1311 reason = ProcessMessage::eCoprocessorError;
1312 break;
1313 case ILL_BADSTK:
1314 reason = ProcessMessage::eInternalStackError;
1315 break;
1316 }
1317
1318 return reason;
1319}
1320
1321ProcessMessage::CrashReason
1322ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
1323{
1324 ProcessMessage::CrashReason reason;
1325 assert(info->si_signo == SIGFPE);
1326
1327 reason = ProcessMessage::eInvalidCrashReason;
1328
1329 switch (info->si_code)
1330 {
1331 default:
1332 assert(false && "unexpected si_code for SIGFPE");
1333 break;
1334 case FPE_INTDIV:
1335 reason = ProcessMessage::eIntegerDivideByZero;
1336 break;
1337 case FPE_INTOVF:
1338 reason = ProcessMessage::eIntegerOverflow;
1339 break;
1340 case FPE_FLTDIV:
1341 reason = ProcessMessage::eFloatDivideByZero;
1342 break;
1343 case FPE_FLTOVF:
1344 reason = ProcessMessage::eFloatOverflow;
1345 break;
1346 case FPE_FLTUND:
1347 reason = ProcessMessage::eFloatUnderflow;
1348 break;
1349 case FPE_FLTRES:
1350 reason = ProcessMessage::eFloatInexactResult;
1351 break;
1352 case FPE_FLTINV:
1353 reason = ProcessMessage::eFloatInvalidOperation;
1354 break;
1355 case FPE_FLTSUB:
1356 reason = ProcessMessage::eFloatSubscriptRange;
1357 break;
1358 }
1359
1360 return reason;
1361}
1362
1363ProcessMessage::CrashReason
1364ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
1365{
1366 ProcessMessage::CrashReason reason;
1367 assert(info->si_signo == SIGBUS);
1368
1369 reason = ProcessMessage::eInvalidCrashReason;
1370
1371 switch (info->si_code)
1372 {
1373 default:
1374 assert(false && "unexpected si_code for SIGBUS");
1375 break;
1376 case BUS_ADRALN:
1377 reason = ProcessMessage::eIllegalAlignment;
1378 break;
1379 case BUS_ADRERR:
1380 reason = ProcessMessage::eIllegalAddress;
1381 break;
1382 case BUS_OBJERR:
1383 reason = ProcessMessage::eHardwareError;
1384 break;
1385 }
1386
1387 return reason;
1388}
1389
1390void
1391ProcessMonitor::ServeOperation(OperationArgs *args)
1392{
1393 int status;
1394 pollfd fdset;
1395
1396 ProcessMonitor *monitor = args->m_monitor;
1397
1398 fdset.fd = monitor->m_server_fd;
1399 fdset.events = POLLIN | POLLPRI;
1400 fdset.revents = 0;
1401
1402 // We are finised with the arguments and are ready to go. Sync with the
1403 // parent thread and start serving operations on the inferior.
1404 sem_post(&args->m_semaphore);
1405
1406 for (;;)
1407 {
1408 if ((status = poll(&fdset, 1, -1)) < 0)
1409 {
1410 switch (errno)
1411 {
1412 default:
1413 assert(false && "Unexpected poll() failure!");
1414 continue;
1415
1416 case EINTR: continue; // Just poll again.
1417 case EBADF: return; // Connection terminated.
1418 }
1419 }
1420
1421 assert(status == 1 && "Too many descriptors!");
1422
1423 if (fdset.revents & POLLIN)
1424 {
1425 Operation *op = NULL;
1426
1427 READ_AGAIN:
1428 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1429 {
1430 // There is only one acceptable failure.
1431 assert(errno == EINTR);
1432 goto READ_AGAIN;
1433 }
Ed Mastea02f5532013-07-02 16:45:16 +00001434 if (status == 0)
1435 continue; // Poll again. The connection probably terminated.
Johnny Chen9ed5b492012-01-05 21:48:15 +00001436 assert(status == sizeof(op));
1437 op->Execute(monitor);
1438 write(fdset.fd, &op, sizeof(op));
1439 }
1440 }
1441}
1442
1443void
1444ProcessMonitor::DoOperation(Operation *op)
1445{
1446 int status;
1447 Operation *ack = NULL;
1448 Mutex::Locker lock(m_server_mutex);
1449
1450 // FIXME: Do proper error checking here.
1451 write(m_client_fd, &op, sizeof(op));
1452
1453READ_AGAIN:
1454 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1455 {
1456 // If interrupted by a signal handler try again. Otherwise the monitor
1457 // thread probably died and we have a stale file descriptor -- abort the
1458 // operation.
1459 if (errno == EINTR)
1460 goto READ_AGAIN;
1461 return;
1462 }
1463
1464 assert(status == sizeof(ack));
1465 assert(ack == op && "Invalid monitor thread response!");
1466}
1467
1468size_t
1469ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1470 Error &error)
1471{
1472 size_t result;
1473 ReadOperation op(vm_addr, buf, size, error, result);
1474 DoOperation(&op);
1475 return result;
1476}
1477
1478size_t
1479ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1480 lldb_private::Error &error)
1481{
1482 size_t result;
1483 WriteOperation op(vm_addr, buf, size, error, result);
1484 DoOperation(&op);
1485 return result;
1486}
1487
1488bool
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00001489ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +00001490 unsigned size, RegisterValue &value)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001491{
1492 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001493 ReadRegOperation op(tid, offset, size, value, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001494 DoOperation(&op);
1495 return result;
1496}
1497
1498bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001499ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00001500 const char* reg_name, const RegisterValue &value)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001501{
1502 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001503 WriteRegOperation op(tid, offset, value, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001504 DoOperation(&op);
1505 return result;
1506}
1507
1508bool
Matt Kopec7de48462013-03-06 17:20:48 +00001509ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001510{
1511 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001512 ReadGPROperation op(tid, buf, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001513 DoOperation(&op);
1514 return result;
1515}
1516
1517bool
Matt Kopec7de48462013-03-06 17:20:48 +00001518ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001519{
1520 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001521 ReadFPROperation op(tid, buf, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001522 DoOperation(&op);
1523 return result;
1524}
1525
1526bool
Ed Maste5d34af32013-06-24 15:09:18 +00001527ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1528{
1529 return false;
1530}
1531
1532bool
Matt Kopec7de48462013-03-06 17:20:48 +00001533ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001534{
1535 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001536 WriteGPROperation op(tid, buf, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001537 DoOperation(&op);
1538 return result;
1539}
1540
1541bool
Matt Kopec7de48462013-03-06 17:20:48 +00001542ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001543{
1544 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001545 WriteFPROperation op(tid, buf, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001546 DoOperation(&op);
1547 return result;
1548}
1549
1550bool
Ed Maste5d34af32013-06-24 15:09:18 +00001551ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1552{
1553 return false;
1554}
1555
1556bool
Johnny Chen9ed5b492012-01-05 21:48:15 +00001557ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
1558{
1559 bool result;
Ed Mastea02f5532013-07-02 16:45:16 +00001560 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1561
1562 if (log)
1563 log->Printf ("ProcessMonitor::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
1564 m_process->GetUnixSignals().GetSignalAsCString (signo));
Johnny Chen9ed5b492012-01-05 21:48:15 +00001565 ResumeOperation op(tid, signo, result);
1566 DoOperation(&op);
Ed Mastea02f5532013-07-02 16:45:16 +00001567 if (log)
1568 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
Johnny Chen9ed5b492012-01-05 21:48:15 +00001569 return result;
1570}
1571
1572bool
1573ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
1574{
1575 bool result;
1576 SingleStepOperation op(tid, signo, result);
1577 DoOperation(&op);
1578 return result;
1579}
1580
1581bool
1582ProcessMonitor::BringProcessIntoLimbo()
1583{
1584 bool result;
1585 KillOperation op(result);
1586 DoOperation(&op);
1587 return result;
1588}
1589
1590bool
Ed Maste819e3992013-07-17 14:02:20 +00001591ProcessMonitor::GetLwpInfo(lldb::tid_t tid, void *lwpinfo, int &ptrace_err)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001592{
1593 bool result;
Ed Maste819e3992013-07-17 14:02:20 +00001594 LwpInfoOperation op(tid, lwpinfo, result, ptrace_err);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001595 DoOperation(&op);
1596 return result;
1597}
1598
1599bool
1600ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1601{
1602 bool result;
1603 EventMessageOperation op(tid, message, result);
1604 DoOperation(&op);
1605 return result;
1606}
1607
Ed Mastea02f5532013-07-02 16:45:16 +00001608lldb_private::Error
Matt Kopecedee1822013-06-03 19:48:53 +00001609ProcessMonitor::Detach(lldb::tid_t tid)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001610{
Ed Mastea02f5532013-07-02 16:45:16 +00001611 lldb_private::Error error;
1612 if (tid != LLDB_INVALID_THREAD_ID)
1613 {
1614 DetachOperation op(error);
1615 DoOperation(&op);
1616 }
1617 return error;
Johnny Chen9ed5b492012-01-05 21:48:15 +00001618}
1619
1620bool
1621ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1622{
1623 int target_fd = open(path, flags, 0666);
1624
1625 if (target_fd == -1)
1626 return false;
1627
1628 return (dup2(target_fd, fd) == -1) ? false : true;
1629}
1630
1631void
1632ProcessMonitor::StopMonitoringChildProcess()
1633{
1634 lldb::thread_result_t thread_result;
1635
1636 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
1637 {
1638 Host::ThreadCancel(m_monitor_thread, NULL);
1639 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1640 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1641 }
1642}
1643
1644void
1645ProcessMonitor::StopMonitor()
1646{
1647 StopMonitoringChildProcess();
Ed Mastea02f5532013-07-02 16:45:16 +00001648 StopOpThread();
Johnny Chen9ed5b492012-01-05 21:48:15 +00001649 CloseFD(m_terminal_fd);
1650 CloseFD(m_client_fd);
1651 CloseFD(m_server_fd);
1652}
1653
1654void
Ed Mastea02f5532013-07-02 16:45:16 +00001655ProcessMonitor::StopOpThread()
1656{
1657 lldb::thread_result_t result;
1658
1659 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1660 return;
1661
1662 Host::ThreadCancel(m_operation_thread, NULL);
1663 Host::ThreadJoin(m_operation_thread, &result, NULL);
1664 m_operation_thread = LLDB_INVALID_HOST_THREAD;
1665}
1666
1667void
Johnny Chen9ed5b492012-01-05 21:48:15 +00001668ProcessMonitor::CloseFD(int &fd)
1669{
1670 if (fd != -1)
1671 {
1672 close(fd);
1673 fd = -1;
1674 }
1675}