blob: 8fe74511108c1ed96425049f1a214e5cd79f32f5 [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//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000263/// @class ReadGPROperation
264/// @brief Implements ProcessMonitor::ReadGPR.
265class ReadGPROperation : public Operation
266{
267public:
268 ReadGPROperation(void *buf, bool &result)
269 : m_buf(buf), m_result(result)
270 { }
271
272 void Execute(ProcessMonitor *monitor);
273
274private:
275 void *m_buf;
276 bool &m_result;
277};
278
279void
280ReadGPROperation::Execute(ProcessMonitor *monitor)
281{
282 if (ptrace(PTRACE_GETREGS, monitor->GetPID(), NULL, m_buf) < 0)
283 m_result = false;
284 else
285 m_result = true;
286}
287
288//------------------------------------------------------------------------------
289/// @class ReadFPROperation
290/// @brief Implements ProcessMonitor::ReadFPR.
291class ReadFPROperation : public Operation
292{
293public:
294 ReadFPROperation(void *buf, bool &result)
295 : m_buf(buf), m_result(result)
296 { }
297
298 void Execute(ProcessMonitor *monitor);
299
300private:
301 void *m_buf;
302 bool &m_result;
303};
304
305void
306ReadFPROperation::Execute(ProcessMonitor *monitor)
307{
308 if (ptrace(PTRACE_GETFPREGS, monitor->GetPID(), NULL, m_buf) < 0)
309 m_result = false;
310 else
311 m_result = true;
312}
313
314//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000315/// @class ResumeOperation
316/// @brief Implements ProcessMonitor::Resume.
317class ResumeOperation : public Operation
318{
319public:
320 ResumeOperation(lldb::tid_t tid, bool &result) :
321 m_tid(tid), m_result(result) { }
322
323 void Execute(ProcessMonitor *monitor);
324
325private:
326 lldb::tid_t m_tid;
327 bool &m_result;
328};
329
330void
331ResumeOperation::Execute(ProcessMonitor *monitor)
332{
333 if (ptrace(PTRACE_CONT, m_tid, NULL, NULL))
334 m_result = false;
335 else
336 m_result = true;
337}
338
339//------------------------------------------------------------------------------
340/// @class ResumeOperation
341/// @brief Implements ProcessMonitor::SingleStep.
342class SingleStepOperation : public Operation
343{
344public:
345 SingleStepOperation(lldb::tid_t tid, bool &result)
346 : m_tid(tid), m_result(result) { }
347
348 void Execute(ProcessMonitor *monitor);
349
350private:
351 lldb::tid_t m_tid;
352 bool &m_result;
353};
354
355void
356SingleStepOperation::Execute(ProcessMonitor *monitor)
357{
358 if (ptrace(PTRACE_SINGLESTEP, m_tid, NULL, NULL))
359 m_result = false;
360 else
361 m_result = true;
362}
363
364//------------------------------------------------------------------------------
365/// @class SiginfoOperation
366/// @brief Implements ProcessMonitor::GetSignalInfo.
367class SiginfoOperation : public Operation
368{
369public:
370 SiginfoOperation(lldb::tid_t tid, void *info, bool &result)
371 : m_tid(tid), m_info(info), m_result(result) { }
372
373 void Execute(ProcessMonitor *monitor);
374
375private:
376 lldb::tid_t m_tid;
377 void *m_info;
378 bool &m_result;
379};
380
381void
382SiginfoOperation::Execute(ProcessMonitor *monitor)
383{
384 if (ptrace(PTRACE_GETSIGINFO, m_tid, NULL, m_info))
385 m_result = false;
386 else
387 m_result = true;
388}
389
390//------------------------------------------------------------------------------
391/// @class EventMessageOperation
392/// @brief Implements ProcessMonitor::GetEventMessage.
393class EventMessageOperation : public Operation
394{
395public:
396 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
397 : m_tid(tid), m_message(message), m_result(result) { }
398
399 void Execute(ProcessMonitor *monitor);
400
401private:
402 lldb::tid_t m_tid;
403 unsigned long *m_message;
404 bool &m_result;
405};
406
407void
408EventMessageOperation::Execute(ProcessMonitor *monitor)
409{
410 if (ptrace(PTRACE_GETEVENTMSG, m_tid, NULL, m_message))
411 m_result = false;
412 else
413 m_result = true;
414}
415
416//------------------------------------------------------------------------------
417/// @class KillOperation
418/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
419class KillOperation : public Operation
420{
421public:
422 KillOperation(bool &result) : m_result(result) { }
423
424 void Execute(ProcessMonitor *monitor);
425
426private:
427 bool &m_result;
428};
429
430void
431KillOperation::Execute(ProcessMonitor *monitor)
432{
433 lldb::pid_t pid = monitor->GetPID();
434
435 if (ptrace(PTRACE_KILL, pid, NULL, NULL))
436 m_result = false;
437 else
438 m_result = true;
439
440#if 0
441 // First, stop the inferior process.
442 if (kill(pid, SIGSTOP))
443 {
444 m_result = false;
445 return;
446 }
447
448 // Clear any ptrace options. When PTRACE_O_TRACEEXIT is set, a plain
449 // PTRACE_KILL (or any termination signal) will not truely terminate the
450 // inferior process. Instead, the process is left in a state of "limbo"
451 // allowing us to interrogate its state. However in this case we really do
452 // want the process gone.
453 if (ptrace(PTRACE_SETOPTIONS, pid, NULL, 0UL))
454 {
455 m_result = false;
456 return;
457 }
458
459 // Kill it.
460 if (ptrace(PTRACE_KILL, pid, NULL, NULL))
461 m_result = false;
462 else
463 m_result = true;
464#endif
465}
466
467ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
468 lldb_private::Module *module,
469 char const **argv,
470 char const **envp,
471 const char *stdin_path,
472 const char *stdout_path,
473 const char *stderr_path)
474 : m_monitor(monitor),
475 m_module(module),
476 m_argv(argv),
477 m_envp(envp),
478 m_stdin_path(stdin_path),
479 m_stdout_path(stdout_path),
480 m_stderr_path(stderr_path)
481{
482 sem_init(&m_semaphore, 0, 0);
483}
484
485ProcessMonitor::LaunchArgs::~LaunchArgs()
486{
487 sem_destroy(&m_semaphore);
488}
489
490//------------------------------------------------------------------------------
491/// The basic design of the ProcessMonitor is built around two threads.
492///
493/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
494/// for changes in the debugee state. When a change is detected a
495/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
496/// "drives" state changes in the debugger.
497///
498/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000499/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000500/// operations such as register reads/writes, stepping, etc. See the comments
501/// on the Operation class for more info as to why this is needed.
502ProcessMonitor::ProcessMonitor(ProcessLinux *process,
503 Module *module,
504 const char *argv[],
505 const char *envp[],
506 const char *stdin_path,
507 const char *stdout_path,
508 const char *stderr_path,
509 lldb_private::Error &error)
510 : m_process(process),
511 m_operation_thread(LLDB_INVALID_HOST_THREAD),
512 m_pid(LLDB_INVALID_PROCESS_ID),
513 m_terminal_fd(-1),
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000514 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000515 m_client_fd(-1),
516 m_server_fd(-1)
517{
Stephen Wilson57740ec2011-01-15 00:12:41 +0000518 std::auto_ptr<LaunchArgs> args;
519
520 args.reset(new LaunchArgs(this, module, argv, envp,
521 stdin_path, stdout_path, stderr_path));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000522
523 // Server/client descriptors.
524 if (!EnableIPC())
525 {
526 error.SetErrorToGenericError();
527 error.SetErrorString("Monitor failed to initialize.");
528 }
529
Stephen Wilson57740ec2011-01-15 00:12:41 +0000530 StartOperationThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000531 if (!error.Success())
532 return;
533
534WAIT_AGAIN:
535 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000536 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000537 {
538 if (errno == EINTR)
539 goto WAIT_AGAIN;
540 else
541 {
542 error.SetErrorToErrno();
543 return;
544 }
545 }
546
547 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000548 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000549 {
550 StopOperationThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000551 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000552 return;
553 }
554
555 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000556 m_monitor_thread = Host::StartMonitoringChildProcess(
557 ProcessMonitor::MonitorCallback, this, GetPID(), true);
558 if (m_monitor_thread == LLDB_INVALID_HOST_THREAD)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000559 {
560 error.SetErrorToGenericError();
561 error.SetErrorString("Process launch failed.");
562 return;
563 }
564}
565
566ProcessMonitor::~ProcessMonitor()
567{
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000568 StopMonitoringChildProcess();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000569 StopOperationThread();
570
571 close(m_terminal_fd);
572 close(m_client_fd);
573 close(m_server_fd);
574}
575
576//------------------------------------------------------------------------------
577// Thread setup and tear down.
578void
579ProcessMonitor::StartOperationThread(LaunchArgs *args, Error &error)
580{
581 static const char *g_thread_name = "lldb.process.linux.operation";
582
583 if (m_operation_thread != LLDB_INVALID_HOST_THREAD)
584 return;
585
586 m_operation_thread =
587 Host::ThreadCreate(g_thread_name, OperationThread, args, &error);
588}
589
590void
591ProcessMonitor::StopOperationThread()
592{
593 lldb::thread_result_t result;
594
595 if (m_operation_thread == LLDB_INVALID_HOST_THREAD)
596 return;
597
598 Host::ThreadCancel(m_operation_thread, NULL);
599 Host::ThreadJoin(m_operation_thread, &result, NULL);
600}
601
602void *
603ProcessMonitor::OperationThread(void *arg)
604{
605 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
606
607 if (!Launch(args))
608 return NULL;
609
610 ServeOperation(args->m_monitor);
611 return NULL;
612}
613
614bool
615ProcessMonitor::Launch(LaunchArgs *args)
616{
617 ProcessMonitor *monitor = args->m_monitor;
618 ProcessLinux &process = monitor->GetProcess();
619 const char **argv = args->m_argv;
620 const char **envp = args->m_envp;
621 const char *stdin_path = args->m_stdin_path;
622 const char *stdout_path = args->m_stdout_path;
623 const char *stderr_path = args->m_stderr_path;
624
625 lldb_utility::PseudoTerminal terminal;
626 const size_t err_len = 1024;
627 char err_str[err_len];
628 lldb::pid_t pid;
629
630 lldb::ThreadSP inferior;
631
Stephen Wilson57740ec2011-01-15 00:12:41 +0000632 // Propagate the environment if one is not supplied.
633 if (envp == NULL || envp[0] == NULL)
634 envp = const_cast<const char **>(environ);
635
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000636 // Pseudo terminal setup.
637 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
638 {
639 args->m_error.SetErrorToGenericError();
640 args->m_error.SetErrorString("Could not open controlling TTY.");
641 goto FINISH;
642 }
643
644 if ((pid = terminal.Fork(err_str, err_len)) < 0)
645 {
646 args->m_error.SetErrorToGenericError();
647 args->m_error.SetErrorString("Process fork failed.");
648 goto FINISH;
649 }
650
651 // Child process.
652 if (pid == 0)
653 {
654 // Trace this process.
655 ptrace(PTRACE_TRACEME, 0, NULL, NULL);
656
657 // Do not inherit setgid powers.
658 setgid(getgid());
659
660 // Let us have our own process group.
661 setpgid(0, 0);
662
Greg Clayton710dd5a2011-01-08 20:28:42 +0000663 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000664 //
665 // FIXME: If two or more of the paths are the same we needlessly open
666 // the same file multiple times.
667 if (stdin_path != NULL && stdin_path[0])
668 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY | O_CREAT))
669 exit(1);
670
671 if (stdout_path != NULL && stdout_path[0])
672 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
673 exit(1);
674
675 if (stderr_path != NULL && stderr_path[0])
676 if (!DupDescriptor(stderr_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
677 exit(1);
678
679 // Execute. We should never return.
680 execve(argv[0],
681 const_cast<char *const *>(argv),
682 const_cast<char *const *>(envp));
683 exit(-1);
684 }
685
686 // Wait for the child process to to trap on its call to execve.
687 int status;
688 if ((status = waitpid(pid, NULL, 0)) < 0)
689 {
690 // execve likely failed for some reason.
691 args->m_error.SetErrorToErrno();
692 goto FINISH;
693 }
694 assert(status == pid && "Could not sync with inferior process.");
695
696 // Have the child raise an event on exit. This is used to keep the child in
697 // limbo until it is destroyed.
698 if (ptrace(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0)
699 {
700 args->m_error.SetErrorToErrno();
701 goto FINISH;
702 }
703
704 // Release the master terminal descriptor and pass it off to the
705 // ProcessMonitor instance. Similarly stash the inferior pid.
706 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
707 monitor->m_pid = pid;
708
709 // Update the process thread list with this new thread and mark it as
710 // current.
711 inferior.reset(new LinuxThread(process, pid));
712 process.GetThreadList().AddThread(inferior);
Stephen Wilson5a8feea2011-01-04 21:39:27 +0000713 process.GetThreadList().SetSelectedThreadByID(pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000714
715 // Let our process instance know the thread has stopped.
716 process.SendMessage(ProcessMessage::Trace(pid));
717
718FINISH:
719 // Sync with our parent thread now that the launch operation is complete.
720 sem_post(&args->m_semaphore);
721 return args->m_error.Success();
722}
723
724bool
725ProcessMonitor::EnableIPC()
726{
727 int fd[2];
728
729 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
730 return false;
731
732 m_client_fd = fd[0];
733 m_server_fd = fd[1];
734 return true;
735}
736
737bool
738ProcessMonitor::MonitorCallback(void *callback_baton,
739 lldb::pid_t pid,
740 int signal,
741 int status)
742{
743 ProcessMessage message;
744 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
745 ProcessLinux *process = monitor->m_process;
746
747 switch (signal)
748 {
749 case 0:
750 // No signal. The child has exited normally.
751 message = ProcessMessage::Exit(pid, status);
752 break;
753
754 case SIGTRAP:
755 // Specially handle SIGTRAP and form the appropriate message.
756 message = MonitorSIGTRAP(monitor, pid);
757 break;
758
759 default:
760 // For all other signals simply notify the process instance. Note that
761 // the process exit status is set when the signal resulted in
762 // termination.
763 //
764 // FIXME: We need a specialized message to inform the process instance
765 // about "crashes".
766 if (status)
767 message = ProcessMessage::Exit(pid, status);
768 else
769 message = ProcessMessage::Signal(pid, signal);
770 }
771
772 process->SendMessage(message);
773 bool stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
774 return stop_monitoring;
775}
776
777ProcessMessage
778ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor, lldb::pid_t pid)
779{
780 siginfo_t info;
781 ProcessMessage message;
782 bool status;
783
784 status = monitor->GetSignalInfo(pid, &info);
785 assert(status && "GetSignalInfo failed!");
786
787 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
788
789 switch (info.si_code)
790 {
791 default:
792 assert(false && "Unexpected SIGTRAP code!");
793 break;
794
795 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
796 {
797 // The inferior process is about to exit. Maintain the process in a
798 // state of "limbo" until we are explicitly commanded to detach,
799 // destroy, resume, etc.
800 unsigned long data = 0;
801 if (!monitor->GetEventMessage(pid, &data))
802 data = -1;
803 message = ProcessMessage::Exit(pid, (data >> 8));
804 break;
805 }
806
807 case 0:
808 case TRAP_TRACE:
809 message = ProcessMessage::Trace(pid);
810 break;
811
812 case SI_KERNEL:
813 case TRAP_BRKPT:
814 message = ProcessMessage::Break(pid);
815 break;
816 }
817
818 return message;
819}
820
821void
822ProcessMonitor::ServeOperation(ProcessMonitor *monitor)
823{
824 int status;
825 pollfd fdset;
826
827 fdset.fd = monitor->m_server_fd;
828 fdset.events = POLLIN | POLLPRI;
829 fdset.revents = 0;
830
831 for (;;)
832 {
833 if ((status = poll(&fdset, 1, -1)) < 0)
834 {
835 switch (errno)
836 {
837 default:
838 assert(false && "Unexpected poll() failure!");
839 continue;
840
841 case EINTR: continue; // Just poll again.
842 case EBADF: return; // Connection terminated.
843 }
844 }
845
846 assert(status == 1 && "Too many descriptors!");
847
848 if (fdset.revents & POLLIN)
849 {
850 Operation *op = NULL;
851
852 READ_AGAIN:
853 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
854 {
855 // There is only one acceptable failure.
856 assert(errno == EINTR);
857 goto READ_AGAIN;
858 }
859
860 assert(status == sizeof(op));
861 op->Execute(monitor);
862 write(fdset.fd, &op, sizeof(op));
863 }
864 }
865}
866
867void
868ProcessMonitor::DoOperation(Operation *op)
869{
870 int status;
871 Operation *ack = NULL;
872 Mutex::Locker lock(m_server_mutex);
873
874 // FIXME: Do proper error checking here.
875 write(m_client_fd, &op, sizeof(op));
876
877READ_AGAIN:
878 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
879 {
880 // If interrupted by a signal handler try again. Otherwise the monitor
881 // thread probably died and we have a stale file descriptor -- abort the
882 // operation.
883 if (errno == EINTR)
884 goto READ_AGAIN;
885 return;
886 }
887
888 assert(status == sizeof(ack));
889 assert(ack == op && "Invalid monitor thread response!");
890}
891
892size_t
893ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
894 Error &error)
895{
896 size_t result;
897 ReadOperation op(vm_addr, buf, size, error, result);
898 DoOperation(&op);
899 return result;
900}
901
902size_t
903ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
904 lldb_private::Error &error)
905{
906 size_t result;
907 WriteOperation op(vm_addr, buf, size, error, result);
908 DoOperation(&op);
909 return result;
910}
911
912bool
913ProcessMonitor::ReadRegisterValue(unsigned offset, Scalar &value)
914{
915 bool result;
916 ReadRegOperation op(offset, value, result);
917 DoOperation(&op);
918 return result;
919}
920
921bool
922ProcessMonitor::WriteRegisterValue(unsigned offset, const Scalar &value)
923{
924 bool result;
925 WriteRegOperation op(offset, value, result);
926 DoOperation(&op);
927 return result;
928}
929
930bool
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000931ProcessMonitor::ReadGPR(void *buf)
932{
933 bool result;
934 ReadGPROperation op(buf, result);
935 DoOperation(&op);
936 return result;
937}
938
939bool
940ProcessMonitor::ReadFPR(void *buf)
941{
942 bool result;
943 ReadFPROperation op(buf, result);
944 DoOperation(&op);
945 return result;
946}
947
948bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000949ProcessMonitor::Resume(lldb::tid_t tid)
950{
951 bool result;
952 ResumeOperation op(tid, result);
953 DoOperation(&op);
954 return result;
955}
956
957bool
958ProcessMonitor::SingleStep(lldb::tid_t tid)
959{
960 bool result;
961 SingleStepOperation op(tid, result);
962 DoOperation(&op);
963 return result;
964}
965
966bool
967ProcessMonitor::BringProcessIntoLimbo()
968{
969 bool result;
970 KillOperation op(result);
971 DoOperation(&op);
972 return result;
973}
974
975bool
976ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo)
977{
978 bool result;
979 SiginfoOperation op(tid, siginfo, result);
980 DoOperation(&op);
981 return result;
982}
983
984bool
985ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
986{
987 bool result;
988 EventMessageOperation op(tid, message, result);
989 DoOperation(&op);
990 return result;
991}
992
993bool
994ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
995{
996 int target_fd = open(path, flags);
997
998 if (target_fd == -1)
999 return false;
1000
1001 return (dup2(fd, target_fd) == -1) ? false : true;
1002}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001003
1004void
1005ProcessMonitor::StopMonitoringChildProcess()
1006{
1007 lldb::thread_result_t thread_result;
1008
1009 if (m_monitor_thread != LLDB_INVALID_HOST_THREAD)
1010 {
1011 Host::ThreadCancel(m_monitor_thread, NULL);
1012 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1013 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1014 }
1015}