blob: f21cb00e7fcd9b61cddfa02549225b5f0c22fc06 [file] [log] [blame]
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001//===-- ProcessMonitor.cpp ------------------------------------ -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
12#include <poll.h>
13#include <string.h>
14#include <unistd.h>
15#include <sys/ptrace.h>
16#include <sys/socket.h>
17#include <sys/types.h>
18#include <sys/wait.h>
19
20// C++ Includes
21// Other libraries and framework includes
22#include "lldb/Core/Error.h"
23#include "lldb/Core/Scalar.h"
24#include "lldb/Host/Host.h"
25#include "lldb/Target/Thread.h"
26#include "lldb/Target/RegisterContext.h"
27#include "lldb/Utility/PseudoTerminal.h"
28
29#include "LinuxThread.h"
30#include "ProcessLinux.h"
31#include "ProcessMonitor.h"
32
33
34using namespace lldb_private;
35
36//------------------------------------------------------------------------------
37// Static implementations of ProcessMonitor::ReadMemory and
38// ProcessMonitor::WriteMemory. This enables mutual recursion between these
39// functions without needed to go thru the thread funnel.
40
41static size_t
42DoReadMemory(lldb::pid_t pid, unsigned word_size,
43 lldb::addr_t vm_addr, void *buf, size_t size, Error &error)
44{
45 unsigned char *dst = static_cast<unsigned char*>(buf);
46 size_t bytes_read;
47 size_t remainder;
48 long data;
49
50 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
51 {
52 errno = 0;
53 data = ptrace(PTRACE_PEEKDATA, pid, vm_addr, NULL);
54
55 if (data == -1L && errno)
56 {
57 error.SetErrorToErrno();
58 return bytes_read;
59 }
60
61 remainder = size - bytes_read;
62 remainder = remainder > word_size ? word_size : remainder;
63 for (unsigned i = 0; i < remainder; ++i)
64 dst[i] = ((data >> i*8) & 0xFF);
65 vm_addr += word_size;
66 dst += word_size;
67 }
68
69 return bytes_read;
70}
71
72static size_t
73DoWriteMemory(lldb::pid_t pid, unsigned word_size,
74 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
75{
76 const unsigned char *src = static_cast<const unsigned char*>(buf);
77 size_t bytes_written = 0;
78 size_t remainder;
79
80 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
81 {
82 remainder = size - bytes_written;
83 remainder = remainder > word_size ? word_size : remainder;
84
85 if (remainder == word_size)
86 {
87 unsigned long data = 0;
88 for (unsigned i = 0; i < word_size; ++i)
89 data |= (unsigned long)src[i] << i*8;
90
91 if (ptrace(PTRACE_POKEDATA, pid, vm_addr, data))
92 {
93 error.SetErrorToErrno();
94 return bytes_written;
95 }
96 }
97 else
98 {
99 unsigned char buff[8];
100 if (DoReadMemory(pid, word_size, vm_addr,
101 buff, word_size, error) != word_size)
102 return bytes_written;
103
104 memcpy(buff, src, remainder);
105
106 if (DoWriteMemory(pid, word_size, vm_addr,
107 buff, word_size, error) != word_size)
108 return bytes_written;
109 }
110
111 vm_addr += word_size;
112 src += word_size;
113 }
114 return bytes_written;
115}
116
117
118//------------------------------------------------------------------------------
119/// @class Operation
120/// @brief Represents a ProcessMonitor operation.
121///
122/// Under Linux, it is not possible to ptrace() from any other thread but the
123/// one that spawned or attached to the process from the start. Therefore, when
124/// a ProcessMonitor is asked to deliver or change the state of an inferior
125/// process the operation must be "funneled" to a specific thread to perform the
126/// task. The Operation class provides an abstract base for all services the
127/// ProcessMonitor must perform via the single virtual function Execute, thus
128/// encapsulating the code that needs to run in the privileged context.
129class Operation
130{
131public:
132 virtual void Execute(ProcessMonitor *monitor) = 0;
133};
134
135//------------------------------------------------------------------------------
136/// @class ReadOperation
137/// @brief Implements ProcessMonitor::ReadMemory.
138class ReadOperation : public Operation
139{
140public:
141 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
142 Error &error, size_t &result)
143 : m_addr(addr), m_buff(buff), m_size(size),
144 m_error(error), m_result(result)
145 { }
146
147 void Execute(ProcessMonitor *monitor);
148
149private:
150 lldb::addr_t m_addr;
151 void *m_buff;
152 size_t m_size;
153 Error &m_error;
154 size_t &m_result;
155};
156
157void
158ReadOperation::Execute(ProcessMonitor *monitor)
159{
160 const unsigned word_size = monitor->GetProcess().GetAddressByteSize();
161 lldb::pid_t pid = monitor->GetPID();
162
163 m_result = DoReadMemory(pid, word_size, m_addr, m_buff, m_size, m_error);
164}
165
166//------------------------------------------------------------------------------
167/// @class ReadOperation
168/// @brief Implements ProcessMonitor::WriteMemory.
169class WriteOperation : public Operation
170{
171public:
172 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
173 Error &error, size_t &result)
174 : m_addr(addr), m_buff(buff), m_size(size),
175 m_error(error), m_result(result)
176 { }
177
178 void Execute(ProcessMonitor *monitor);
179
180private:
181 lldb::addr_t m_addr;
182 const void *m_buff;
183 size_t m_size;
184 Error &m_error;
185 size_t &m_result;
186};
187
188void
189WriteOperation::Execute(ProcessMonitor *monitor)
190{
191 const unsigned word_size = monitor->GetProcess().GetAddressByteSize();
192 lldb::pid_t pid = monitor->GetPID();
193
194 m_result = DoWriteMemory(pid, word_size, m_addr, m_buff, m_size, m_error);
195}
196
197//------------------------------------------------------------------------------
198/// @class ReadRegOperation
199/// @brief Implements ProcessMonitor::ReadRegisterValue.
200class ReadRegOperation : public Operation
201{
202public:
203 ReadRegOperation(unsigned offset, Scalar &value, bool &result)
204 : m_offset(offset), m_value(value), m_result(result)
205 { }
206
207 void Execute(ProcessMonitor *monitor);
208
209private:
210 unsigned m_offset;
211 Scalar &m_value;
212 bool &m_result;
213};
214
215void
216ReadRegOperation::Execute(ProcessMonitor *monitor)
217{
218 lldb::pid_t pid = monitor->GetPID();
219
220 // Set errno to zero so that we can detect a failed peek.
221 errno = 0;
222 unsigned long data = ptrace(PTRACE_PEEKUSER, pid, m_offset, NULL);
223
224 if (data == -1UL && errno)
225 m_result = false;
226 else
227 {
228 m_value = data;
229 m_result = true;
230 }
231}
232
233//------------------------------------------------------------------------------
234/// @class WriteRegOperation
235/// @brief Implements ProcessMonitor::WriteRegisterValue.
236class WriteRegOperation : public Operation
237{
238public:
239 WriteRegOperation(unsigned offset, const Scalar &value, bool &result)
240 : m_offset(offset), m_value(value), m_result(result)
241 { }
242
243 void Execute(ProcessMonitor *monitor);
244
245private:
246 unsigned m_offset;
247 const Scalar &m_value;
248 bool &m_result;
249};
250
251void
252WriteRegOperation::Execute(ProcessMonitor *monitor)
253{
254 lldb::pid_t pid = monitor->GetPID();
255
256 if (ptrace(PTRACE_POKEUSER, pid, m_offset, m_value.ULong()))
257 m_result = false;
258 else
259 m_result = true;
260}
261
262//------------------------------------------------------------------------------
263/// @class ResumeOperation
264/// @brief Implements ProcessMonitor::Resume.
265class ResumeOperation : public Operation
266{
267public:
268 ResumeOperation(lldb::tid_t tid, bool &result) :
269 m_tid(tid), m_result(result) { }
270
271 void Execute(ProcessMonitor *monitor);
272
273private:
274 lldb::tid_t m_tid;
275 bool &m_result;
276};
277
278void
279ResumeOperation::Execute(ProcessMonitor *monitor)
280{
281 if (ptrace(PTRACE_CONT, m_tid, NULL, NULL))
282 m_result = false;
283 else
284 m_result = true;
285}
286
287//------------------------------------------------------------------------------
288/// @class ResumeOperation
289/// @brief Implements ProcessMonitor::SingleStep.
290class SingleStepOperation : public Operation
291{
292public:
293 SingleStepOperation(lldb::tid_t tid, bool &result)
294 : m_tid(tid), m_result(result) { }
295
296 void Execute(ProcessMonitor *monitor);
297
298private:
299 lldb::tid_t m_tid;
300 bool &m_result;
301};
302
303void
304SingleStepOperation::Execute(ProcessMonitor *monitor)
305{
306 if (ptrace(PTRACE_SINGLESTEP, m_tid, NULL, NULL))
307 m_result = false;
308 else
309 m_result = true;
310}
311
312//------------------------------------------------------------------------------
313/// @class SiginfoOperation
314/// @brief Implements ProcessMonitor::GetSignalInfo.
315class SiginfoOperation : public Operation
316{
317public:
318 SiginfoOperation(lldb::tid_t tid, void *info, bool &result)
319 : m_tid(tid), m_info(info), m_result(result) { }
320
321 void Execute(ProcessMonitor *monitor);
322
323private:
324 lldb::tid_t m_tid;
325 void *m_info;
326 bool &m_result;
327};
328
329void
330SiginfoOperation::Execute(ProcessMonitor *monitor)
331{
332 if (ptrace(PTRACE_GETSIGINFO, m_tid, NULL, m_info))
333 m_result = false;
334 else
335 m_result = true;
336}
337
338//------------------------------------------------------------------------------
339/// @class EventMessageOperation
340/// @brief Implements ProcessMonitor::GetEventMessage.
341class EventMessageOperation : public Operation
342{
343public:
344 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
345 : m_tid(tid), m_message(message), m_result(result) { }
346
347 void Execute(ProcessMonitor *monitor);
348
349private:
350 lldb::tid_t m_tid;
351 unsigned long *m_message;
352 bool &m_result;
353};
354
355void
356EventMessageOperation::Execute(ProcessMonitor *monitor)
357{
358 if (ptrace(PTRACE_GETEVENTMSG, m_tid, NULL, m_message))
359 m_result = false;
360 else
361 m_result = true;
362}
363
364//------------------------------------------------------------------------------
365/// @class KillOperation
366/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
367class KillOperation : public Operation
368{
369public:
370 KillOperation(bool &result) : m_result(result) { }
371
372 void Execute(ProcessMonitor *monitor);
373
374private:
375 bool &m_result;
376};
377
378void
379KillOperation::Execute(ProcessMonitor *monitor)
380{
381 lldb::pid_t pid = monitor->GetPID();
382
383 if (ptrace(PTRACE_KILL, pid, NULL, NULL))
384 m_result = false;
385 else
386 m_result = true;
387
388#if 0
389 // First, stop the inferior process.
390 if (kill(pid, SIGSTOP))
391 {
392 m_result = false;
393 return;
394 }
395
396 // Clear any ptrace options. When PTRACE_O_TRACEEXIT is set, a plain
397 // PTRACE_KILL (or any termination signal) will not truely terminate the
398 // inferior process. Instead, the process is left in a state of "limbo"
399 // allowing us to interrogate its state. However in this case we really do
400 // want the process gone.
401 if (ptrace(PTRACE_SETOPTIONS, pid, NULL, 0UL))
402 {
403 m_result = false;
404 return;
405 }
406
407 // Kill it.
408 if (ptrace(PTRACE_KILL, pid, NULL, NULL))
409 m_result = false;
410 else
411 m_result = true;
412#endif
413}
414
415ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
416 lldb_private::Module *module,
417 char const **argv,
418 char const **envp,
419 const char *stdin_path,
420 const char *stdout_path,
421 const char *stderr_path)
422 : m_monitor(monitor),
423 m_module(module),
424 m_argv(argv),
425 m_envp(envp),
426 m_stdin_path(stdin_path),
427 m_stdout_path(stdout_path),
428 m_stderr_path(stderr_path)
429{
430 sem_init(&m_semaphore, 0, 0);
431}
432
433ProcessMonitor::LaunchArgs::~LaunchArgs()
434{
435 sem_destroy(&m_semaphore);
436}
437
438//------------------------------------------------------------------------------
439/// The basic design of the ProcessMonitor is built around two threads.
440///
441/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
442/// for changes in the debugee state. When a change is detected a
443/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
444/// "drives" state changes in the debugger.
445///
446/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000447/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000448/// operations such as register reads/writes, stepping, etc. See the comments
449/// on the Operation class for more info as to why this is needed.
450ProcessMonitor::ProcessMonitor(ProcessLinux *process,
451 Module *module,
452 const char *argv[],
453 const char *envp[],
454 const char *stdin_path,
455 const char *stdout_path,
456 const char *stderr_path,
457 lldb_private::Error &error)
458 : m_process(process),
459 m_operation_thread(LLDB_INVALID_HOST_THREAD),
460 m_pid(LLDB_INVALID_PROCESS_ID),
461 m_terminal_fd(-1),
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000462 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000463 m_client_fd(-1),
464 m_server_fd(-1)
465{
Stephen Wilson57740ec2011-01-15 00:12:41 +0000466 std::auto_ptr<LaunchArgs> args;
467
468 args.reset(new LaunchArgs(this, module, argv, envp,
469 stdin_path, stdout_path, stderr_path));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000470
471 // Server/client descriptors.
472 if (!EnableIPC())
473 {
474 error.SetErrorToGenericError();
475 error.SetErrorString("Monitor failed to initialize.");
476 }
477
Stephen Wilson57740ec2011-01-15 00:12:41 +0000478 StartOperationThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000479 if (!error.Success())
480 return;
481
482WAIT_AGAIN:
483 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000484 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000485 {
486 if (errno == EINTR)
487 goto WAIT_AGAIN;
488 else
489 {
490 error.SetErrorToErrno();
491 return;
492 }
493 }
494
495 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000496 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000497 {
498 StopOperationThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000499 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000500 return;
501 }
502
503 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000504 m_monitor_thread = Host::StartMonitoringChildProcess(
505 ProcessMonitor::MonitorCallback, this, GetPID(), true);
506 if (m_monitor_thread == LLDB_INVALID_HOST_THREAD)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000507 {
508 error.SetErrorToGenericError();
509 error.SetErrorString("Process launch failed.");
510 return;
511 }
512}
513
514ProcessMonitor::~ProcessMonitor()
515{
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000516 StopMonitoringChildProcess();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000517 StopOperationThread();
518
519 close(m_terminal_fd);
520 close(m_client_fd);
521 close(m_server_fd);
522}
523
524//------------------------------------------------------------------------------
525// Thread setup and tear down.
526void
527ProcessMonitor::StartOperationThread(LaunchArgs *args, Error &error)
528{
529 static const char *g_thread_name = "lldb.process.linux.operation";
530
531 if (m_operation_thread != LLDB_INVALID_HOST_THREAD)
532 return;
533
534 m_operation_thread =
535 Host::ThreadCreate(g_thread_name, OperationThread, args, &error);
536}
537
538void
539ProcessMonitor::StopOperationThread()
540{
541 lldb::thread_result_t result;
542
543 if (m_operation_thread == LLDB_INVALID_HOST_THREAD)
544 return;
545
546 Host::ThreadCancel(m_operation_thread, NULL);
547 Host::ThreadJoin(m_operation_thread, &result, NULL);
548}
549
550void *
551ProcessMonitor::OperationThread(void *arg)
552{
553 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
554
555 if (!Launch(args))
556 return NULL;
557
558 ServeOperation(args->m_monitor);
559 return NULL;
560}
561
562bool
563ProcessMonitor::Launch(LaunchArgs *args)
564{
565 ProcessMonitor *monitor = args->m_monitor;
566 ProcessLinux &process = monitor->GetProcess();
567 const char **argv = args->m_argv;
568 const char **envp = args->m_envp;
569 const char *stdin_path = args->m_stdin_path;
570 const char *stdout_path = args->m_stdout_path;
571 const char *stderr_path = args->m_stderr_path;
572
573 lldb_utility::PseudoTerminal terminal;
574 const size_t err_len = 1024;
575 char err_str[err_len];
576 lldb::pid_t pid;
577
578 lldb::ThreadSP inferior;
579
Stephen Wilson57740ec2011-01-15 00:12:41 +0000580 // Propagate the environment if one is not supplied.
581 if (envp == NULL || envp[0] == NULL)
582 envp = const_cast<const char **>(environ);
583
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000584 // Pseudo terminal setup.
585 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
586 {
587 args->m_error.SetErrorToGenericError();
588 args->m_error.SetErrorString("Could not open controlling TTY.");
589 goto FINISH;
590 }
591
592 if ((pid = terminal.Fork(err_str, err_len)) < 0)
593 {
594 args->m_error.SetErrorToGenericError();
595 args->m_error.SetErrorString("Process fork failed.");
596 goto FINISH;
597 }
598
599 // Child process.
600 if (pid == 0)
601 {
602 // Trace this process.
603 ptrace(PTRACE_TRACEME, 0, NULL, NULL);
604
605 // Do not inherit setgid powers.
606 setgid(getgid());
607
608 // Let us have our own process group.
609 setpgid(0, 0);
610
Greg Clayton710dd5a2011-01-08 20:28:42 +0000611 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000612 //
613 // FIXME: If two or more of the paths are the same we needlessly open
614 // the same file multiple times.
615 if (stdin_path != NULL && stdin_path[0])
616 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY | O_CREAT))
617 exit(1);
618
619 if (stdout_path != NULL && stdout_path[0])
620 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
621 exit(1);
622
623 if (stderr_path != NULL && stderr_path[0])
624 if (!DupDescriptor(stderr_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
625 exit(1);
626
627 // Execute. We should never return.
628 execve(argv[0],
629 const_cast<char *const *>(argv),
630 const_cast<char *const *>(envp));
631 exit(-1);
632 }
633
634 // Wait for the child process to to trap on its call to execve.
635 int status;
636 if ((status = waitpid(pid, NULL, 0)) < 0)
637 {
638 // execve likely failed for some reason.
639 args->m_error.SetErrorToErrno();
640 goto FINISH;
641 }
642 assert(status == pid && "Could not sync with inferior process.");
643
644 // Have the child raise an event on exit. This is used to keep the child in
645 // limbo until it is destroyed.
646 if (ptrace(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0)
647 {
648 args->m_error.SetErrorToErrno();
649 goto FINISH;
650 }
651
652 // Release the master terminal descriptor and pass it off to the
653 // ProcessMonitor instance. Similarly stash the inferior pid.
654 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
655 monitor->m_pid = pid;
656
657 // Update the process thread list with this new thread and mark it as
658 // current.
659 inferior.reset(new LinuxThread(process, pid));
660 process.GetThreadList().AddThread(inferior);
Stephen Wilson5a8feea2011-01-04 21:39:27 +0000661 process.GetThreadList().SetSelectedThreadByID(pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000662
663 // Let our process instance know the thread has stopped.
664 process.SendMessage(ProcessMessage::Trace(pid));
665
666FINISH:
667 // Sync with our parent thread now that the launch operation is complete.
668 sem_post(&args->m_semaphore);
669 return args->m_error.Success();
670}
671
672bool
673ProcessMonitor::EnableIPC()
674{
675 int fd[2];
676
677 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
678 return false;
679
680 m_client_fd = fd[0];
681 m_server_fd = fd[1];
682 return true;
683}
684
685bool
686ProcessMonitor::MonitorCallback(void *callback_baton,
687 lldb::pid_t pid,
688 int signal,
689 int status)
690{
691 ProcessMessage message;
692 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
693 ProcessLinux *process = monitor->m_process;
694
695 switch (signal)
696 {
697 case 0:
698 // No signal. The child has exited normally.
699 message = ProcessMessage::Exit(pid, status);
700 break;
701
702 case SIGTRAP:
703 // Specially handle SIGTRAP and form the appropriate message.
704 message = MonitorSIGTRAP(monitor, pid);
705 break;
706
707 default:
708 // For all other signals simply notify the process instance. Note that
709 // the process exit status is set when the signal resulted in
710 // termination.
711 //
712 // FIXME: We need a specialized message to inform the process instance
713 // about "crashes".
714 if (status)
715 message = ProcessMessage::Exit(pid, status);
716 else
717 message = ProcessMessage::Signal(pid, signal);
718 }
719
720 process->SendMessage(message);
721 bool stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
722 return stop_monitoring;
723}
724
725ProcessMessage
726ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor, lldb::pid_t pid)
727{
728 siginfo_t info;
729 ProcessMessage message;
730 bool status;
731
732 status = monitor->GetSignalInfo(pid, &info);
733 assert(status && "GetSignalInfo failed!");
734
735 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
736
737 switch (info.si_code)
738 {
739 default:
740 assert(false && "Unexpected SIGTRAP code!");
741 break;
742
743 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
744 {
745 // The inferior process is about to exit. Maintain the process in a
746 // state of "limbo" until we are explicitly commanded to detach,
747 // destroy, resume, etc.
748 unsigned long data = 0;
749 if (!monitor->GetEventMessage(pid, &data))
750 data = -1;
751 message = ProcessMessage::Exit(pid, (data >> 8));
752 break;
753 }
754
755 case 0:
756 case TRAP_TRACE:
757 message = ProcessMessage::Trace(pid);
758 break;
759
760 case SI_KERNEL:
761 case TRAP_BRKPT:
762 message = ProcessMessage::Break(pid);
763 break;
764 }
765
766 return message;
767}
768
769void
770ProcessMonitor::ServeOperation(ProcessMonitor *monitor)
771{
772 int status;
773 pollfd fdset;
774
775 fdset.fd = monitor->m_server_fd;
776 fdset.events = POLLIN | POLLPRI;
777 fdset.revents = 0;
778
779 for (;;)
780 {
781 if ((status = poll(&fdset, 1, -1)) < 0)
782 {
783 switch (errno)
784 {
785 default:
786 assert(false && "Unexpected poll() failure!");
787 continue;
788
789 case EINTR: continue; // Just poll again.
790 case EBADF: return; // Connection terminated.
791 }
792 }
793
794 assert(status == 1 && "Too many descriptors!");
795
796 if (fdset.revents & POLLIN)
797 {
798 Operation *op = NULL;
799
800 READ_AGAIN:
801 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
802 {
803 // There is only one acceptable failure.
804 assert(errno == EINTR);
805 goto READ_AGAIN;
806 }
807
808 assert(status == sizeof(op));
809 op->Execute(monitor);
810 write(fdset.fd, &op, sizeof(op));
811 }
812 }
813}
814
815void
816ProcessMonitor::DoOperation(Operation *op)
817{
818 int status;
819 Operation *ack = NULL;
820 Mutex::Locker lock(m_server_mutex);
821
822 // FIXME: Do proper error checking here.
823 write(m_client_fd, &op, sizeof(op));
824
825READ_AGAIN:
826 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
827 {
828 // If interrupted by a signal handler try again. Otherwise the monitor
829 // thread probably died and we have a stale file descriptor -- abort the
830 // operation.
831 if (errno == EINTR)
832 goto READ_AGAIN;
833 return;
834 }
835
836 assert(status == sizeof(ack));
837 assert(ack == op && "Invalid monitor thread response!");
838}
839
840size_t
841ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
842 Error &error)
843{
844 size_t result;
845 ReadOperation op(vm_addr, buf, size, error, result);
846 DoOperation(&op);
847 return result;
848}
849
850size_t
851ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
852 lldb_private::Error &error)
853{
854 size_t result;
855 WriteOperation op(vm_addr, buf, size, error, result);
856 DoOperation(&op);
857 return result;
858}
859
860bool
861ProcessMonitor::ReadRegisterValue(unsigned offset, Scalar &value)
862{
863 bool result;
864 ReadRegOperation op(offset, value, result);
865 DoOperation(&op);
866 return result;
867}
868
869bool
870ProcessMonitor::WriteRegisterValue(unsigned offset, const Scalar &value)
871{
872 bool result;
873 WriteRegOperation op(offset, value, result);
874 DoOperation(&op);
875 return result;
876}
877
878bool
879ProcessMonitor::Resume(lldb::tid_t tid)
880{
881 bool result;
882 ResumeOperation op(tid, result);
883 DoOperation(&op);
884 return result;
885}
886
887bool
888ProcessMonitor::SingleStep(lldb::tid_t tid)
889{
890 bool result;
891 SingleStepOperation op(tid, result);
892 DoOperation(&op);
893 return result;
894}
895
896bool
897ProcessMonitor::BringProcessIntoLimbo()
898{
899 bool result;
900 KillOperation op(result);
901 DoOperation(&op);
902 return result;
903}
904
905bool
906ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo)
907{
908 bool result;
909 SiginfoOperation op(tid, siginfo, result);
910 DoOperation(&op);
911 return result;
912}
913
914bool
915ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
916{
917 bool result;
918 EventMessageOperation op(tid, message, result);
919 DoOperation(&op);
920 return result;
921}
922
923bool
924ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
925{
926 int target_fd = open(path, flags);
927
928 if (target_fd == -1)
929 return false;
930
931 return (dup2(fd, target_fd) == -1) ? false : true;
932}
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000933
934void
935ProcessMonitor::StopMonitoringChildProcess()
936{
937 lldb::thread_result_t thread_result;
938
939 if (m_monitor_thread != LLDB_INVALID_HOST_THREAD)
940 {
941 Host::ThreadCancel(m_monitor_thread, NULL);
942 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
943 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
944 }
945}