blob: 490ca6f60a3eee1f9acd364395e665f149ab28d1 [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);
Stephen Wilsond4182f42011-02-09 20:10:35 +0000558 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_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
Stephen Wilsond4182f42011-02-09 20:10:35 +0000583 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000584 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
Stephen Wilsond4182f42011-02-09 20:10:35 +0000595 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000596 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
Stephen Wilson570243b2011-01-19 01:37:06 +0000610 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000611 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:
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000719 return args->m_error.Success();
720}
721
722bool
723ProcessMonitor::EnableIPC()
724{
725 int fd[2];
726
727 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
728 return false;
729
730 m_client_fd = fd[0];
731 m_server_fd = fd[1];
732 return true;
733}
734
735bool
736ProcessMonitor::MonitorCallback(void *callback_baton,
737 lldb::pid_t pid,
738 int signal,
739 int status)
740{
741 ProcessMessage message;
742 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
743 ProcessLinux *process = monitor->m_process;
744
745 switch (signal)
746 {
747 case 0:
748 // No signal. The child has exited normally.
749 message = ProcessMessage::Exit(pid, status);
750 break;
751
752 case SIGTRAP:
753 // Specially handle SIGTRAP and form the appropriate message.
754 message = MonitorSIGTRAP(monitor, pid);
755 break;
756
757 default:
758 // For all other signals simply notify the process instance. Note that
759 // the process exit status is set when the signal resulted in
760 // termination.
761 //
762 // FIXME: We need a specialized message to inform the process instance
763 // about "crashes".
764 if (status)
765 message = ProcessMessage::Exit(pid, status);
766 else
767 message = ProcessMessage::Signal(pid, signal);
768 }
769
770 process->SendMessage(message);
771 bool stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
772 return stop_monitoring;
773}
774
775ProcessMessage
776ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor, lldb::pid_t pid)
777{
778 siginfo_t info;
779 ProcessMessage message;
780 bool status;
781
782 status = monitor->GetSignalInfo(pid, &info);
783 assert(status && "GetSignalInfo failed!");
784
785 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
786
787 switch (info.si_code)
788 {
789 default:
790 assert(false && "Unexpected SIGTRAP code!");
791 break;
792
793 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
794 {
795 // The inferior process is about to exit. Maintain the process in a
796 // state of "limbo" until we are explicitly commanded to detach,
797 // destroy, resume, etc.
798 unsigned long data = 0;
799 if (!monitor->GetEventMessage(pid, &data))
800 data = -1;
801 message = ProcessMessage::Exit(pid, (data >> 8));
802 break;
803 }
804
805 case 0:
806 case TRAP_TRACE:
807 message = ProcessMessage::Trace(pid);
808 break;
809
810 case SI_KERNEL:
811 case TRAP_BRKPT:
812 message = ProcessMessage::Break(pid);
813 break;
814 }
815
816 return message;
817}
818
819void
Stephen Wilson570243b2011-01-19 01:37:06 +0000820ProcessMonitor::ServeOperation(LaunchArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000821{
822 int status;
823 pollfd fdset;
Stephen Wilson570243b2011-01-19 01:37:06 +0000824 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000825
826 fdset.fd = monitor->m_server_fd;
827 fdset.events = POLLIN | POLLPRI;
828 fdset.revents = 0;
829
Stephen Wilson570243b2011-01-19 01:37:06 +0000830 // We are finised with the arguments and are ready to go. Sync with the
831 // parent thread and start serving operations on the inferior.
832 sem_post(&args->m_semaphore);
833
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000834 for (;;)
835 {
836 if ((status = poll(&fdset, 1, -1)) < 0)
837 {
838 switch (errno)
839 {
840 default:
841 assert(false && "Unexpected poll() failure!");
842 continue;
843
844 case EINTR: continue; // Just poll again.
845 case EBADF: return; // Connection terminated.
846 }
847 }
848
849 assert(status == 1 && "Too many descriptors!");
850
851 if (fdset.revents & POLLIN)
852 {
853 Operation *op = NULL;
854
855 READ_AGAIN:
856 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
857 {
858 // There is only one acceptable failure.
859 assert(errno == EINTR);
860 goto READ_AGAIN;
861 }
862
863 assert(status == sizeof(op));
864 op->Execute(monitor);
865 write(fdset.fd, &op, sizeof(op));
866 }
867 }
868}
869
870void
871ProcessMonitor::DoOperation(Operation *op)
872{
873 int status;
874 Operation *ack = NULL;
875 Mutex::Locker lock(m_server_mutex);
876
877 // FIXME: Do proper error checking here.
878 write(m_client_fd, &op, sizeof(op));
879
880READ_AGAIN:
881 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
882 {
883 // If interrupted by a signal handler try again. Otherwise the monitor
884 // thread probably died and we have a stale file descriptor -- abort the
885 // operation.
886 if (errno == EINTR)
887 goto READ_AGAIN;
888 return;
889 }
890
891 assert(status == sizeof(ack));
892 assert(ack == op && "Invalid monitor thread response!");
893}
894
895size_t
896ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
897 Error &error)
898{
899 size_t result;
900 ReadOperation op(vm_addr, buf, size, error, result);
901 DoOperation(&op);
902 return result;
903}
904
905size_t
906ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
907 lldb_private::Error &error)
908{
909 size_t result;
910 WriteOperation op(vm_addr, buf, size, error, result);
911 DoOperation(&op);
912 return result;
913}
914
915bool
916ProcessMonitor::ReadRegisterValue(unsigned offset, Scalar &value)
917{
918 bool result;
919 ReadRegOperation op(offset, value, result);
920 DoOperation(&op);
921 return result;
922}
923
924bool
925ProcessMonitor::WriteRegisterValue(unsigned offset, const Scalar &value)
926{
927 bool result;
928 WriteRegOperation op(offset, value, result);
929 DoOperation(&op);
930 return result;
931}
932
933bool
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000934ProcessMonitor::ReadGPR(void *buf)
935{
936 bool result;
937 ReadGPROperation op(buf, result);
938 DoOperation(&op);
939 return result;
940}
941
942bool
943ProcessMonitor::ReadFPR(void *buf)
944{
945 bool result;
946 ReadFPROperation op(buf, result);
947 DoOperation(&op);
948 return result;
949}
950
951bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000952ProcessMonitor::Resume(lldb::tid_t tid)
953{
954 bool result;
955 ResumeOperation op(tid, result);
956 DoOperation(&op);
957 return result;
958}
959
960bool
961ProcessMonitor::SingleStep(lldb::tid_t tid)
962{
963 bool result;
964 SingleStepOperation op(tid, result);
965 DoOperation(&op);
966 return result;
967}
968
969bool
970ProcessMonitor::BringProcessIntoLimbo()
971{
972 bool result;
973 KillOperation op(result);
974 DoOperation(&op);
975 return result;
976}
977
978bool
979ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo)
980{
981 bool result;
982 SiginfoOperation op(tid, siginfo, result);
983 DoOperation(&op);
984 return result;
985}
986
987bool
988ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
989{
990 bool result;
991 EventMessageOperation op(tid, message, result);
992 DoOperation(&op);
993 return result;
994}
995
996bool
997ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
998{
999 int target_fd = open(path, flags);
1000
1001 if (target_fd == -1)
1002 return false;
1003
1004 return (dup2(fd, target_fd) == -1) ? false : true;
1005}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001006
1007void
1008ProcessMonitor::StopMonitoringChildProcess()
1009{
1010 lldb::thread_result_t thread_result;
1011
Stephen Wilsond4182f42011-02-09 20:10:35 +00001012 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001013 {
1014 Host::ThreadCancel(m_monitor_thread, NULL);
1015 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1016 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1017 }
1018}