blob: e02e4209641a110c22d1d33ad9187cd88a2f4dbc [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//------------------------------------------------------------------------------
243/// @class ReadOperation
244/// @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:
278 ReadRegOperation(unsigned offset, unsigned size, RegisterValue &value, bool &result)
279 : m_offset(offset), m_size(size), m_value(value), m_result(result)
280 { }
281
282 void Execute(ProcessMonitor *monitor);
283
284private:
285 unsigned m_offset;
286 unsigned m_size;
287 RegisterValue &m_value;
288 bool &m_result;
289};
290
291void
292ReadRegOperation::Execute(ProcessMonitor *monitor)
293{
294 lldb::pid_t pid = monitor->GetPID();
295 struct reg regs;
296 int rc;
297
298 if ((rc = PTRACE(PT_GETREGS, pid, (caddr_t)&regs, 0)) < 0) {
299 m_result = false;
300 } else {
301 if (m_size == sizeof(uintptr_t))
302 m_value = *(uintptr_t *)(((caddr_t)&regs) + m_offset);
303 else
304 memcpy(&m_value, (((caddr_t)&regs) + m_offset), m_size);
305 m_result = true;
306 }
307}
308
309//------------------------------------------------------------------------------
310/// @class WriteRegOperation
311/// @brief Implements ProcessMonitor::WriteRegisterValue.
312class WriteRegOperation : public Operation
313{
314public:
315 WriteRegOperation(unsigned offset, const RegisterValue &value, bool &result)
316 : m_offset(offset), m_value(value), m_result(result)
317 { }
318
319 void Execute(ProcessMonitor *monitor);
320
321private:
322 unsigned m_offset;
323 const RegisterValue &m_value;
324 bool &m_result;
325};
326
327void
328WriteRegOperation::Execute(ProcessMonitor *monitor)
329{
330 lldb::pid_t pid = monitor->GetPID();
331 struct reg regs;
332
333 if (PTRACE(PT_GETREGS, pid, (caddr_t)&regs, 0) < 0) {
334 m_result = false;
335 return;
336 }
337 *(uintptr_t *)(((caddr_t)&regs) + m_offset) = (uintptr_t)m_value.GetAsUInt64();
338 if (PTRACE(PT_SETREGS, pid, (caddr_t)&regs, 0) < 0)
339 m_result = false;
340 else
341 m_result = true;
342}
343
344//------------------------------------------------------------------------------
345/// @class ReadGPROperation
346/// @brief Implements ProcessMonitor::ReadGPR.
347class ReadGPROperation : public Operation
348{
349public:
350 ReadGPROperation(void *buf, bool &result)
351 : m_buf(buf), m_result(result)
352 { }
353
354 void Execute(ProcessMonitor *monitor);
355
356private:
357 void *m_buf;
358 bool &m_result;
359};
360
361void
362ReadGPROperation::Execute(ProcessMonitor *monitor)
363{
364 int rc;
365
366 errno = 0;
367 rc = PTRACE(PT_GETREGS, monitor->GetPID(), (caddr_t)m_buf, 0);
368 if (errno != 0)
369 m_result = false;
370 else
371 m_result = true;
372}
373
374//------------------------------------------------------------------------------
375/// @class ReadFPROperation
376/// @brief Implements ProcessMonitor::ReadFPR.
377class ReadFPROperation : public Operation
378{
379public:
380 ReadFPROperation(void *buf, bool &result)
381 : m_buf(buf), m_result(result)
382 { }
383
384 void Execute(ProcessMonitor *monitor);
385
386private:
387 void *m_buf;
388 bool &m_result;
389};
390
391void
392ReadFPROperation::Execute(ProcessMonitor *monitor)
393{
394 if (PTRACE(PT_GETFPREGS, monitor->GetPID(), (caddr_t)m_buf, 0) < 0)
395 m_result = false;
396 else
397 m_result = true;
398}
399
400//------------------------------------------------------------------------------
401/// @class WriteGPROperation
402/// @brief Implements ProcessMonitor::WriteGPR.
403class WriteGPROperation : public Operation
404{
405public:
406 WriteGPROperation(void *buf, bool &result)
407 : m_buf(buf), m_result(result)
408 { }
409
410 void Execute(ProcessMonitor *monitor);
411
412private:
413 void *m_buf;
414 bool &m_result;
415};
416
417void
418WriteGPROperation::Execute(ProcessMonitor *monitor)
419{
420 if (PTRACE(PT_SETREGS, monitor->GetPID(), (caddr_t)m_buf, 0) < 0)
421 m_result = false;
422 else
423 m_result = true;
424}
425
426//------------------------------------------------------------------------------
427/// @class WriteFPROperation
428/// @brief Implements ProcessMonitor::WriteFPR.
429class WriteFPROperation : public Operation
430{
431public:
432 WriteFPROperation(void *buf, bool &result)
433 : m_buf(buf), m_result(result)
434 { }
435
436 void Execute(ProcessMonitor *monitor);
437
438private:
439 void *m_buf;
440 bool &m_result;
441};
442
443void
444WriteFPROperation::Execute(ProcessMonitor *monitor)
445{
446 if (PTRACE(PT_SETFPREGS, monitor->GetPID(), (caddr_t)m_buf, 0) < 0)
447 m_result = false;
448 else
449 m_result = true;
450}
451
452//------------------------------------------------------------------------------
453/// @class ResumeOperation
454/// @brief Implements ProcessMonitor::Resume.
455class ResumeOperation : public Operation
456{
457public:
458 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
459 m_tid(tid), m_signo(signo), m_result(result) { }
460
461 void Execute(ProcessMonitor *monitor);
462
463private:
464 lldb::tid_t m_tid;
465 uint32_t m_signo;
466 bool &m_result;
467};
468
469void
470ResumeOperation::Execute(ProcessMonitor *monitor)
471{
472 int data = 0;
473
474 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
475 data = m_signo;
476
477 if (PTRACE(PT_CONTINUE, m_tid, (caddr_t)1, data))
Ed Mastea02f5532013-07-02 16:45:16 +0000478 {
479 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
480
481 if (log)
482 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, strerror(errno));
Johnny Chen9ed5b492012-01-05 21:48:15 +0000483 m_result = false;
Ed Mastea02f5532013-07-02 16:45:16 +0000484 }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000485 else
486 m_result = true;
487}
488
489//------------------------------------------------------------------------------
Ed Maste428a6782013-06-24 15:04:47 +0000490/// @class SingleStepOperation
Johnny Chen9ed5b492012-01-05 21:48:15 +0000491/// @brief Implements ProcessMonitor::SingleStep.
492class SingleStepOperation : public Operation
493{
494public:
495 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
496 : m_tid(tid), m_signo(signo), m_result(result) { }
497
498 void Execute(ProcessMonitor *monitor);
499
500private:
501 lldb::tid_t m_tid;
502 uint32_t m_signo;
503 bool &m_result;
504};
505
506void
507SingleStepOperation::Execute(ProcessMonitor *monitor)
508{
509 int data = 0;
510
511 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
512 data = m_signo;
513
514 if (PTRACE(PT_STEP, m_tid, NULL, data))
515 m_result = false;
516 else
517 m_result = true;
518}
519
520//------------------------------------------------------------------------------
521/// @class SiginfoOperation
522/// @brief Implements ProcessMonitor::GetSignalInfo.
523class SiginfoOperation : public Operation
524{
525public:
Daniel Maleaa35970a2012-11-23 18:09:58 +0000526 SiginfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
527 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000528
529 void Execute(ProcessMonitor *monitor);
530
531private:
532 lldb::tid_t m_tid;
533 void *m_info;
534 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000535 int &m_err;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000536};
537
538void
539SiginfoOperation::Execute(ProcessMonitor *monitor)
540{
541 struct ptrace_lwpinfo plwp;
542
Daniel Maleaa35970a2012-11-23 18:09:58 +0000543 if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp))) {
Johnny Chen9ed5b492012-01-05 21:48:15 +0000544 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000545 m_err = errno;
546 } else {
Johnny Chen9ed5b492012-01-05 21:48:15 +0000547 memcpy(m_info, &plwp.pl_siginfo, sizeof(siginfo_t));
548 m_result = true;
549 }
550}
551
552//------------------------------------------------------------------------------
553/// @class EventMessageOperation
554/// @brief Implements ProcessMonitor::GetEventMessage.
555class EventMessageOperation : public Operation
556{
557public:
558 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
559 : m_tid(tid), m_message(message), m_result(result) { }
560
561 void Execute(ProcessMonitor *monitor);
562
563private:
564 lldb::tid_t m_tid;
565 unsigned long *m_message;
566 bool &m_result;
567};
568
569void
570EventMessageOperation::Execute(ProcessMonitor *monitor)
571{
572 struct ptrace_lwpinfo plwp;
573
574 if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp)))
575 m_result = false;
576 else {
577 if (plwp.pl_flags & PL_FLAG_FORKED) {
578 m_message = (unsigned long *)plwp.pl_child_pid;
579 m_result = true;
580 } else
581 m_result = false;
582 }
583}
584
585//------------------------------------------------------------------------------
586/// @class KillOperation
587/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
588class KillOperation : public Operation
589{
590public:
591 KillOperation(bool &result) : m_result(result) { }
592
593 void Execute(ProcessMonitor *monitor);
594
595private:
596 bool &m_result;
597};
598
599void
600KillOperation::Execute(ProcessMonitor *monitor)
601{
602 lldb::pid_t pid = monitor->GetPID();
603
604 if (PTRACE(PT_KILL, pid, NULL, 0))
605 m_result = false;
606 else
607 m_result = true;
608}
609
610//------------------------------------------------------------------------------
Ed Mastea02f5532013-07-02 16:45:16 +0000611/// @class DetachOperation
Johnny Chen9ed5b492012-01-05 21:48:15 +0000612/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
613class DetachOperation : public Operation
614{
615public:
616 DetachOperation(Error &result) : m_error(result) { }
617
618 void Execute(ProcessMonitor *monitor);
619
620private:
621 Error &m_error;
622};
623
624void
625DetachOperation::Execute(ProcessMonitor *monitor)
626{
627 lldb::pid_t pid = monitor->GetPID();
628
629 if (PTRACE(PT_DETACH, pid, NULL, 0) < 0)
630 m_error.SetErrorToErrno();
631
632}
633
634ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
635 : m_monitor(monitor)
636{
637 sem_init(&m_semaphore, 0, 0);
638}
639
640ProcessMonitor::OperationArgs::~OperationArgs()
641{
642 sem_destroy(&m_semaphore);
643}
644
645ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
646 lldb_private::Module *module,
647 char const **argv,
648 char const **envp,
649 const char *stdin_path,
650 const char *stdout_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000651 const char *stderr_path,
652 const char *working_dir)
Johnny Chen9ed5b492012-01-05 21:48:15 +0000653 : OperationArgs(monitor),
654 m_module(module),
655 m_argv(argv),
656 m_envp(envp),
657 m_stdin_path(stdin_path),
658 m_stdout_path(stdout_path),
Daniel Malea6217d2a2013-01-08 14:49:22 +0000659 m_stderr_path(stderr_path),
660 m_working_dir(working_dir) { }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000661
662ProcessMonitor::LaunchArgs::~LaunchArgs()
663{ }
664
665ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
666 lldb::pid_t pid)
667 : OperationArgs(monitor), m_pid(pid) { }
668
669ProcessMonitor::AttachArgs::~AttachArgs()
670{ }
671
672//------------------------------------------------------------------------------
673/// The basic design of the ProcessMonitor is built around two threads.
674///
675/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
676/// for changes in the debugee state. When a change is detected a
677/// ProcessMessage is sent to the associated ProcessFreeBSD instance. This thread
678/// "drives" state changes in the debugger.
679///
680/// The second thread (@see OperationThread) is responsible for two things 1)
681/// launching or attaching to the inferior process, and then 2) servicing
682/// operations such as register reads/writes, stepping, etc. See the comments
683/// on the Operation class for more info as to why this is needed.
684ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
685 Module *module,
686 const char *argv[],
687 const char *envp[],
688 const char *stdin_path,
689 const char *stdout_path,
690 const char *stderr_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000691 const char *working_dir,
Johnny Chen9ed5b492012-01-05 21:48:15 +0000692 lldb_private::Error &error)
693 : m_process(static_cast<ProcessFreeBSD *>(process)),
694 m_operation_thread(LLDB_INVALID_HOST_THREAD),
695 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
696 m_pid(LLDB_INVALID_PROCESS_ID),
697 m_server_mutex(Mutex::eMutexTypeRecursive),
698 m_terminal_fd(-1),
699 m_client_fd(-1),
700 m_server_fd(-1)
701{
Greg Clayton7b0992d2013-04-18 22:45:39 +0000702 std::unique_ptr<LaunchArgs> args;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000703
704 args.reset(new LaunchArgs(this, module, argv, envp,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000705 stdin_path, stdout_path, stderr_path, working_dir));
Johnny Chen9ed5b492012-01-05 21:48:15 +0000706
707
708 // Server/client descriptors.
709 if (!EnableIPC())
710 {
711 error.SetErrorToGenericError();
712 error.SetErrorString("Monitor failed to initialize.");
713 }
714
715 StartLaunchOpThread(args.get(), error);
716 if (!error.Success())
717 return;
718
719WAIT_AGAIN:
720 // Wait for the operation thread to initialize.
721 if (sem_wait(&args->m_semaphore))
722 {
723 if (errno == EINTR)
724 goto WAIT_AGAIN;
725 else
726 {
727 error.SetErrorToErrno();
728 return;
729 }
730 }
731
732 // Check that the launch was a success.
733 if (!args->m_error.Success())
734 {
Ed Mastea02f5532013-07-02 16:45:16 +0000735 StopOpThread();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000736 error = args->m_error;
737 return;
738 }
739
740 // Finally, start monitoring the child process for change in state.
741 m_monitor_thread = Host::StartMonitoringChildProcess(
742 ProcessMonitor::MonitorCallback, this, GetPID(), true);
743 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
744 {
745 error.SetErrorToGenericError();
746 error.SetErrorString("Process launch failed.");
747 return;
748 }
749}
750
751ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
752 lldb::pid_t pid,
753 lldb_private::Error &error)
754 : m_process(static_cast<ProcessFreeBSD *>(process)),
755 m_operation_thread(LLDB_INVALID_HOST_THREAD),
756 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
757 m_pid(pid),
758 m_server_mutex(Mutex::eMutexTypeRecursive),
759 m_terminal_fd(-1),
760 m_client_fd(-1),
761 m_server_fd(-1)
762{
Greg Clayton7b0992d2013-04-18 22:45:39 +0000763 std::unique_ptr<AttachArgs> args;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000764
765 args.reset(new AttachArgs(this, pid));
766
767 // Server/client descriptors.
768 if (!EnableIPC())
769 {
770 error.SetErrorToGenericError();
771 error.SetErrorString("Monitor failed to initialize.");
772 }
773
774 StartAttachOpThread(args.get(), error);
775 if (!error.Success())
776 return;
777
778WAIT_AGAIN:
779 // Wait for the operation thread to initialize.
780 if (sem_wait(&args->m_semaphore))
781 {
782 if (errno == EINTR)
783 goto WAIT_AGAIN;
784 else
785 {
786 error.SetErrorToErrno();
787 return;
788 }
789 }
790
Ed Mastea02f5532013-07-02 16:45:16 +0000791 // Check that the attach was a success.
Johnny Chen9ed5b492012-01-05 21:48:15 +0000792 if (!args->m_error.Success())
793 {
Ed Mastea02f5532013-07-02 16:45:16 +0000794 StopOpThread();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000795 error = args->m_error;
796 return;
797 }
798
799 // Finally, start monitoring the child process for change in state.
800 m_monitor_thread = Host::StartMonitoringChildProcess(
801 ProcessMonitor::MonitorCallback, this, GetPID(), true);
802 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
803 {
804 error.SetErrorToGenericError();
805 error.SetErrorString("Process attach failed.");
806 return;
807 }
808}
809
810ProcessMonitor::~ProcessMonitor()
811{
812 StopMonitor();
813}
814
815//------------------------------------------------------------------------------
816// Thread setup and tear down.
817void
818ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
819{
820 static const char *g_thread_name = "lldb.process.freebsd.operation";
821
822 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
823 return;
824
825 m_operation_thread =
826 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
827}
828
Johnny Chen9ed5b492012-01-05 21:48:15 +0000829void *
830ProcessMonitor::LaunchOpThread(void *arg)
831{
832 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
833
834 if (!Launch(args)) {
835 sem_post(&args->m_semaphore);
836 return NULL;
837 }
838
839 ServeOperation(args);
840 return NULL;
841}
842
843bool
844ProcessMonitor::Launch(LaunchArgs *args)
845{
846 ProcessMonitor *monitor = args->m_monitor;
847 ProcessFreeBSD &process = monitor->GetProcess();
Greg Clayton29d19302012-02-27 18:40:48 +0000848 lldb::ProcessSP processSP = process.shared_from_this();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000849 const char **argv = args->m_argv;
850 const char **envp = args->m_envp;
851 const char *stdin_path = args->m_stdin_path;
852 const char *stdout_path = args->m_stdout_path;
853 const char *stderr_path = args->m_stderr_path;
Daniel Malea6217d2a2013-01-08 14:49:22 +0000854 const char *working_dir = args->m_working_dir;
Ed Mastea02f5532013-07-02 16:45:16 +0000855
856 lldb_utility::PseudoTerminal terminal;
857 const size_t err_len = 1024;
858 char err_str[err_len];
Johnny Chen9ed5b492012-01-05 21:48:15 +0000859 lldb::pid_t pid;
860
861 lldb::ThreadSP inferior;
Ed Mastea02f5532013-07-02 16:45:16 +0000862 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen9ed5b492012-01-05 21:48:15 +0000863
864 // Propagate the environment if one is not supplied.
865 if (envp == NULL || envp[0] == NULL)
866 envp = const_cast<const char **>(environ);
867
Ed Mastea02f5532013-07-02 16:45:16 +0000868 // Pseudo terminal setup.
869 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
870 {
871 args->m_error.SetErrorToGenericError();
872 args->m_error.SetErrorString("Could not open controlling TTY.");
873 goto FINISH;
874 }
875
876 if ((pid = terminal.Fork(err_str, err_len)) == -1)
877 {
878 args->m_error.SetErrorToGenericError();
879 args->m_error.SetErrorString("Process fork failed.");
880 goto FINISH;
881 }
882
Johnny Chen9ed5b492012-01-05 21:48:15 +0000883 // Recognized child exit status codes.
884 enum {
885 ePtraceFailed = 1,
886 eDupStdinFailed,
887 eDupStdoutFailed,
888 eDupStderrFailed,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000889 eChdirFailed,
Johnny Chen9ed5b492012-01-05 21:48:15 +0000890 eExecFailed
891 };
892
Johnny Chen9ed5b492012-01-05 21:48:15 +0000893 // Child process.
894 if (pid == 0)
895 {
896 // Trace this process.
897 if (PTRACE(PT_TRACE_ME, 0, NULL, 0) < 0)
898 exit(ePtraceFailed);
899
900 // Do not inherit setgid powers.
901 setgid(getgid());
902
903 // Let us have our own process group.
904 setpgid(0, 0);
905
906 // Dup file descriptors if needed.
907 //
908 // FIXME: If two or more of the paths are the same we needlessly open
909 // the same file multiple times.
910 if (stdin_path != NULL && stdin_path[0])
911 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
912 exit(eDupStdinFailed);
913
914 if (stdout_path != NULL && stdout_path[0])
915 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
916 exit(eDupStdoutFailed);
917
918 if (stderr_path != NULL && stderr_path[0])
919 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
920 exit(eDupStderrFailed);
921
Daniel Malea6217d2a2013-01-08 14:49:22 +0000922 // Change working directory
923 if (working_dir != NULL && working_dir[0])
924 if (0 != ::chdir(working_dir))
925 exit(eChdirFailed);
926
Johnny Chen9ed5b492012-01-05 21:48:15 +0000927 // Execute. We should never return.
928 execve(argv[0],
929 const_cast<char *const *>(argv),
930 const_cast<char *const *>(envp));
931 exit(eExecFailed);
932 }
933
934 // Wait for the child process to to trap on its call to execve.
935 ::pid_t wpid;
936 int status;
937 if ((wpid = waitpid(pid, &status, 0)) < 0)
938 {
939 args->m_error.SetErrorToErrno();
940 goto FINISH;
941 }
942 else if (WIFEXITED(status))
943 {
944 // open, dup or execve likely failed for some reason.
945 args->m_error.SetErrorToGenericError();
946 switch (WEXITSTATUS(status))
947 {
Ed Maste5d34af32013-06-24 15:09:18 +0000948 case ePtraceFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000949 args->m_error.SetErrorString("Child ptrace failed.");
950 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000951 case eDupStdinFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000952 args->m_error.SetErrorString("Child open stdin failed.");
953 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000954 case eDupStdoutFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000955 args->m_error.SetErrorString("Child open stdout failed.");
956 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000957 case eDupStderrFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000958 args->m_error.SetErrorString("Child open stderr failed.");
959 break;
Daniel Malea6217d2a2013-01-08 14:49:22 +0000960 case eChdirFailed:
961 args->m_error.SetErrorString("Child failed to set working directory.");
962 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000963 case eExecFailed:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000964 args->m_error.SetErrorString("Child exec failed.");
965 break;
Ed Maste5d34af32013-06-24 15:09:18 +0000966 default:
Johnny Chen9ed5b492012-01-05 21:48:15 +0000967 args->m_error.SetErrorString("Child returned unknown exit status.");
968 break;
969 }
970 goto FINISH;
971 }
972 assert(WIFSTOPPED(status) && wpid == pid &&
973 "Could not sync with inferior process.");
974
975#ifdef notyet
976 // Have the child raise an event on exit. This is used to keep the child in
977 // limbo until it is destroyed.
978 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0)
979 {
980 args->m_error.SetErrorToErrno();
981 goto FINISH;
982 }
983#endif
Ed Mastea02f5532013-07-02 16:45:16 +0000984 // Release the master terminal descriptor and pass it off to the
985 // ProcessMonitor instance. Similarly stash the inferior pid.
986 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000987 monitor->m_pid = pid;
988
989 // Set the terminal fd to be in non blocking mode (it simplifies the
990 // implementation of ProcessFreeBSD::GetSTDOUT to have a non-blocking
991 // descriptor to read from).
992 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
993 goto FINISH;
994
995 // Update the process thread list with this new thread.
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000996 inferior.reset(new POSIXThread(*processSP, pid));
Ed Mastea02f5532013-07-02 16:45:16 +0000997 if (log)
998 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +0000999 process.GetThreadList().AddThread(inferior);
1000
1001 // Let our process instance know the thread has stopped.
1002 process.SendMessage(ProcessMessage::Trace(pid));
1003
1004FINISH:
1005 return args->m_error.Success();
1006}
1007
1008bool
1009ProcessMonitor::EnableIPC()
1010{
1011 int fd[2];
1012
1013 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
1014 return false;
1015
1016 m_client_fd = fd[0];
1017 m_server_fd = fd[1];
1018 return true;
1019}
1020
1021void
1022ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1023{
1024 static const char *g_thread_name = "lldb.process.freebsd.operation";
1025
1026 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1027 return;
1028
1029 m_operation_thread =
1030 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1031}
1032
Johnny Chen9ed5b492012-01-05 21:48:15 +00001033void *
1034ProcessMonitor::AttachOpThread(void *arg)
1035{
1036 AttachArgs *args = static_cast<AttachArgs*>(arg);
1037
1038 if (!Attach(args))
1039 return NULL;
1040
1041 ServeOperation(args);
1042 return NULL;
1043}
1044
1045bool
1046ProcessMonitor::Attach(AttachArgs *args)
1047{
1048 lldb::pid_t pid = args->m_pid;
1049
1050 ProcessMonitor *monitor = args->m_monitor;
1051 ProcessFreeBSD &process = monitor->GetProcess();
Greg Clayton29d19302012-02-27 18:40:48 +00001052 lldb::ProcessSP processSP = process.shared_from_this();
Johnny Chen9ed5b492012-01-05 21:48:15 +00001053 ThreadList &tl = process.GetThreadList();
1054 lldb::ThreadSP inferior;
1055
1056 if (pid <= 1)
1057 {
1058 args->m_error.SetErrorToGenericError();
1059 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1060 goto FINISH;
1061 }
1062
1063 // Attach to the requested process.
1064 if (PTRACE(PT_ATTACH, pid, NULL, 0) < 0)
1065 {
1066 args->m_error.SetErrorToErrno();
1067 goto FINISH;
1068 }
1069
1070 int status;
1071 if ((status = waitpid(pid, NULL, 0)) < 0)
1072 {
1073 args->m_error.SetErrorToErrno();
1074 goto FINISH;
1075 }
1076
1077 // Update the process thread list with the attached thread.
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +00001078 inferior.reset(new POSIXThread(*processSP, pid));
Johnny Chen9ed5b492012-01-05 21:48:15 +00001079 tl.AddThread(inferior);
1080
1081 // Let our process instance know the thread has stopped.
1082 process.SendMessage(ProcessMessage::Trace(pid));
1083
1084 FINISH:
1085 return args->m_error.Success();
1086}
1087
1088bool
1089ProcessMonitor::MonitorCallback(void *callback_baton,
1090 lldb::pid_t pid,
1091 bool exited,
1092 int signal,
1093 int status)
1094{
1095 ProcessMessage message;
1096 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
1097 ProcessFreeBSD *process = monitor->m_process;
Ed Mastea02f5532013-07-02 16:45:16 +00001098 assert(process);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001099 bool stop_monitoring;
1100 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001101 int ptrace_err;
Johnny Chen9ed5b492012-01-05 21:48:15 +00001102
Ed Mastea02f5532013-07-02 16:45:16 +00001103 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1104
1105 if (exited)
1106 {
1107 if (log)
1108 log->Printf ("ProcessMonitor::%s() got exit signal, tid = %" PRIu64, __FUNCTION__, pid);
1109 message = ProcessMessage::Exit(pid, status);
1110 process->SendMessage(message);
1111 return pid == process->GetID();
1112 }
1113
Daniel Maleaa35970a2012-11-23 18:09:58 +00001114 if (!monitor->GetSignalInfo(pid, &info, ptrace_err))
Johnny Chen9ed5b492012-01-05 21:48:15 +00001115 stop_monitoring = true; // pid is gone. Bail.
1116 else {
1117 switch (info.si_signo)
1118 {
1119 case SIGTRAP:
1120 message = MonitorSIGTRAP(monitor, &info, pid);
1121 break;
1122
1123 default:
1124 message = MonitorSignal(monitor, &info, pid);
1125 break;
1126 }
1127
1128 process->SendMessage(message);
1129 stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
1130 }
1131
1132 return stop_monitoring;
1133}
1134
1135ProcessMessage
1136ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
1137 const siginfo_t *info, lldb::pid_t pid)
1138{
1139 ProcessMessage message;
1140
Ed Mastea02f5532013-07-02 16:45:16 +00001141 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1142
Matt Kopec7de48462013-03-06 17:20:48 +00001143 assert(monitor);
1144 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Johnny Chen9ed5b492012-01-05 21:48:15 +00001145
1146 switch (info->si_code)
1147 {
1148 default:
1149 assert(false && "Unexpected SIGTRAP code!");
1150 break;
1151
1152 case (SIGTRAP /* | (PTRACE_EVENT_EXIT << 8) */):
1153 {
1154 // The inferior process is about to exit. Maintain the process in a
1155 // state of "limbo" until we are explicitly commanded to detach,
1156 // destroy, resume, etc.
1157 unsigned long data = 0;
1158 if (!monitor->GetEventMessage(pid, &data))
1159 data = -1;
Ed Mastea02f5532013-07-02 16:45:16 +00001160 if (log)
1161 log->Printf ("ProcessMonitor::%s() received exit? event, data = %lx, pid = %" PRIu64, __FUNCTION__, data, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001162 message = ProcessMessage::Limbo(pid, (data >> 8));
1163 break;
1164 }
1165
1166 case 0:
1167 case TRAP_TRACE:
Ed Mastea02f5532013-07-02 16:45:16 +00001168 if (log)
1169 log->Printf ("ProcessMonitor::%s() received trace event, pid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001170 message = ProcessMessage::Trace(pid);
1171 break;
1172
1173 case SI_KERNEL:
1174 case TRAP_BRKPT:
Ed Mastea02f5532013-07-02 16:45:16 +00001175 if (log)
1176 log->Printf ("ProcessMonitor::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001177 message = ProcessMessage::Break(pid);
1178 break;
1179 }
1180
1181 return message;
1182}
1183
1184ProcessMessage
1185ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
1186 const siginfo_t *info, lldb::pid_t pid)
1187{
1188 ProcessMessage message;
1189 int signo = info->si_signo;
1190
Ed Mastea02f5532013-07-02 16:45:16 +00001191 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1192
Johnny Chen9ed5b492012-01-05 21:48:15 +00001193 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1194 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1195 // kill(2) or raise(3). Similarly for tgkill(2) on FreeBSD.
1196 //
1197 // IOW, user generated signals never generate what we consider to be a
1198 // "crash".
1199 //
1200 // Similarly, ACK signals generated by this monitor.
1201 if (info->si_code == SI_USER)
1202 {
Ed Mastea02f5532013-07-02 16:45:16 +00001203 if (log)
1204 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
1205 __FUNCTION__,
1206 monitor->m_process->GetUnixSignals().GetSignalAsCString (signo),
1207 "SI_USER",
1208 info->si_pid);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001209 if (info->si_pid == getpid())
1210 return ProcessMessage::SignalDelivered(pid, signo);
1211 else
1212 return ProcessMessage::Signal(pid, signo);
1213 }
1214
Ed Mastea02f5532013-07-02 16:45:16 +00001215 if (log)
1216 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals().GetSignalAsCString (signo));
1217
Johnny Chen9ed5b492012-01-05 21:48:15 +00001218 if (signo == SIGSEGV) {
1219 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1220 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1221 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1222 }
1223
1224 if (signo == SIGILL) {
1225 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1226 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1227 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1228 }
1229
1230 if (signo == SIGFPE) {
1231 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1232 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1233 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1234 }
1235
1236 if (signo == SIGBUS) {
1237 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1238 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1239 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1240 }
1241
1242 // Everything else is "normal" and does not require any special action on
1243 // our part.
1244 return ProcessMessage::Signal(pid, signo);
1245}
1246
1247ProcessMessage::CrashReason
1248ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1249{
1250 ProcessMessage::CrashReason reason;
1251 assert(info->si_signo == SIGSEGV);
1252
1253 reason = ProcessMessage::eInvalidCrashReason;
1254
1255 switch (info->si_code)
1256 {
1257 default:
1258 assert(false && "unexpected si_code for SIGSEGV");
1259 break;
1260 case SEGV_MAPERR:
1261 reason = ProcessMessage::eInvalidAddress;
1262 break;
1263 case SEGV_ACCERR:
1264 reason = ProcessMessage::ePrivilegedAddress;
1265 break;
1266 }
1267
1268 return reason;
1269}
1270
1271ProcessMessage::CrashReason
1272ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
1273{
1274 ProcessMessage::CrashReason reason;
1275 assert(info->si_signo == SIGILL);
1276
1277 reason = ProcessMessage::eInvalidCrashReason;
1278
1279 switch (info->si_code)
1280 {
1281 default:
1282 assert(false && "unexpected si_code for SIGILL");
1283 break;
1284 case ILL_ILLOPC:
1285 reason = ProcessMessage::eIllegalOpcode;
1286 break;
1287 case ILL_ILLOPN:
1288 reason = ProcessMessage::eIllegalOperand;
1289 break;
1290 case ILL_ILLADR:
1291 reason = ProcessMessage::eIllegalAddressingMode;
1292 break;
1293 case ILL_ILLTRP:
1294 reason = ProcessMessage::eIllegalTrap;
1295 break;
1296 case ILL_PRVOPC:
1297 reason = ProcessMessage::ePrivilegedOpcode;
1298 break;
1299 case ILL_PRVREG:
1300 reason = ProcessMessage::ePrivilegedRegister;
1301 break;
1302 case ILL_COPROC:
1303 reason = ProcessMessage::eCoprocessorError;
1304 break;
1305 case ILL_BADSTK:
1306 reason = ProcessMessage::eInternalStackError;
1307 break;
1308 }
1309
1310 return reason;
1311}
1312
1313ProcessMessage::CrashReason
1314ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
1315{
1316 ProcessMessage::CrashReason reason;
1317 assert(info->si_signo == SIGFPE);
1318
1319 reason = ProcessMessage::eInvalidCrashReason;
1320
1321 switch (info->si_code)
1322 {
1323 default:
1324 assert(false && "unexpected si_code for SIGFPE");
1325 break;
1326 case FPE_INTDIV:
1327 reason = ProcessMessage::eIntegerDivideByZero;
1328 break;
1329 case FPE_INTOVF:
1330 reason = ProcessMessage::eIntegerOverflow;
1331 break;
1332 case FPE_FLTDIV:
1333 reason = ProcessMessage::eFloatDivideByZero;
1334 break;
1335 case FPE_FLTOVF:
1336 reason = ProcessMessage::eFloatOverflow;
1337 break;
1338 case FPE_FLTUND:
1339 reason = ProcessMessage::eFloatUnderflow;
1340 break;
1341 case FPE_FLTRES:
1342 reason = ProcessMessage::eFloatInexactResult;
1343 break;
1344 case FPE_FLTINV:
1345 reason = ProcessMessage::eFloatInvalidOperation;
1346 break;
1347 case FPE_FLTSUB:
1348 reason = ProcessMessage::eFloatSubscriptRange;
1349 break;
1350 }
1351
1352 return reason;
1353}
1354
1355ProcessMessage::CrashReason
1356ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
1357{
1358 ProcessMessage::CrashReason reason;
1359 assert(info->si_signo == SIGBUS);
1360
1361 reason = ProcessMessage::eInvalidCrashReason;
1362
1363 switch (info->si_code)
1364 {
1365 default:
1366 assert(false && "unexpected si_code for SIGBUS");
1367 break;
1368 case BUS_ADRALN:
1369 reason = ProcessMessage::eIllegalAlignment;
1370 break;
1371 case BUS_ADRERR:
1372 reason = ProcessMessage::eIllegalAddress;
1373 break;
1374 case BUS_OBJERR:
1375 reason = ProcessMessage::eHardwareError;
1376 break;
1377 }
1378
1379 return reason;
1380}
1381
1382void
1383ProcessMonitor::ServeOperation(OperationArgs *args)
1384{
1385 int status;
1386 pollfd fdset;
1387
1388 ProcessMonitor *monitor = args->m_monitor;
1389
1390 fdset.fd = monitor->m_server_fd;
1391 fdset.events = POLLIN | POLLPRI;
1392 fdset.revents = 0;
1393
1394 // We are finised with the arguments and are ready to go. Sync with the
1395 // parent thread and start serving operations on the inferior.
1396 sem_post(&args->m_semaphore);
1397
1398 for (;;)
1399 {
1400 if ((status = poll(&fdset, 1, -1)) < 0)
1401 {
1402 switch (errno)
1403 {
1404 default:
1405 assert(false && "Unexpected poll() failure!");
1406 continue;
1407
1408 case EINTR: continue; // Just poll again.
1409 case EBADF: return; // Connection terminated.
1410 }
1411 }
1412
1413 assert(status == 1 && "Too many descriptors!");
1414
1415 if (fdset.revents & POLLIN)
1416 {
1417 Operation *op = NULL;
1418
1419 READ_AGAIN:
1420 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1421 {
1422 // There is only one acceptable failure.
1423 assert(errno == EINTR);
1424 goto READ_AGAIN;
1425 }
Ed Mastea02f5532013-07-02 16:45:16 +00001426 if (status == 0)
1427 continue; // Poll again. The connection probably terminated.
Johnny Chen9ed5b492012-01-05 21:48:15 +00001428 assert(status == sizeof(op));
1429 op->Execute(monitor);
1430 write(fdset.fd, &op, sizeof(op));
1431 }
1432 }
1433}
1434
1435void
1436ProcessMonitor::DoOperation(Operation *op)
1437{
1438 int status;
1439 Operation *ack = NULL;
1440 Mutex::Locker lock(m_server_mutex);
1441
1442 // FIXME: Do proper error checking here.
1443 write(m_client_fd, &op, sizeof(op));
1444
1445READ_AGAIN:
1446 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1447 {
1448 // If interrupted by a signal handler try again. Otherwise the monitor
1449 // thread probably died and we have a stale file descriptor -- abort the
1450 // operation.
1451 if (errno == EINTR)
1452 goto READ_AGAIN;
1453 return;
1454 }
1455
1456 assert(status == sizeof(ack));
1457 assert(ack == op && "Invalid monitor thread response!");
1458}
1459
1460size_t
1461ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1462 Error &error)
1463{
1464 size_t result;
1465 ReadOperation op(vm_addr, buf, size, error, result);
1466 DoOperation(&op);
1467 return result;
1468}
1469
1470size_t
1471ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1472 lldb_private::Error &error)
1473{
1474 size_t result;
1475 WriteOperation op(vm_addr, buf, size, error, result);
1476 DoOperation(&op);
1477 return result;
1478}
1479
1480bool
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00001481ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +00001482 unsigned size, RegisterValue &value)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001483{
1484 bool result;
1485 ReadRegOperation op(offset, size, value, result);
1486 DoOperation(&op);
1487 return result;
1488}
1489
1490bool
Daniel Maleaf0da3712012-12-18 19:50:15 +00001491ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00001492 const char* reg_name, const RegisterValue &value)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001493{
1494 bool result;
1495 WriteRegOperation op(offset, value, result);
1496 DoOperation(&op);
1497 return result;
1498}
1499
1500bool
Matt Kopec7de48462013-03-06 17:20:48 +00001501ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001502{
1503 bool result;
1504 ReadGPROperation op(buf, result);
1505 DoOperation(&op);
1506 return result;
1507}
1508
1509bool
Matt Kopec7de48462013-03-06 17:20:48 +00001510ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001511{
1512 bool result;
1513 ReadFPROperation op(buf, result);
1514 DoOperation(&op);
1515 return result;
1516}
1517
1518bool
Ed Maste5d34af32013-06-24 15:09:18 +00001519ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1520{
1521 return false;
1522}
1523
1524bool
Matt Kopec7de48462013-03-06 17:20:48 +00001525ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001526{
1527 bool result;
1528 WriteGPROperation op(buf, result);
1529 DoOperation(&op);
1530 return result;
1531}
1532
1533bool
Matt Kopec7de48462013-03-06 17:20:48 +00001534ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001535{
1536 bool result;
1537 WriteFPROperation op(buf, result);
1538 DoOperation(&op);
1539 return result;
1540}
1541
1542bool
Ed Maste5d34af32013-06-24 15:09:18 +00001543ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1544{
1545 return false;
1546}
1547
1548bool
Johnny Chen9ed5b492012-01-05 21:48:15 +00001549ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
1550{
1551 bool result;
Ed Mastea02f5532013-07-02 16:45:16 +00001552 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1553
1554 if (log)
1555 log->Printf ("ProcessMonitor::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
1556 m_process->GetUnixSignals().GetSignalAsCString (signo));
Johnny Chen9ed5b492012-01-05 21:48:15 +00001557 ResumeOperation op(tid, signo, result);
1558 DoOperation(&op);
Ed Mastea02f5532013-07-02 16:45:16 +00001559 if (log)
1560 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
Johnny Chen9ed5b492012-01-05 21:48:15 +00001561 return result;
1562}
1563
1564bool
1565ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
1566{
1567 bool result;
1568 SingleStepOperation op(tid, signo, result);
1569 DoOperation(&op);
1570 return result;
1571}
1572
1573bool
1574ProcessMonitor::BringProcessIntoLimbo()
1575{
1576 bool result;
1577 KillOperation op(result);
1578 DoOperation(&op);
1579 return result;
1580}
1581
1582bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00001583ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001584{
1585 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001586 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Johnny Chen9ed5b492012-01-05 21:48:15 +00001587 DoOperation(&op);
1588 return result;
1589}
1590
1591bool
1592ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1593{
1594 bool result;
1595 EventMessageOperation op(tid, message, result);
1596 DoOperation(&op);
1597 return result;
1598}
1599
Ed Mastea02f5532013-07-02 16:45:16 +00001600lldb_private::Error
Matt Kopecedee1822013-06-03 19:48:53 +00001601ProcessMonitor::Detach(lldb::tid_t tid)
Johnny Chen9ed5b492012-01-05 21:48:15 +00001602{
Ed Mastea02f5532013-07-02 16:45:16 +00001603 lldb_private::Error error;
1604 if (tid != LLDB_INVALID_THREAD_ID)
1605 {
1606 DetachOperation op(error);
1607 DoOperation(&op);
1608 }
1609 return error;
Johnny Chen9ed5b492012-01-05 21:48:15 +00001610}
1611
1612bool
1613ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1614{
1615 int target_fd = open(path, flags, 0666);
1616
1617 if (target_fd == -1)
1618 return false;
1619
1620 return (dup2(target_fd, fd) == -1) ? false : true;
1621}
1622
1623void
1624ProcessMonitor::StopMonitoringChildProcess()
1625{
1626 lldb::thread_result_t thread_result;
1627
1628 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
1629 {
1630 Host::ThreadCancel(m_monitor_thread, NULL);
1631 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1632 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1633 }
1634}
1635
1636void
1637ProcessMonitor::StopMonitor()
1638{
1639 StopMonitoringChildProcess();
Ed Mastea02f5532013-07-02 16:45:16 +00001640 StopOpThread();
Johnny Chen9ed5b492012-01-05 21:48:15 +00001641 CloseFD(m_terminal_fd);
1642 CloseFD(m_client_fd);
1643 CloseFD(m_server_fd);
1644}
1645
1646void
Ed Mastea02f5532013-07-02 16:45:16 +00001647ProcessMonitor::StopOpThread()
1648{
1649 lldb::thread_result_t result;
1650
1651 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1652 return;
1653
1654 Host::ThreadCancel(m_operation_thread, NULL);
1655 Host::ThreadJoin(m_operation_thread, &result, NULL);
1656 m_operation_thread = LLDB_INVALID_HOST_THREAD;
1657}
1658
1659void
Johnny Chen9ed5b492012-01-05 21:48:15 +00001660ProcessMonitor::CloseFD(int &fd)
1661{
1662 if (fd != -1)
1663 {
1664 close(fd);
1665 fd = -1;
1666 }
1667}