blob: c5909c85a6da1a4faaa7c0361b7facc351177183 [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
Stephen Wilson26977162011-03-23 02:14:42 +0000117// Simple helper function to ensure flags are enabled on the given file
118// descriptor.
119static bool
120EnsureFDFlags(int fd, int flags, Error &error)
121{
122 int status;
123
124 if ((status = fcntl(fd, F_GETFL)) == -1)
125 {
126 error.SetErrorToErrno();
127 return false;
128 }
129
130 if (fcntl(fd, F_SETFL, status | flags) == -1)
131 {
132 error.SetErrorToErrno();
133 return false;
134 }
135
136 return true;
137}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000138
139//------------------------------------------------------------------------------
140/// @class Operation
141/// @brief Represents a ProcessMonitor operation.
142///
143/// Under Linux, it is not possible to ptrace() from any other thread but the
144/// one that spawned or attached to the process from the start. Therefore, when
145/// a ProcessMonitor is asked to deliver or change the state of an inferior
146/// process the operation must be "funneled" to a specific thread to perform the
147/// task. The Operation class provides an abstract base for all services the
148/// ProcessMonitor must perform via the single virtual function Execute, thus
149/// encapsulating the code that needs to run in the privileged context.
150class Operation
151{
152public:
153 virtual void Execute(ProcessMonitor *monitor) = 0;
154};
155
156//------------------------------------------------------------------------------
157/// @class ReadOperation
158/// @brief Implements ProcessMonitor::ReadMemory.
159class ReadOperation : public Operation
160{
161public:
162 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
163 Error &error, size_t &result)
164 : m_addr(addr), m_buff(buff), m_size(size),
165 m_error(error), m_result(result)
166 { }
167
168 void Execute(ProcessMonitor *monitor);
169
170private:
171 lldb::addr_t m_addr;
172 void *m_buff;
173 size_t m_size;
174 Error &m_error;
175 size_t &m_result;
176};
177
178void
179ReadOperation::Execute(ProcessMonitor *monitor)
180{
181 const unsigned word_size = monitor->GetProcess().GetAddressByteSize();
182 lldb::pid_t pid = monitor->GetPID();
183
184 m_result = DoReadMemory(pid, word_size, m_addr, m_buff, m_size, m_error);
185}
186
187//------------------------------------------------------------------------------
188/// @class ReadOperation
189/// @brief Implements ProcessMonitor::WriteMemory.
190class WriteOperation : public Operation
191{
192public:
193 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
194 Error &error, size_t &result)
195 : m_addr(addr), m_buff(buff), m_size(size),
196 m_error(error), m_result(result)
197 { }
198
199 void Execute(ProcessMonitor *monitor);
200
201private:
202 lldb::addr_t m_addr;
203 const void *m_buff;
204 size_t m_size;
205 Error &m_error;
206 size_t &m_result;
207};
208
209void
210WriteOperation::Execute(ProcessMonitor *monitor)
211{
212 const unsigned word_size = monitor->GetProcess().GetAddressByteSize();
213 lldb::pid_t pid = monitor->GetPID();
214
215 m_result = DoWriteMemory(pid, word_size, m_addr, m_buff, m_size, m_error);
216}
217
218//------------------------------------------------------------------------------
219/// @class ReadRegOperation
220/// @brief Implements ProcessMonitor::ReadRegisterValue.
221class ReadRegOperation : public Operation
222{
223public:
224 ReadRegOperation(unsigned offset, Scalar &value, bool &result)
225 : m_offset(offset), m_value(value), m_result(result)
226 { }
227
228 void Execute(ProcessMonitor *monitor);
229
230private:
231 unsigned m_offset;
232 Scalar &m_value;
233 bool &m_result;
234};
235
236void
237ReadRegOperation::Execute(ProcessMonitor *monitor)
238{
239 lldb::pid_t pid = monitor->GetPID();
240
241 // Set errno to zero so that we can detect a failed peek.
242 errno = 0;
243 unsigned long data = ptrace(PTRACE_PEEKUSER, pid, m_offset, NULL);
244
245 if (data == -1UL && errno)
246 m_result = false;
247 else
248 {
249 m_value = data;
250 m_result = true;
251 }
252}
253
254//------------------------------------------------------------------------------
255/// @class WriteRegOperation
256/// @brief Implements ProcessMonitor::WriteRegisterValue.
257class WriteRegOperation : public Operation
258{
259public:
260 WriteRegOperation(unsigned offset, const Scalar &value, bool &result)
261 : m_offset(offset), m_value(value), m_result(result)
262 { }
263
264 void Execute(ProcessMonitor *monitor);
265
266private:
267 unsigned m_offset;
268 const Scalar &m_value;
269 bool &m_result;
270};
271
272void
273WriteRegOperation::Execute(ProcessMonitor *monitor)
274{
275 lldb::pid_t pid = monitor->GetPID();
276
277 if (ptrace(PTRACE_POKEUSER, pid, m_offset, m_value.ULong()))
278 m_result = false;
279 else
280 m_result = true;
281}
282
283//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000284/// @class ReadGPROperation
285/// @brief Implements ProcessMonitor::ReadGPR.
286class ReadGPROperation : public Operation
287{
288public:
289 ReadGPROperation(void *buf, bool &result)
290 : m_buf(buf), m_result(result)
291 { }
292
293 void Execute(ProcessMonitor *monitor);
294
295private:
296 void *m_buf;
297 bool &m_result;
298};
299
300void
301ReadGPROperation::Execute(ProcessMonitor *monitor)
302{
303 if (ptrace(PTRACE_GETREGS, monitor->GetPID(), NULL, m_buf) < 0)
304 m_result = false;
305 else
306 m_result = true;
307}
308
309//------------------------------------------------------------------------------
310/// @class ReadFPROperation
311/// @brief Implements ProcessMonitor::ReadFPR.
312class ReadFPROperation : public Operation
313{
314public:
315 ReadFPROperation(void *buf, bool &result)
316 : m_buf(buf), m_result(result)
317 { }
318
319 void Execute(ProcessMonitor *monitor);
320
321private:
322 void *m_buf;
323 bool &m_result;
324};
325
326void
327ReadFPROperation::Execute(ProcessMonitor *monitor)
328{
329 if (ptrace(PTRACE_GETFPREGS, monitor->GetPID(), NULL, m_buf) < 0)
330 m_result = false;
331 else
332 m_result = true;
333}
334
335//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000336/// @class ResumeOperation
337/// @brief Implements ProcessMonitor::Resume.
338class ResumeOperation : public Operation
339{
340public:
341 ResumeOperation(lldb::tid_t tid, bool &result) :
342 m_tid(tid), m_result(result) { }
343
344 void Execute(ProcessMonitor *monitor);
345
346private:
347 lldb::tid_t m_tid;
348 bool &m_result;
349};
350
351void
352ResumeOperation::Execute(ProcessMonitor *monitor)
353{
354 if (ptrace(PTRACE_CONT, m_tid, NULL, NULL))
355 m_result = false;
356 else
357 m_result = true;
358}
359
360//------------------------------------------------------------------------------
361/// @class ResumeOperation
362/// @brief Implements ProcessMonitor::SingleStep.
363class SingleStepOperation : public Operation
364{
365public:
366 SingleStepOperation(lldb::tid_t tid, bool &result)
367 : m_tid(tid), m_result(result) { }
368
369 void Execute(ProcessMonitor *monitor);
370
371private:
372 lldb::tid_t m_tid;
373 bool &m_result;
374};
375
376void
377SingleStepOperation::Execute(ProcessMonitor *monitor)
378{
379 if (ptrace(PTRACE_SINGLESTEP, m_tid, NULL, NULL))
380 m_result = false;
381 else
382 m_result = true;
383}
384
385//------------------------------------------------------------------------------
386/// @class SiginfoOperation
387/// @brief Implements ProcessMonitor::GetSignalInfo.
388class SiginfoOperation : public Operation
389{
390public:
391 SiginfoOperation(lldb::tid_t tid, void *info, bool &result)
392 : m_tid(tid), m_info(info), m_result(result) { }
393
394 void Execute(ProcessMonitor *monitor);
395
396private:
397 lldb::tid_t m_tid;
398 void *m_info;
399 bool &m_result;
400};
401
402void
403SiginfoOperation::Execute(ProcessMonitor *monitor)
404{
405 if (ptrace(PTRACE_GETSIGINFO, m_tid, NULL, m_info))
406 m_result = false;
407 else
408 m_result = true;
409}
410
411//------------------------------------------------------------------------------
412/// @class EventMessageOperation
413/// @brief Implements ProcessMonitor::GetEventMessage.
414class EventMessageOperation : public Operation
415{
416public:
417 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
418 : m_tid(tid), m_message(message), m_result(result) { }
419
420 void Execute(ProcessMonitor *monitor);
421
422private:
423 lldb::tid_t m_tid;
424 unsigned long *m_message;
425 bool &m_result;
426};
427
428void
429EventMessageOperation::Execute(ProcessMonitor *monitor)
430{
431 if (ptrace(PTRACE_GETEVENTMSG, m_tid, NULL, m_message))
432 m_result = false;
433 else
434 m_result = true;
435}
436
437//------------------------------------------------------------------------------
438/// @class KillOperation
439/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
440class KillOperation : public Operation
441{
442public:
443 KillOperation(bool &result) : m_result(result) { }
444
445 void Execute(ProcessMonitor *monitor);
446
447private:
448 bool &m_result;
449};
450
451void
452KillOperation::Execute(ProcessMonitor *monitor)
453{
454 lldb::pid_t pid = monitor->GetPID();
455
456 if (ptrace(PTRACE_KILL, pid, NULL, NULL))
457 m_result = false;
458 else
459 m_result = true;
460
461#if 0
462 // First, stop the inferior process.
463 if (kill(pid, SIGSTOP))
464 {
465 m_result = false;
466 return;
467 }
468
469 // Clear any ptrace options. When PTRACE_O_TRACEEXIT is set, a plain
470 // PTRACE_KILL (or any termination signal) will not truely terminate the
471 // inferior process. Instead, the process is left in a state of "limbo"
472 // allowing us to interrogate its state. However in this case we really do
473 // want the process gone.
474 if (ptrace(PTRACE_SETOPTIONS, pid, NULL, 0UL))
475 {
476 m_result = false;
477 return;
478 }
479
480 // Kill it.
481 if (ptrace(PTRACE_KILL, pid, NULL, NULL))
482 m_result = false;
483 else
484 m_result = true;
485#endif
486}
487
488ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
489 lldb_private::Module *module,
490 char const **argv,
491 char const **envp,
492 const char *stdin_path,
493 const char *stdout_path,
494 const char *stderr_path)
495 : m_monitor(monitor),
496 m_module(module),
497 m_argv(argv),
498 m_envp(envp),
499 m_stdin_path(stdin_path),
500 m_stdout_path(stdout_path),
501 m_stderr_path(stderr_path)
502{
503 sem_init(&m_semaphore, 0, 0);
504}
505
506ProcessMonitor::LaunchArgs::~LaunchArgs()
507{
508 sem_destroy(&m_semaphore);
509}
510
511//------------------------------------------------------------------------------
512/// The basic design of the ProcessMonitor is built around two threads.
513///
514/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
515/// for changes in the debugee state. When a change is detected a
516/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
517/// "drives" state changes in the debugger.
518///
519/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000520/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000521/// operations such as register reads/writes, stepping, etc. See the comments
522/// on the Operation class for more info as to why this is needed.
523ProcessMonitor::ProcessMonitor(ProcessLinux *process,
524 Module *module,
525 const char *argv[],
526 const char *envp[],
527 const char *stdin_path,
528 const char *stdout_path,
529 const char *stderr_path,
530 lldb_private::Error &error)
531 : m_process(process),
532 m_operation_thread(LLDB_INVALID_HOST_THREAD),
533 m_pid(LLDB_INVALID_PROCESS_ID),
534 m_terminal_fd(-1),
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000535 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000536 m_client_fd(-1),
537 m_server_fd(-1)
538{
Stephen Wilson57740ec2011-01-15 00:12:41 +0000539 std::auto_ptr<LaunchArgs> args;
540
541 args.reset(new LaunchArgs(this, module, argv, envp,
542 stdin_path, stdout_path, stderr_path));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000543
544 // Server/client descriptors.
545 if (!EnableIPC())
546 {
547 error.SetErrorToGenericError();
548 error.SetErrorString("Monitor failed to initialize.");
549 }
550
Stephen Wilson57740ec2011-01-15 00:12:41 +0000551 StartOperationThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000552 if (!error.Success())
553 return;
554
555WAIT_AGAIN:
556 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000557 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000558 {
559 if (errno == EINTR)
560 goto WAIT_AGAIN;
561 else
562 {
563 error.SetErrorToErrno();
564 return;
565 }
566 }
567
568 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000569 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000570 {
571 StopOperationThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000572 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000573 return;
574 }
575
576 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000577 m_monitor_thread = Host::StartMonitoringChildProcess(
578 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Stephen Wilsond4182f42011-02-09 20:10:35 +0000579 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000580 {
581 error.SetErrorToGenericError();
582 error.SetErrorString("Process launch failed.");
583 return;
584 }
585}
586
587ProcessMonitor::~ProcessMonitor()
588{
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000589 StopMonitoringChildProcess();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000590 StopOperationThread();
591
592 close(m_terminal_fd);
593 close(m_client_fd);
594 close(m_server_fd);
595}
596
597//------------------------------------------------------------------------------
598// Thread setup and tear down.
599void
600ProcessMonitor::StartOperationThread(LaunchArgs *args, Error &error)
601{
602 static const char *g_thread_name = "lldb.process.linux.operation";
603
Stephen Wilsond4182f42011-02-09 20:10:35 +0000604 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000605 return;
606
607 m_operation_thread =
608 Host::ThreadCreate(g_thread_name, OperationThread, args, &error);
609}
610
611void
612ProcessMonitor::StopOperationThread()
613{
614 lldb::thread_result_t result;
615
Stephen Wilsond4182f42011-02-09 20:10:35 +0000616 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000617 return;
618
619 Host::ThreadCancel(m_operation_thread, NULL);
620 Host::ThreadJoin(m_operation_thread, &result, NULL);
621}
622
623void *
624ProcessMonitor::OperationThread(void *arg)
625{
626 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
627
628 if (!Launch(args))
629 return NULL;
630
Stephen Wilson570243b2011-01-19 01:37:06 +0000631 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000632 return NULL;
633}
634
635bool
636ProcessMonitor::Launch(LaunchArgs *args)
637{
638 ProcessMonitor *monitor = args->m_monitor;
639 ProcessLinux &process = monitor->GetProcess();
640 const char **argv = args->m_argv;
641 const char **envp = args->m_envp;
642 const char *stdin_path = args->m_stdin_path;
643 const char *stdout_path = args->m_stdout_path;
644 const char *stderr_path = args->m_stderr_path;
645
646 lldb_utility::PseudoTerminal terminal;
647 const size_t err_len = 1024;
648 char err_str[err_len];
649 lldb::pid_t pid;
650
651 lldb::ThreadSP inferior;
652
Stephen Wilson57740ec2011-01-15 00:12:41 +0000653 // Propagate the environment if one is not supplied.
654 if (envp == NULL || envp[0] == NULL)
655 envp = const_cast<const char **>(environ);
656
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000657 // Pseudo terminal setup.
658 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
659 {
660 args->m_error.SetErrorToGenericError();
661 args->m_error.SetErrorString("Could not open controlling TTY.");
662 goto FINISH;
663 }
664
665 if ((pid = terminal.Fork(err_str, err_len)) < 0)
666 {
667 args->m_error.SetErrorToGenericError();
668 args->m_error.SetErrorString("Process fork failed.");
669 goto FINISH;
670 }
671
672 // Child process.
673 if (pid == 0)
674 {
675 // Trace this process.
676 ptrace(PTRACE_TRACEME, 0, NULL, NULL);
677
678 // Do not inherit setgid powers.
679 setgid(getgid());
680
681 // Let us have our own process group.
682 setpgid(0, 0);
683
Greg Clayton710dd5a2011-01-08 20:28:42 +0000684 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000685 //
686 // FIXME: If two or more of the paths are the same we needlessly open
687 // the same file multiple times.
688 if (stdin_path != NULL && stdin_path[0])
689 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY | O_CREAT))
690 exit(1);
691
692 if (stdout_path != NULL && stdout_path[0])
693 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
694 exit(1);
695
696 if (stderr_path != NULL && stderr_path[0])
697 if (!DupDescriptor(stderr_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
698 exit(1);
699
700 // Execute. We should never return.
701 execve(argv[0],
702 const_cast<char *const *>(argv),
703 const_cast<char *const *>(envp));
704 exit(-1);
705 }
706
707 // Wait for the child process to to trap on its call to execve.
708 int status;
709 if ((status = waitpid(pid, NULL, 0)) < 0)
710 {
711 // execve likely failed for some reason.
712 args->m_error.SetErrorToErrno();
713 goto FINISH;
714 }
715 assert(status == pid && "Could not sync with inferior process.");
716
717 // Have the child raise an event on exit. This is used to keep the child in
718 // limbo until it is destroyed.
719 if (ptrace(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0)
720 {
721 args->m_error.SetErrorToErrno();
722 goto FINISH;
723 }
724
725 // Release the master terminal descriptor and pass it off to the
726 // ProcessMonitor instance. Similarly stash the inferior pid.
727 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
728 monitor->m_pid = pid;
729
Stephen Wilson26977162011-03-23 02:14:42 +0000730 // Set the terminal fd to be in non blocking mode (it simplifies the
731 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
732 // descriptor to read from).
733 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
734 goto FINISH;
735
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000736 // Update the process thread list with this new thread and mark it as
737 // current.
738 inferior.reset(new LinuxThread(process, pid));
739 process.GetThreadList().AddThread(inferior);
Stephen Wilson5a8feea2011-01-04 21:39:27 +0000740 process.GetThreadList().SetSelectedThreadByID(pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000741
742 // Let our process instance know the thread has stopped.
743 process.SendMessage(ProcessMessage::Trace(pid));
744
745FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000746 return args->m_error.Success();
747}
748
749bool
750ProcessMonitor::EnableIPC()
751{
752 int fd[2];
753
754 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
755 return false;
756
757 m_client_fd = fd[0];
758 m_server_fd = fd[1];
759 return true;
760}
761
762bool
763ProcessMonitor::MonitorCallback(void *callback_baton,
764 lldb::pid_t pid,
765 int signal,
766 int status)
767{
768 ProcessMessage message;
769 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
770 ProcessLinux *process = monitor->m_process;
771
772 switch (signal)
773 {
774 case 0:
775 // No signal. The child has exited normally.
776 message = ProcessMessage::Exit(pid, status);
777 break;
778
779 case SIGTRAP:
780 // Specially handle SIGTRAP and form the appropriate message.
781 message = MonitorSIGTRAP(monitor, pid);
782 break;
783
784 default:
785 // For all other signals simply notify the process instance. Note that
786 // the process exit status is set when the signal resulted in
787 // termination.
788 //
789 // FIXME: We need a specialized message to inform the process instance
790 // about "crashes".
791 if (status)
792 message = ProcessMessage::Exit(pid, status);
793 else
794 message = ProcessMessage::Signal(pid, signal);
795 }
796
797 process->SendMessage(message);
798 bool stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
799 return stop_monitoring;
800}
801
802ProcessMessage
803ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor, lldb::pid_t pid)
804{
805 siginfo_t info;
806 ProcessMessage message;
807 bool status;
808
809 status = monitor->GetSignalInfo(pid, &info);
810 assert(status && "GetSignalInfo failed!");
811
812 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
813
814 switch (info.si_code)
815 {
816 default:
817 assert(false && "Unexpected SIGTRAP code!");
818 break;
819
820 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
821 {
822 // The inferior process is about to exit. Maintain the process in a
823 // state of "limbo" until we are explicitly commanded to detach,
824 // destroy, resume, etc.
825 unsigned long data = 0;
826 if (!monitor->GetEventMessage(pid, &data))
827 data = -1;
828 message = ProcessMessage::Exit(pid, (data >> 8));
829 break;
830 }
831
832 case 0:
833 case TRAP_TRACE:
834 message = ProcessMessage::Trace(pid);
835 break;
836
837 case SI_KERNEL:
838 case TRAP_BRKPT:
839 message = ProcessMessage::Break(pid);
840 break;
841 }
842
843 return message;
844}
845
846void
Stephen Wilson570243b2011-01-19 01:37:06 +0000847ProcessMonitor::ServeOperation(LaunchArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000848{
849 int status;
850 pollfd fdset;
Stephen Wilson570243b2011-01-19 01:37:06 +0000851 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000852
853 fdset.fd = monitor->m_server_fd;
854 fdset.events = POLLIN | POLLPRI;
855 fdset.revents = 0;
856
Stephen Wilson570243b2011-01-19 01:37:06 +0000857 // We are finised with the arguments and are ready to go. Sync with the
858 // parent thread and start serving operations on the inferior.
859 sem_post(&args->m_semaphore);
860
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000861 for (;;)
862 {
863 if ((status = poll(&fdset, 1, -1)) < 0)
864 {
865 switch (errno)
866 {
867 default:
868 assert(false && "Unexpected poll() failure!");
869 continue;
870
871 case EINTR: continue; // Just poll again.
872 case EBADF: return; // Connection terminated.
873 }
874 }
875
876 assert(status == 1 && "Too many descriptors!");
877
878 if (fdset.revents & POLLIN)
879 {
880 Operation *op = NULL;
881
882 READ_AGAIN:
883 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
884 {
885 // There is only one acceptable failure.
886 assert(errno == EINTR);
887 goto READ_AGAIN;
888 }
889
890 assert(status == sizeof(op));
891 op->Execute(monitor);
892 write(fdset.fd, &op, sizeof(op));
893 }
894 }
895}
896
897void
898ProcessMonitor::DoOperation(Operation *op)
899{
900 int status;
901 Operation *ack = NULL;
902 Mutex::Locker lock(m_server_mutex);
903
904 // FIXME: Do proper error checking here.
905 write(m_client_fd, &op, sizeof(op));
906
907READ_AGAIN:
908 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
909 {
910 // If interrupted by a signal handler try again. Otherwise the monitor
911 // thread probably died and we have a stale file descriptor -- abort the
912 // operation.
913 if (errno == EINTR)
914 goto READ_AGAIN;
915 return;
916 }
917
918 assert(status == sizeof(ack));
919 assert(ack == op && "Invalid monitor thread response!");
920}
921
922size_t
923ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
924 Error &error)
925{
926 size_t result;
927 ReadOperation op(vm_addr, buf, size, error, result);
928 DoOperation(&op);
929 return result;
930}
931
932size_t
933ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
934 lldb_private::Error &error)
935{
936 size_t result;
937 WriteOperation op(vm_addr, buf, size, error, result);
938 DoOperation(&op);
939 return result;
940}
941
942bool
943ProcessMonitor::ReadRegisterValue(unsigned offset, Scalar &value)
944{
945 bool result;
946 ReadRegOperation op(offset, value, result);
947 DoOperation(&op);
948 return result;
949}
950
951bool
952ProcessMonitor::WriteRegisterValue(unsigned offset, const Scalar &value)
953{
954 bool result;
955 WriteRegOperation op(offset, value, result);
956 DoOperation(&op);
957 return result;
958}
959
960bool
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000961ProcessMonitor::ReadGPR(void *buf)
962{
963 bool result;
964 ReadGPROperation op(buf, result);
965 DoOperation(&op);
966 return result;
967}
968
969bool
970ProcessMonitor::ReadFPR(void *buf)
971{
972 bool result;
973 ReadFPROperation op(buf, result);
974 DoOperation(&op);
975 return result;
976}
977
978bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000979ProcessMonitor::Resume(lldb::tid_t tid)
980{
981 bool result;
982 ResumeOperation op(tid, result);
983 DoOperation(&op);
984 return result;
985}
986
987bool
988ProcessMonitor::SingleStep(lldb::tid_t tid)
989{
990 bool result;
991 SingleStepOperation op(tid, result);
992 DoOperation(&op);
993 return result;
994}
995
996bool
997ProcessMonitor::BringProcessIntoLimbo()
998{
999 bool result;
1000 KillOperation op(result);
1001 DoOperation(&op);
1002 return result;
1003}
1004
1005bool
1006ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo)
1007{
1008 bool result;
1009 SiginfoOperation op(tid, siginfo, result);
1010 DoOperation(&op);
1011 return result;
1012}
1013
1014bool
1015ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1016{
1017 bool result;
1018 EventMessageOperation op(tid, message, result);
1019 DoOperation(&op);
1020 return result;
1021}
1022
1023bool
1024ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1025{
1026 int target_fd = open(path, flags);
1027
1028 if (target_fd == -1)
1029 return false;
1030
1031 return (dup2(fd, target_fd) == -1) ? false : true;
1032}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001033
1034void
1035ProcessMonitor::StopMonitoringChildProcess()
1036{
1037 lldb::thread_result_t thread_result;
1038
Stephen Wilsond4182f42011-02-09 20:10:35 +00001039 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001040 {
1041 Host::ThreadCancel(m_monitor_thread, NULL);
1042 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1043 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1044 }
1045}