blob: 12ae4712d53a3d45034a862a3987289b11635f61 [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),
Johnny Chen9ed5b492012-01-05 21:48:15 +0000707 m_terminal_fd(-1),
Ed Maste756e1ff2013-09-18 19:34:08 +0000708 m_operation(0)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000709{
Ed Maste756e1ff2013-09-18 19:34:08 +0000710 std::unique_ptr<LaunchArgs> args(new LaunchArgs(this, module, argv, envp,
711 stdin_path, stdout_path, stderr_path,
712 working_dir));
Johnny Chen9ed5b492012-01-05 21:48:15 +0000713
714
Ed Maste756e1ff2013-09-18 19:34:08 +0000715 sem_init(&m_operation_pending, 0, 0);
716 sem_init(&m_operation_done, 0, 0);
Johnny Chen9ed5b492012-01-05 21:48:15 +0000717
718 StartLaunchOpThread(args.get(), error);
719 if (!error.Success())
720 return;
721
722WAIT_AGAIN:
723 // Wait for the operation thread to initialize.
724 if (sem_wait(&args->m_semaphore))
725 {
726 if (errno == EINTR)
727 goto WAIT_AGAIN;
728 else
729 {
730 error.SetErrorToErrno();
731 return;
732 }
733 }
734
735 // Check that the launch was a success.
736 if (!args->m_error.Success())
737 {
Ed Mastea02f5532013-07-02 16:45:16 +0000738 StopOpThread();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000739 error = args->m_error;
740 return;
741 }
742
743 // Finally, start monitoring the child process for change in state.
744 m_monitor_thread = Host::StartMonitoringChildProcess(
745 ProcessMonitor::MonitorCallback, this, GetPID(), true);
746 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
747 {
748 error.SetErrorToGenericError();
749 error.SetErrorString("Process launch failed.");
750 return;
751 }
752}
753
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000754ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen9ed5b492012-01-05 21:48:15 +0000755 lldb::pid_t pid,
756 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000757 : m_process(static_cast<ProcessFreeBSD *>(process)),
Johnny Chen9ed5b492012-01-05 21:48:15 +0000758 m_operation_thread(LLDB_INVALID_HOST_THREAD),
759 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
760 m_pid(pid),
Johnny Chen9ed5b492012-01-05 21:48:15 +0000761 m_terminal_fd(-1),
Ed Maste756e1ff2013-09-18 19:34:08 +0000762 m_operation(0)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000763{
Ed Maste756e1ff2013-09-18 19:34:08 +0000764 sem_init(&m_operation_pending, 0, 0);
765 sem_init(&m_operation_done, 0, 0);
Johnny Chen9ed5b492012-01-05 21:48:15 +0000766
Johnny Chen9ed5b492012-01-05 21:48:15 +0000767
Ed Maste756e1ff2013-09-18 19:34:08 +0000768 std::unique_ptr<AttachArgs> args(new AttachArgs(this, pid));
Johnny Chen9ed5b492012-01-05 21:48:15 +0000769
770 StartAttachOpThread(args.get(), error);
771 if (!error.Success())
772 return;
773
774WAIT_AGAIN:
775 // Wait for the operation thread to initialize.
776 if (sem_wait(&args->m_semaphore))
777 {
778 if (errno == EINTR)
779 goto WAIT_AGAIN;
780 else
781 {
782 error.SetErrorToErrno();
783 return;
784 }
785 }
786
Ed Mastea02f5532013-07-02 16:45:16 +0000787 // Check that the attach was a success.
Johnny Chen9ed5b492012-01-05 21:48:15 +0000788 if (!args->m_error.Success())
789 {
Ed Mastea02f5532013-07-02 16:45:16 +0000790 StopOpThread();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000791 error = args->m_error;
792 return;
793 }
794
795 // Finally, start monitoring the child process for change in state.
796 m_monitor_thread = Host::StartMonitoringChildProcess(
797 ProcessMonitor::MonitorCallback, this, GetPID(), true);
798 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
799 {
800 error.SetErrorToGenericError();
801 error.SetErrorString("Process attach failed.");
802 return;
803 }
804}
805
806ProcessMonitor::~ProcessMonitor()
807{
808 StopMonitor();
809}
810
811//------------------------------------------------------------------------------
812// Thread setup and tear down.
813void
814ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
815{
816 static const char *g_thread_name = "lldb.process.freebsd.operation";
817
818 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
819 return;
820
821 m_operation_thread =
822 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
823}
824
Johnny Chen9ed5b492012-01-05 21:48:15 +0000825void *
826ProcessMonitor::LaunchOpThread(void *arg)
827{
828 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
829
830 if (!Launch(args)) {
831 sem_post(&args->m_semaphore);
832 return NULL;
833 }
834
835 ServeOperation(args);
836 return NULL;
837}
838
839bool
840ProcessMonitor::Launch(LaunchArgs *args)
841{
842 ProcessMonitor *monitor = args->m_monitor;
843 ProcessFreeBSD &process = monitor->GetProcess();
844 const char **argv = args->m_argv;
845 const char **envp = args->m_envp;
846 const char *stdin_path = args->m_stdin_path;
847 const char *stdout_path = args->m_stdout_path;
848 const char *stderr_path = args->m_stderr_path;
Daniel Malea6217d2a2013-01-08 14:49:22 +0000849 const char *working_dir = args->m_working_dir;
Ed Mastea02f5532013-07-02 16:45:16 +0000850
851 lldb_utility::PseudoTerminal terminal;
852 const size_t err_len = 1024;
853 char err_str[err_len];
Johnny Chen9ed5b492012-01-05 21:48:15 +0000854 lldb::pid_t pid;
855
Johnny Chen9ed5b492012-01-05 21:48:15 +0000856 // Propagate the environment if one is not supplied.
857 if (envp == NULL || envp[0] == NULL)
858 envp = const_cast<const char **>(environ);
859
Ed Mastea02f5532013-07-02 16:45:16 +0000860 if ((pid = terminal.Fork(err_str, err_len)) == -1)
861 {
862 args->m_error.SetErrorToGenericError();
863 args->m_error.SetErrorString("Process fork failed.");
864 goto FINISH;
865 }
866
Johnny Chen9ed5b492012-01-05 21:48:15 +0000867 // Recognized child exit status codes.
868 enum {
869 ePtraceFailed = 1,
870 eDupStdinFailed,
871 eDupStdoutFailed,
872 eDupStderrFailed,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000873 eChdirFailed,
Johnny Chen9ed5b492012-01-05 21:48:15 +0000874 eExecFailed
875 };
876
Johnny Chen9ed5b492012-01-05 21:48:15 +0000877 // Child process.
878 if (pid == 0)
879 {
880 // Trace this process.
881 if (PTRACE(PT_TRACE_ME, 0, NULL, 0) < 0)
882 exit(ePtraceFailed);
883
884 // Do not inherit setgid powers.
885 setgid(getgid());
886
887 // Let us have our own process group.
888 setpgid(0, 0);
889
890 // Dup file descriptors if needed.
891 //
892 // FIXME: If two or more of the paths are the same we needlessly open
893 // the same file multiple times.
894 if (stdin_path != NULL && stdin_path[0])
895 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
896 exit(eDupStdinFailed);
897
898 if (stdout_path != NULL && stdout_path[0])
899 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
900 exit(eDupStdoutFailed);
901
902 if (stderr_path != NULL && stderr_path[0])
903 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
904 exit(eDupStderrFailed);
905
Daniel Malea6217d2a2013-01-08 14:49:22 +0000906 // Change working directory
907 if (working_dir != NULL && working_dir[0])
908 if (0 != ::chdir(working_dir))
909 exit(eChdirFailed);
910
Johnny Chen9ed5b492012-01-05 21:48:15 +0000911 // Execute. We should never return.
912 execve(argv[0],
913 const_cast<char *const *>(argv),
914 const_cast<char *const *>(envp));
915 exit(eExecFailed);
916 }
917
918 // Wait for the child process to to trap on its call to execve.
919 ::pid_t wpid;
920 int status;
921 if ((wpid = waitpid(pid, &status, 0)) < 0)
922 {
923 args->m_error.SetErrorToErrno();
924 goto FINISH;
925 }
926 else if (WIFEXITED(status))
927 {
928 // open, dup or execve likely failed for some reason.
929 args->m_error.SetErrorToGenericError();
930 switch (WEXITSTATUS(status))
931 {
Ed Maste5d34af32013-06-24 15:09:18 +0000932 case ePtraceFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000933 args->m_error.SetErrorString("Child ptrace failed.");
934 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000935 case eDupStdinFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000936 args->m_error.SetErrorString("Child open stdin failed.");
937 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000938 case eDupStdoutFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000939 args->m_error.SetErrorString("Child open stdout failed.");
940 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000941 case eDupStderrFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000942 args->m_error.SetErrorString("Child open stderr failed.");
943 break;
Daniel Malea6217d2a2013-01-08 14:49:22 +0000944 case eChdirFailed:
945 args->m_error.SetErrorString("Child failed to set working directory.");
946 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000947 case eExecFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000948 args->m_error.SetErrorString("Child exec failed.");
949 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000950 default:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000951 args->m_error.SetErrorString("Child returned unknown exit status.");
952 break;
953 }
954 goto FINISH;
955 }
956 assert(WIFSTOPPED(status) && wpid == pid &&
957 "Could not sync with inferior process.");
958
959#ifdef notyet
960 // Have the child raise an event on exit. This is used to keep the child in
961 // limbo until it is destroyed.
962 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0)
963 {
964 args->m_error.SetErrorToErrno();
965 goto FINISH;
966 }
967#endif
Ed Mastea02f5532013-07-02 16:45:16 +0000968 // Release the master terminal descriptor and pass it off to the
969 // ProcessMonitor instance. Similarly stash the inferior pid.
970 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000971 monitor->m_pid = pid;
972
973 // Set the terminal fd to be in non blocking mode (it simplifies the
974 // implementation of ProcessFreeBSD::GetSTDOUT to have a non-blocking
975 // descriptor to read from).
976 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
977 goto FINISH;
978
Ed Mastee5441432013-09-03 23:55:30 +0000979 process.SendMessage(ProcessMessage::Attach(pid));
Johnny Chen9ed5b492012-01-05 21:48:15 +0000980
981FINISH:
982 return args->m_error.Success();
983}
984
Johnny Chen9ed5b492012-01-05 21:48:15 +0000985void
986ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
987{
988 static const char *g_thread_name = "lldb.process.freebsd.operation";
989
990 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
991 return;
992
993 m_operation_thread =
994 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
995}
996
Johnny Chen9ed5b492012-01-05 21:48:15 +0000997void *
998ProcessMonitor::AttachOpThread(void *arg)
999{
1000 AttachArgs *args = static_cast<AttachArgs*>(arg);
1001
1002 if (!Attach(args))
1003 return NULL;
1004
1005 ServeOperation(args);
1006 return NULL;
1007}
1008
1009bool
1010ProcessMonitor::Attach(AttachArgs *args)
1011{
1012 lldb::pid_t pid = args->m_pid;
1013
1014 ProcessMonitor *monitor = args->m_monitor;
1015 ProcessFreeBSD &process = monitor->GetProcess();
Johnny Chen9ed5b492012-01-05 21:48:15 +00001016
1017 if (pid <= 1)
1018 {
1019 args->m_error.SetErrorToGenericError();
1020 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1021 goto FINISH;
1022 }
1023
1024 // Attach to the requested process.
1025 if (PTRACE(PT_ATTACH, pid, NULL, 0) < 0)
1026 {
1027 args->m_error.SetErrorToErrno();
1028 goto FINISH;
1029 }
1030
1031 int status;
1032 if ((status = waitpid(pid, NULL, 0)) < 0)
1033 {
1034 args->m_error.SetErrorToErrno();
1035 goto FINISH;
1036 }
1037
Ed Mastee5441432013-09-03 23:55:30 +00001038 process.SendMessage(ProcessMessage::Attach(pid));
Johnny Chen9ed5b492012-01-05 21:48:15 +00001039
Ed Mastee5441432013-09-03 23:55:30 +00001040FINISH:
Johnny Chen9ed5b492012-01-05 21:48:15 +00001041 return args->m_error.Success();
1042}
1043
1044bool
1045ProcessMonitor::MonitorCallback(void *callback_baton,
1046 lldb::pid_t pid,
1047 bool exited,
1048 int signal,
1049 int status)
1050{
1051 ProcessMessage message;
1052 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001053 ProcessFreeBSD *process = monitor->m_process;
Ed Mastea02f5532013-07-02 16:45:16 +00001054 assert(process);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001055 bool stop_monitoring;
Ed Maste819e3992013-07-17 14:02:20 +00001056 struct ptrace_lwpinfo plwp;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001057 int ptrace_err;
Johnny Chen9ed5b492012-01-05 21:48:15 +00001058
Ed Mastea02f5532013-07-02 16:45:16 +00001059 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1060
1061 if (exited)
1062 {
1063 if (log)
1064 log->Printf ("ProcessMonitor::%s() got exit signal, tid = %" PRIu64, __FUNCTION__, pid);
1065 message = ProcessMessage::Exit(pid, status);
1066 process->SendMessage(message);
1067 return pid == process->GetID();
1068 }
1069
Ed Maste819e3992013-07-17 14:02:20 +00001070 if (!monitor->GetLwpInfo(pid, &plwp, ptrace_err))
Johnny Chen9ed5b492012-01-05 21:48:15 +00001071 stop_monitoring = true; // pid is gone. Bail.
1072 else {
Ed Maste819e3992013-07-17 14:02:20 +00001073 switch (plwp.pl_siginfo.si_signo)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001074 {
1075 case SIGTRAP:
Ed Maste819e3992013-07-17 14:02:20 +00001076 message = MonitorSIGTRAP(monitor, &plwp.pl_siginfo, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001077 break;
1078
1079 default:
Ed Maste819e3992013-07-17 14:02:20 +00001080 message = MonitorSignal(monitor, &plwp.pl_siginfo, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001081 break;
1082 }
1083
1084 process->SendMessage(message);
1085 stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
1086 }
1087
1088 return stop_monitoring;
1089}
1090
1091ProcessMessage
1092ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
1093 const siginfo_t *info, lldb::pid_t pid)
1094{
1095 ProcessMessage message;
1096
Ed Mastea02f5532013-07-02 16:45:16 +00001097 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1098
Matt Kopec7de48462013-03-06 17:20:48 +00001099 assert(monitor);
1100 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Johnny Chen9ed5b492012-01-05 21:48:15 +00001101
1102 switch (info->si_code)
1103 {
1104 default:
1105 assert(false && "Unexpected SIGTRAP code!");
1106 break;
1107
1108 case (SIGTRAP /* | (PTRACE_EVENT_EXIT << 8) */):
1109 {
1110 // The inferior process is about to exit. Maintain the process in a
1111 // state of "limbo" until we are explicitly commanded to detach,
1112 // destroy, resume, etc.
1113 unsigned long data = 0;
1114 if (!monitor->GetEventMessage(pid, &data))
1115 data = -1;
Ed Mastea02f5532013-07-02 16:45:16 +00001116 if (log)
1117 log->Printf ("ProcessMonitor::%s() received exit? event, data = %lx, pid = %" PRIu64, __FUNCTION__, data, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001118 message = ProcessMessage::Limbo(pid, (data >> 8));
1119 break;
1120 }
1121
1122 case 0:
1123 case TRAP_TRACE:
Ed Mastea02f5532013-07-02 16:45:16 +00001124 if (log)
1125 log->Printf ("ProcessMonitor::%s() received trace event, pid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001126 message = ProcessMessage::Trace(pid);
1127 break;
1128
1129 case SI_KERNEL:
1130 case TRAP_BRKPT:
Ed Mastea02f5532013-07-02 16:45:16 +00001131 if (log)
1132 log->Printf ("ProcessMonitor::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001133 message = ProcessMessage::Break(pid);
1134 break;
1135 }
1136
1137 return message;
1138}
1139
1140ProcessMessage
1141ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
1142 const siginfo_t *info, lldb::pid_t pid)
1143{
1144 ProcessMessage message;
1145 int signo = info->si_signo;
1146
Ed Mastea02f5532013-07-02 16:45:16 +00001147 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1148
Johnny Chen9ed5b492012-01-05 21:48:15 +00001149 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1150 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1151 // kill(2) or raise(3). Similarly for tgkill(2) on FreeBSD.
1152 //
1153 // IOW, user generated signals never generate what we consider to be a
1154 // "crash".
1155 //
1156 // Similarly, ACK signals generated by this monitor.
1157 if (info->si_code == SI_USER)
1158 {
Ed Mastea02f5532013-07-02 16:45:16 +00001159 if (log)
1160 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
1161 __FUNCTION__,
1162 monitor->m_process->GetUnixSignals().GetSignalAsCString (signo),
1163 "SI_USER",
1164 info->si_pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001165 if (info->si_pid == getpid())
1166 return ProcessMessage::SignalDelivered(pid, signo);
1167 else
1168 return ProcessMessage::Signal(pid, signo);
1169 }
1170
Ed Mastea02f5532013-07-02 16:45:16 +00001171 if (log)
1172 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals().GetSignalAsCString (signo));
1173
Johnny Chen9ed5b492012-01-05 21:48:15 +00001174 if (signo == SIGSEGV) {
1175 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1176 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1177 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1178 }
1179
1180 if (signo == SIGILL) {
1181 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1182 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1183 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1184 }
1185
1186 if (signo == SIGFPE) {
1187 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1188 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1189 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1190 }
1191
1192 if (signo == SIGBUS) {
1193 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1194 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1195 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1196 }
1197
1198 // Everything else is "normal" and does not require any special action on
1199 // our part.
1200 return ProcessMessage::Signal(pid, signo);
1201}
1202
1203ProcessMessage::CrashReason
1204ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1205{
1206 ProcessMessage::CrashReason reason;
1207 assert(info->si_signo == SIGSEGV);
1208
1209 reason = ProcessMessage::eInvalidCrashReason;
1210
1211 switch (info->si_code)
1212 {
1213 default:
1214 assert(false && "unexpected si_code for SIGSEGV");
1215 break;
1216 case SEGV_MAPERR:
1217 reason = ProcessMessage::eInvalidAddress;
1218 break;
1219 case SEGV_ACCERR:
1220 reason = ProcessMessage::ePrivilegedAddress;
1221 break;
1222 }
1223
1224 return reason;
1225}
1226
1227ProcessMessage::CrashReason
1228ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
1229{
1230 ProcessMessage::CrashReason reason;
1231 assert(info->si_signo == SIGILL);
1232
1233 reason = ProcessMessage::eInvalidCrashReason;
1234
1235 switch (info->si_code)
1236 {
1237 default:
1238 assert(false && "unexpected si_code for SIGILL");
1239 break;
1240 case ILL_ILLOPC:
1241 reason = ProcessMessage::eIllegalOpcode;
1242 break;
1243 case ILL_ILLOPN:
1244 reason = ProcessMessage::eIllegalOperand;
1245 break;
1246 case ILL_ILLADR:
1247 reason = ProcessMessage::eIllegalAddressingMode;
1248 break;
1249 case ILL_ILLTRP:
1250 reason = ProcessMessage::eIllegalTrap;
1251 break;
1252 case ILL_PRVOPC:
1253 reason = ProcessMessage::ePrivilegedOpcode;
1254 break;
1255 case ILL_PRVREG:
1256 reason = ProcessMessage::ePrivilegedRegister;
1257 break;
1258 case ILL_COPROC:
1259 reason = ProcessMessage::eCoprocessorError;
1260 break;
1261 case ILL_BADSTK:
1262 reason = ProcessMessage::eInternalStackError;
1263 break;
1264 }
1265
1266 return reason;
1267}
1268
1269ProcessMessage::CrashReason
1270ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
1271{
1272 ProcessMessage::CrashReason reason;
1273 assert(info->si_signo == SIGFPE);
1274
1275 reason = ProcessMessage::eInvalidCrashReason;
1276
1277 switch (info->si_code)
1278 {
1279 default:
1280 assert(false && "unexpected si_code for SIGFPE");
1281 break;
1282 case FPE_INTDIV:
1283 reason = ProcessMessage::eIntegerDivideByZero;
1284 break;
1285 case FPE_INTOVF:
1286 reason = ProcessMessage::eIntegerOverflow;
1287 break;
1288 case FPE_FLTDIV:
1289 reason = ProcessMessage::eFloatDivideByZero;
1290 break;
1291 case FPE_FLTOVF:
1292 reason = ProcessMessage::eFloatOverflow;
1293 break;
1294 case FPE_FLTUND:
1295 reason = ProcessMessage::eFloatUnderflow;
1296 break;
1297 case FPE_FLTRES:
1298 reason = ProcessMessage::eFloatInexactResult;
1299 break;
1300 case FPE_FLTINV:
1301 reason = ProcessMessage::eFloatInvalidOperation;
1302 break;
1303 case FPE_FLTSUB:
1304 reason = ProcessMessage::eFloatSubscriptRange;
1305 break;
1306 }
1307
1308 return reason;
1309}
1310
1311ProcessMessage::CrashReason
1312ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
1313{
1314 ProcessMessage::CrashReason reason;
1315 assert(info->si_signo == SIGBUS);
1316
1317 reason = ProcessMessage::eInvalidCrashReason;
1318
1319 switch (info->si_code)
1320 {
1321 default:
1322 assert(false && "unexpected si_code for SIGBUS");
1323 break;
1324 case BUS_ADRALN:
1325 reason = ProcessMessage::eIllegalAlignment;
1326 break;
1327 case BUS_ADRERR:
1328 reason = ProcessMessage::eIllegalAddress;
1329 break;
1330 case BUS_OBJERR:
1331 reason = ProcessMessage::eHardwareError;
1332 break;
1333 }
1334
1335 return reason;
1336}
1337
1338void
1339ProcessMonitor::ServeOperation(OperationArgs *args)
1340{
1341 int status;
Johnny Chen9ed5b492012-01-05 21:48:15 +00001342
1343 ProcessMonitor *monitor = args->m_monitor;
1344
Johnny Chen9ed5b492012-01-05 21:48:15 +00001345 // We are finised with the arguments and are ready to go. Sync with the
1346 // parent thread and start serving operations on the inferior.
1347 sem_post(&args->m_semaphore);
1348
1349 for (;;)
1350 {
Ed Maste756e1ff2013-09-18 19:34:08 +00001351 // wait for next pending operation
1352 sem_wait(&monitor->m_operation_pending);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001353
Ed Maste756e1ff2013-09-18 19:34:08 +00001354 monitor->m_operation->Execute(monitor);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001355
Ed Maste756e1ff2013-09-18 19:34:08 +00001356 // notify calling thread that operation is complete
1357 sem_post(&monitor->m_operation_done);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001358 }
1359}
1360
1361void
1362ProcessMonitor::DoOperation(Operation *op)
1363{
Ed Maste756e1ff2013-09-18 19:34:08 +00001364 Mutex::Locker lock(m_operation_mutex);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001365
Ed Maste756e1ff2013-09-18 19:34:08 +00001366 m_operation = op;
Johnny Chen9ed5b492012-01-05 21:48:15 +00001367
Ed Maste756e1ff2013-09-18 19:34:08 +00001368 // notify operation thread that an operation is ready to be processed
1369 sem_post(&m_operation_pending);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001370
Ed Maste756e1ff2013-09-18 19:34:08 +00001371 // wait for operation to complete
1372 sem_wait(&m_operation_done);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001373}
1374
1375size_t
1376ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1377 Error &error)
1378{
1379 size_t result;
1380 ReadOperation op(vm_addr, buf, size, error, result);
1381 DoOperation(&op);
1382 return result;
1383}
1384
1385size_t
1386ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1387 lldb_private::Error &error)
1388{
1389 size_t result;
1390 WriteOperation op(vm_addr, buf, size, error, result);
1391 DoOperation(&op);
1392 return result;
1393}
1394
1395bool
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00001396ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +00001397 unsigned size, RegisterValue &value)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001398{
1399 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001400 ReadRegOperation op(tid, offset, size, value, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001401 DoOperation(&op);
1402 return result;
1403}
1404
1405bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001406ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00001407 const char* reg_name, const RegisterValue &value)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001408{
1409 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001410 WriteRegOperation op(tid, offset, value, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001411 DoOperation(&op);
1412 return result;
1413}
1414
1415bool
Matt Kopec7de48462013-03-06 17:20:48 +00001416ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001417{
1418 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001419 ReadGPROperation op(tid, buf, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001420 DoOperation(&op);
1421 return result;
1422}
1423
1424bool
Matt Kopec7de48462013-03-06 17:20:48 +00001425ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001426{
1427 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001428 ReadFPROperation op(tid, buf, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001429 DoOperation(&op);
1430 return result;
1431}
1432
1433bool
Ed Maste5d34af32013-06-24 15:09:18 +00001434ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1435{
1436 return false;
1437}
1438
1439bool
Matt Kopec7de48462013-03-06 17:20:48 +00001440ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001441{
1442 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001443 WriteGPROperation op(tid, buf, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001444 DoOperation(&op);
1445 return result;
1446}
1447
1448bool
Matt Kopec7de48462013-03-06 17:20:48 +00001449ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001450{
1451 bool result;
Ed Maste6f066412013-07-04 21:47:32 +00001452 WriteFPROperation op(tid, buf, result);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001453 DoOperation(&op);
1454 return result;
1455}
1456
1457bool
Ed Maste5d34af32013-06-24 15:09:18 +00001458ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1459{
1460 return false;
1461}
1462
1463bool
Johnny Chen9ed5b492012-01-05 21:48:15 +00001464ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
1465{
1466 bool result;
Ed Mastea02f5532013-07-02 16:45:16 +00001467 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1468
1469 if (log)
1470 log->Printf ("ProcessMonitor::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
1471 m_process->GetUnixSignals().GetSignalAsCString (signo));
Johnny Chen9ed5b492012-01-05 21:48:15 +00001472 ResumeOperation op(tid, signo, result);
1473 DoOperation(&op);
Ed Mastea02f5532013-07-02 16:45:16 +00001474 if (log)
1475 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
Johnny Chen9ed5b492012-01-05 21:48:15 +00001476 return result;
1477}
1478
1479bool
1480ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
1481{
1482 bool result;
1483 SingleStepOperation op(tid, signo, result);
1484 DoOperation(&op);
1485 return result;
1486}
1487
1488bool
1489ProcessMonitor::BringProcessIntoLimbo()
1490{
1491 bool result;
1492 KillOperation op(result);
1493 DoOperation(&op);
1494 return result;
1495}
1496
1497bool
Ed Maste819e3992013-07-17 14:02:20 +00001498ProcessMonitor::GetLwpInfo(lldb::tid_t tid, void *lwpinfo, int &ptrace_err)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001499{
1500 bool result;
Ed Maste819e3992013-07-17 14:02:20 +00001501 LwpInfoOperation op(tid, lwpinfo, result, ptrace_err);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001502 DoOperation(&op);
1503 return result;
1504}
1505
1506bool
1507ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1508{
1509 bool result;
1510 EventMessageOperation op(tid, message, result);
1511 DoOperation(&op);
1512 return result;
1513}
1514
Ed Mastea02f5532013-07-02 16:45:16 +00001515lldb_private::Error
Matt Kopecedee1822013-06-03 19:48:53 +00001516ProcessMonitor::Detach(lldb::tid_t tid)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001517{
Ed Mastea02f5532013-07-02 16:45:16 +00001518 lldb_private::Error error;
1519 if (tid != LLDB_INVALID_THREAD_ID)
1520 {
1521 DetachOperation op(error);
1522 DoOperation(&op);
1523 }
1524 return error;
Johnny Chen9ed5b492012-01-05 21:48:15 +00001525}
1526
1527bool
1528ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1529{
1530 int target_fd = open(path, flags, 0666);
1531
1532 if (target_fd == -1)
1533 return false;
1534
1535 return (dup2(target_fd, fd) == -1) ? false : true;
1536}
1537
1538void
1539ProcessMonitor::StopMonitoringChildProcess()
1540{
1541 lldb::thread_result_t thread_result;
1542
1543 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
1544 {
1545 Host::ThreadCancel(m_monitor_thread, NULL);
1546 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1547 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1548 }
1549}
1550
1551void
1552ProcessMonitor::StopMonitor()
1553{
1554 StopMonitoringChildProcess();
Ed Mastea02f5532013-07-02 16:45:16 +00001555 StopOpThread();
Ed Maste756e1ff2013-09-18 19:34:08 +00001556 sem_destroy(&m_operation_pending);
1557 sem_destroy(&m_operation_done);
1558
Andrew Kaylor5e268992013-09-14 00:17:31 +00001559 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
1560 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
1561 // the descriptor to a ConnectionFileDescriptor object. Consequently
1562 // even though still has the file descriptor, we shouldn't close it here.
Johnny Chen9ed5b492012-01-05 21:48:15 +00001563}
1564
Andrew Kaylord4d54992013-09-17 00:30:24 +00001565// FIXME: On Linux, when a new thread is created, we receive to notifications,
1566// (1) a SIGTRAP|PTRACE_EVENT_CLONE from the main process thread with the
1567// child thread id as additional information, and (2) a SIGSTOP|SI_USER from
1568// the new child thread indicating that it has is stopped because we attached.
1569// We have no guarantee of the order in which these arrive, but we need both
1570// before we are ready to proceed. We currently keep a list of threads which
1571// have sent the initial SIGSTOP|SI_USER event. Then when we receive the
1572// SIGTRAP|PTRACE_EVENT_CLONE notification, if the initial stop has not occurred
1573// we call ProcessMonitor::WaitForInitialTIDStop() to wait for it.
1574//
1575// Right now, the above logic is in ProcessPOSIX, so we need a definition of
1576// this function in the FreeBSD ProcessMonitor implementation even if it isn't
1577// logically needed.
1578//
1579// We really should figure out what actually happens on FreeBSD and move the
1580// Linux-specific logic out of ProcessPOSIX as needed.
1581
1582bool
1583ProcessMonitor::WaitForInitialTIDStop(lldb::tid_t tid)
1584{
1585 return true;
1586}
1587
Johnny Chen9ed5b492012-01-05 21:48:15 +00001588void
Ed Mastea02f5532013-07-02 16:45:16 +00001589ProcessMonitor::StopOpThread()
1590{
1591 lldb::thread_result_t result;
1592
1593 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1594 return;
1595
1596 Host::ThreadCancel(m_operation_thread, NULL);
1597 Host::ThreadJoin(m_operation_thread, &result, NULL);
1598 m_operation_thread = LLDB_INVALID_HOST_THREAD;
1599}