blob: 5bad483d91e28ae300bd7a27dc5fff7374d75b8b [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"
Johnny Chen13e8e1c2011-05-13 21:29:50 +000023#include "lldb/Core/RegisterValue.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000024#include "lldb/Core/Scalar.h"
25#include "lldb/Host/Host.h"
26#include "lldb/Target/Thread.h"
27#include "lldb/Target/RegisterContext.h"
28#include "lldb/Utility/PseudoTerminal.h"
29
30#include "LinuxThread.h"
31#include "ProcessLinux.h"
32#include "ProcessMonitor.h"
33
34
35using namespace lldb_private;
36
37//------------------------------------------------------------------------------
38// Static implementations of ProcessMonitor::ReadMemory and
39// ProcessMonitor::WriteMemory. This enables mutual recursion between these
40// functions without needed to go thru the thread funnel.
41
42static size_t
43DoReadMemory(lldb::pid_t pid, unsigned word_size,
44 lldb::addr_t vm_addr, void *buf, size_t size, Error &error)
45{
46 unsigned char *dst = static_cast<unsigned char*>(buf);
47 size_t bytes_read;
48 size_t remainder;
49 long data;
50
51 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
52 {
53 errno = 0;
54 data = ptrace(PTRACE_PEEKDATA, pid, vm_addr, NULL);
55
56 if (data == -1L && errno)
57 {
58 error.SetErrorToErrno();
59 return bytes_read;
60 }
61
62 remainder = size - bytes_read;
63 remainder = remainder > word_size ? word_size : remainder;
64 for (unsigned i = 0; i < remainder; ++i)
65 dst[i] = ((data >> i*8) & 0xFF);
66 vm_addr += word_size;
67 dst += word_size;
68 }
69
70 return bytes_read;
71}
72
73static size_t
74DoWriteMemory(lldb::pid_t pid, unsigned word_size,
75 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
76{
77 const unsigned char *src = static_cast<const unsigned char*>(buf);
78 size_t bytes_written = 0;
79 size_t remainder;
80
81 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
82 {
83 remainder = size - bytes_written;
84 remainder = remainder > word_size ? word_size : remainder;
85
86 if (remainder == word_size)
87 {
88 unsigned long data = 0;
89 for (unsigned i = 0; i < word_size; ++i)
90 data |= (unsigned long)src[i] << i*8;
91
92 if (ptrace(PTRACE_POKEDATA, pid, vm_addr, data))
93 {
94 error.SetErrorToErrno();
95 return bytes_written;
96 }
97 }
98 else
99 {
100 unsigned char buff[8];
101 if (DoReadMemory(pid, word_size, vm_addr,
102 buff, word_size, error) != word_size)
103 return bytes_written;
104
105 memcpy(buff, src, remainder);
106
107 if (DoWriteMemory(pid, word_size, vm_addr,
108 buff, word_size, error) != word_size)
109 return bytes_written;
110 }
111
112 vm_addr += word_size;
113 src += word_size;
114 }
115 return bytes_written;
116}
117
Stephen Wilson26977162011-03-23 02:14:42 +0000118// Simple helper function to ensure flags are enabled on the given file
119// descriptor.
120static bool
121EnsureFDFlags(int fd, int flags, Error &error)
122{
123 int status;
124
125 if ((status = fcntl(fd, F_GETFL)) == -1)
126 {
127 error.SetErrorToErrno();
128 return false;
129 }
130
131 if (fcntl(fd, F_SETFL, status | flags) == -1)
132 {
133 error.SetErrorToErrno();
134 return false;
135 }
136
137 return true;
138}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000139
140//------------------------------------------------------------------------------
141/// @class Operation
142/// @brief Represents a ProcessMonitor operation.
143///
144/// Under Linux, it is not possible to ptrace() from any other thread but the
145/// one that spawned or attached to the process from the start. Therefore, when
146/// a ProcessMonitor is asked to deliver or change the state of an inferior
147/// process the operation must be "funneled" to a specific thread to perform the
148/// task. The Operation class provides an abstract base for all services the
149/// ProcessMonitor must perform via the single virtual function Execute, thus
150/// encapsulating the code that needs to run in the privileged context.
151class Operation
152{
153public:
154 virtual void Execute(ProcessMonitor *monitor) = 0;
155};
156
157//------------------------------------------------------------------------------
158/// @class ReadOperation
159/// @brief Implements ProcessMonitor::ReadMemory.
160class ReadOperation : public Operation
161{
162public:
163 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
164 Error &error, size_t &result)
165 : m_addr(addr), m_buff(buff), m_size(size),
166 m_error(error), m_result(result)
167 { }
168
169 void Execute(ProcessMonitor *monitor);
170
171private:
172 lldb::addr_t m_addr;
173 void *m_buff;
174 size_t m_size;
175 Error &m_error;
176 size_t &m_result;
177};
178
179void
180ReadOperation::Execute(ProcessMonitor *monitor)
181{
182 const unsigned word_size = monitor->GetProcess().GetAddressByteSize();
183 lldb::pid_t pid = monitor->GetPID();
184
185 m_result = DoReadMemory(pid, word_size, m_addr, m_buff, m_size, m_error);
186}
187
188//------------------------------------------------------------------------------
189/// @class ReadOperation
190/// @brief Implements ProcessMonitor::WriteMemory.
191class WriteOperation : public Operation
192{
193public:
194 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
195 Error &error, size_t &result)
196 : m_addr(addr), m_buff(buff), m_size(size),
197 m_error(error), m_result(result)
198 { }
199
200 void Execute(ProcessMonitor *monitor);
201
202private:
203 lldb::addr_t m_addr;
204 const void *m_buff;
205 size_t m_size;
206 Error &m_error;
207 size_t &m_result;
208};
209
210void
211WriteOperation::Execute(ProcessMonitor *monitor)
212{
213 const unsigned word_size = monitor->GetProcess().GetAddressByteSize();
214 lldb::pid_t pid = monitor->GetPID();
215
216 m_result = DoWriteMemory(pid, word_size, m_addr, m_buff, m_size, m_error);
217}
218
219//------------------------------------------------------------------------------
220/// @class ReadRegOperation
221/// @brief Implements ProcessMonitor::ReadRegisterValue.
222class ReadRegOperation : public Operation
223{
224public:
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000225 ReadRegOperation(unsigned offset, RegisterValue &value, bool &result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000226 : m_offset(offset), m_value(value), m_result(result)
227 { }
228
229 void Execute(ProcessMonitor *monitor);
230
231private:
232 unsigned m_offset;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000233 RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000234 bool &m_result;
235};
236
237void
238ReadRegOperation::Execute(ProcessMonitor *monitor)
239{
240 lldb::pid_t pid = monitor->GetPID();
241
242 // Set errno to zero so that we can detect a failed peek.
243 errno = 0;
244 unsigned long data = ptrace(PTRACE_PEEKUSER, pid, m_offset, NULL);
245
246 if (data == -1UL && errno)
247 m_result = false;
248 else
249 {
250 m_value = data;
251 m_result = true;
252 }
253}
254
255//------------------------------------------------------------------------------
256/// @class WriteRegOperation
257/// @brief Implements ProcessMonitor::WriteRegisterValue.
258class WriteRegOperation : public Operation
259{
260public:
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000261 WriteRegOperation(unsigned offset, const RegisterValue &value, bool &result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000262 : m_offset(offset), m_value(value), m_result(result)
263 { }
264
265 void Execute(ProcessMonitor *monitor);
266
267private:
268 unsigned m_offset;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000269 const RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000270 bool &m_result;
271};
272
273void
274WriteRegOperation::Execute(ProcessMonitor *monitor)
275{
276 lldb::pid_t pid = monitor->GetPID();
277
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000278 if (ptrace(PTRACE_POKEUSER, pid, m_offset, m_value.GetAsUInt64()))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000279 m_result = false;
280 else
281 m_result = true;
282}
283
284//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000285/// @class ReadGPROperation
286/// @brief Implements ProcessMonitor::ReadGPR.
287class ReadGPROperation : public Operation
288{
289public:
290 ReadGPROperation(void *buf, bool &result)
291 : m_buf(buf), m_result(result)
292 { }
293
294 void Execute(ProcessMonitor *monitor);
295
296private:
297 void *m_buf;
298 bool &m_result;
299};
300
301void
302ReadGPROperation::Execute(ProcessMonitor *monitor)
303{
304 if (ptrace(PTRACE_GETREGS, monitor->GetPID(), NULL, m_buf) < 0)
305 m_result = false;
306 else
307 m_result = true;
308}
309
310//------------------------------------------------------------------------------
311/// @class ReadFPROperation
312/// @brief Implements ProcessMonitor::ReadFPR.
313class ReadFPROperation : public Operation
314{
315public:
316 ReadFPROperation(void *buf, bool &result)
317 : m_buf(buf), m_result(result)
318 { }
319
320 void Execute(ProcessMonitor *monitor);
321
322private:
323 void *m_buf;
324 bool &m_result;
325};
326
327void
328ReadFPROperation::Execute(ProcessMonitor *monitor)
329{
330 if (ptrace(PTRACE_GETFPREGS, monitor->GetPID(), NULL, m_buf) < 0)
331 m_result = false;
332 else
333 m_result = true;
334}
335
336//------------------------------------------------------------------------------
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000337/// @class WriteGPROperation
338/// @brief Implements ProcessMonitor::WriteGPR.
339class WriteGPROperation : public Operation
340{
341public:
342 WriteGPROperation(void *buf, bool &result)
343 : m_buf(buf), m_result(result)
344 { }
345
346 void Execute(ProcessMonitor *monitor);
347
348private:
349 void *m_buf;
350 bool &m_result;
351};
352
353void
354WriteGPROperation::Execute(ProcessMonitor *monitor)
355{
356 if (ptrace(PTRACE_SETREGS, monitor->GetPID(), NULL, m_buf) < 0)
357 m_result = false;
358 else
359 m_result = true;
360}
361
362//------------------------------------------------------------------------------
363/// @class WriteFPROperation
364/// @brief Implements ProcessMonitor::WriteFPR.
365class WriteFPROperation : public Operation
366{
367public:
368 WriteFPROperation(void *buf, bool &result)
369 : m_buf(buf), m_result(result)
370 { }
371
372 void Execute(ProcessMonitor *monitor);
373
374private:
375 void *m_buf;
376 bool &m_result;
377};
378
379void
380WriteFPROperation::Execute(ProcessMonitor *monitor)
381{
382 if (ptrace(PTRACE_SETFPREGS, monitor->GetPID(), NULL, m_buf) < 0)
383 m_result = false;
384 else
385 m_result = true;
386}
387
388//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000389/// @class ResumeOperation
390/// @brief Implements ProcessMonitor::Resume.
391class ResumeOperation : public Operation
392{
393public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000394 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
395 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000396
397 void Execute(ProcessMonitor *monitor);
398
399private:
400 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000401 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000402 bool &m_result;
403};
404
405void
406ResumeOperation::Execute(ProcessMonitor *monitor)
407{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000408 int data = 0;
409
410 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
411 data = m_signo;
412
413 if (ptrace(PTRACE_CONT, m_tid, NULL, data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000414 m_result = false;
415 else
416 m_result = true;
417}
418
419//------------------------------------------------------------------------------
420/// @class ResumeOperation
421/// @brief Implements ProcessMonitor::SingleStep.
422class SingleStepOperation : public Operation
423{
424public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000425 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
426 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000427
428 void Execute(ProcessMonitor *monitor);
429
430private:
431 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000432 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000433 bool &m_result;
434};
435
436void
437SingleStepOperation::Execute(ProcessMonitor *monitor)
438{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000439 int data = 0;
440
441 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
442 data = m_signo;
443
444 if (ptrace(PTRACE_SINGLESTEP, m_tid, NULL, data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000445 m_result = false;
446 else
447 m_result = true;
448}
449
450//------------------------------------------------------------------------------
451/// @class SiginfoOperation
452/// @brief Implements ProcessMonitor::GetSignalInfo.
453class SiginfoOperation : public Operation
454{
455public:
456 SiginfoOperation(lldb::tid_t tid, void *info, bool &result)
457 : m_tid(tid), m_info(info), m_result(result) { }
458
459 void Execute(ProcessMonitor *monitor);
460
461private:
462 lldb::tid_t m_tid;
463 void *m_info;
464 bool &m_result;
465};
466
467void
468SiginfoOperation::Execute(ProcessMonitor *monitor)
469{
470 if (ptrace(PTRACE_GETSIGINFO, m_tid, NULL, m_info))
471 m_result = false;
472 else
473 m_result = true;
474}
475
476//------------------------------------------------------------------------------
477/// @class EventMessageOperation
478/// @brief Implements ProcessMonitor::GetEventMessage.
479class EventMessageOperation : public Operation
480{
481public:
482 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
483 : m_tid(tid), m_message(message), m_result(result) { }
484
485 void Execute(ProcessMonitor *monitor);
486
487private:
488 lldb::tid_t m_tid;
489 unsigned long *m_message;
490 bool &m_result;
491};
492
493void
494EventMessageOperation::Execute(ProcessMonitor *monitor)
495{
496 if (ptrace(PTRACE_GETEVENTMSG, m_tid, NULL, m_message))
497 m_result = false;
498 else
499 m_result = true;
500}
501
502//------------------------------------------------------------------------------
503/// @class KillOperation
504/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
505class KillOperation : public Operation
506{
507public:
508 KillOperation(bool &result) : m_result(result) { }
509
510 void Execute(ProcessMonitor *monitor);
511
512private:
513 bool &m_result;
514};
515
516void
517KillOperation::Execute(ProcessMonitor *monitor)
518{
519 lldb::pid_t pid = monitor->GetPID();
520
521 if (ptrace(PTRACE_KILL, pid, NULL, NULL))
522 m_result = false;
523 else
524 m_result = true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000525}
526
527ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
528 lldb_private::Module *module,
529 char const **argv,
530 char const **envp,
531 const char *stdin_path,
532 const char *stdout_path,
533 const char *stderr_path)
534 : m_monitor(monitor),
535 m_module(module),
536 m_argv(argv),
537 m_envp(envp),
538 m_stdin_path(stdin_path),
539 m_stdout_path(stdout_path),
540 m_stderr_path(stderr_path)
541{
542 sem_init(&m_semaphore, 0, 0);
543}
544
545ProcessMonitor::LaunchArgs::~LaunchArgs()
546{
547 sem_destroy(&m_semaphore);
548}
549
550//------------------------------------------------------------------------------
551/// The basic design of the ProcessMonitor is built around two threads.
552///
553/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
554/// for changes in the debugee state. When a change is detected a
555/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
556/// "drives" state changes in the debugger.
557///
558/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000559/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000560/// operations such as register reads/writes, stepping, etc. See the comments
561/// on the Operation class for more info as to why this is needed.
562ProcessMonitor::ProcessMonitor(ProcessLinux *process,
563 Module *module,
564 const char *argv[],
565 const char *envp[],
566 const char *stdin_path,
567 const char *stdout_path,
568 const char *stderr_path,
569 lldb_private::Error &error)
570 : m_process(process),
571 m_operation_thread(LLDB_INVALID_HOST_THREAD),
572 m_pid(LLDB_INVALID_PROCESS_ID),
573 m_terminal_fd(-1),
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000574 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000575 m_client_fd(-1),
576 m_server_fd(-1)
577{
Stephen Wilson57740ec2011-01-15 00:12:41 +0000578 std::auto_ptr<LaunchArgs> args;
579
580 args.reset(new LaunchArgs(this, module, argv, envp,
581 stdin_path, stdout_path, stderr_path));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000582
583 // Server/client descriptors.
584 if (!EnableIPC())
585 {
586 error.SetErrorToGenericError();
587 error.SetErrorString("Monitor failed to initialize.");
588 }
589
Stephen Wilson57740ec2011-01-15 00:12:41 +0000590 StartOperationThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000591 if (!error.Success())
592 return;
593
594WAIT_AGAIN:
595 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000596 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000597 {
598 if (errno == EINTR)
599 goto WAIT_AGAIN;
600 else
601 {
602 error.SetErrorToErrno();
603 return;
604 }
605 }
606
607 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000608 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000609 {
610 StopOperationThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000611 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000612 return;
613 }
614
615 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000616 m_monitor_thread = Host::StartMonitoringChildProcess(
617 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Stephen Wilsond4182f42011-02-09 20:10:35 +0000618 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000619 {
620 error.SetErrorToGenericError();
621 error.SetErrorString("Process launch failed.");
622 return;
623 }
624}
625
626ProcessMonitor::~ProcessMonitor()
627{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000628 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000629}
630
631//------------------------------------------------------------------------------
632// Thread setup and tear down.
633void
634ProcessMonitor::StartOperationThread(LaunchArgs *args, Error &error)
635{
636 static const char *g_thread_name = "lldb.process.linux.operation";
637
Stephen Wilsond4182f42011-02-09 20:10:35 +0000638 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000639 return;
640
641 m_operation_thread =
642 Host::ThreadCreate(g_thread_name, OperationThread, args, &error);
643}
644
645void
646ProcessMonitor::StopOperationThread()
647{
648 lldb::thread_result_t result;
649
Stephen Wilsond4182f42011-02-09 20:10:35 +0000650 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000651 return;
652
653 Host::ThreadCancel(m_operation_thread, NULL);
654 Host::ThreadJoin(m_operation_thread, &result, NULL);
655}
656
657void *
658ProcessMonitor::OperationThread(void *arg)
659{
660 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
661
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +0000662 if (!Launch(args)) {
663 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000664 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +0000665 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000666
Stephen Wilson570243b2011-01-19 01:37:06 +0000667 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000668 return NULL;
669}
670
671bool
672ProcessMonitor::Launch(LaunchArgs *args)
673{
674 ProcessMonitor *monitor = args->m_monitor;
675 ProcessLinux &process = monitor->GetProcess();
676 const char **argv = args->m_argv;
677 const char **envp = args->m_envp;
678 const char *stdin_path = args->m_stdin_path;
679 const char *stdout_path = args->m_stdout_path;
680 const char *stderr_path = args->m_stderr_path;
681
682 lldb_utility::PseudoTerminal terminal;
683 const size_t err_len = 1024;
684 char err_str[err_len];
685 lldb::pid_t pid;
686
687 lldb::ThreadSP inferior;
688
Stephen Wilson57740ec2011-01-15 00:12:41 +0000689 // Propagate the environment if one is not supplied.
690 if (envp == NULL || envp[0] == NULL)
691 envp = const_cast<const char **>(environ);
692
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000693 // Pseudo terminal setup.
694 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
695 {
696 args->m_error.SetErrorToGenericError();
697 args->m_error.SetErrorString("Could not open controlling TTY.");
698 goto FINISH;
699 }
700
701 if ((pid = terminal.Fork(err_str, err_len)) < 0)
702 {
703 args->m_error.SetErrorToGenericError();
704 args->m_error.SetErrorString("Process fork failed.");
705 goto FINISH;
706 }
707
708 // Child process.
709 if (pid == 0)
710 {
711 // Trace this process.
712 ptrace(PTRACE_TRACEME, 0, NULL, NULL);
713
714 // Do not inherit setgid powers.
715 setgid(getgid());
716
717 // Let us have our own process group.
718 setpgid(0, 0);
719
Greg Clayton710dd5a2011-01-08 20:28:42 +0000720 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000721 //
722 // FIXME: If two or more of the paths are the same we needlessly open
723 // the same file multiple times.
724 if (stdin_path != NULL && stdin_path[0])
725 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY | O_CREAT))
726 exit(1);
727
728 if (stdout_path != NULL && stdout_path[0])
729 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
730 exit(1);
731
732 if (stderr_path != NULL && stderr_path[0])
733 if (!DupDescriptor(stderr_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
734 exit(1);
735
736 // Execute. We should never return.
737 execve(argv[0],
738 const_cast<char *const *>(argv),
739 const_cast<char *const *>(envp));
740 exit(-1);
741 }
742
743 // Wait for the child process to to trap on its call to execve.
744 int status;
745 if ((status = waitpid(pid, NULL, 0)) < 0)
746 {
747 // execve likely failed for some reason.
748 args->m_error.SetErrorToErrno();
749 goto FINISH;
750 }
751 assert(status == pid && "Could not sync with inferior process.");
752
753 // Have the child raise an event on exit. This is used to keep the child in
754 // limbo until it is destroyed.
755 if (ptrace(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0)
756 {
757 args->m_error.SetErrorToErrno();
758 goto FINISH;
759 }
760
761 // Release the master terminal descriptor and pass it off to the
762 // ProcessMonitor instance. Similarly stash the inferior pid.
763 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
764 monitor->m_pid = pid;
765
Stephen Wilson26977162011-03-23 02:14:42 +0000766 // Set the terminal fd to be in non blocking mode (it simplifies the
767 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
768 // descriptor to read from).
769 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
770 goto FINISH;
771
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000772 // Update the process thread list with this new thread and mark it as
773 // current.
774 inferior.reset(new LinuxThread(process, pid));
775 process.GetThreadList().AddThread(inferior);
Stephen Wilson5a8feea2011-01-04 21:39:27 +0000776 process.GetThreadList().SetSelectedThreadByID(pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000777
778 // Let our process instance know the thread has stopped.
779 process.SendMessage(ProcessMessage::Trace(pid));
780
781FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000782 return args->m_error.Success();
783}
784
785bool
786ProcessMonitor::EnableIPC()
787{
788 int fd[2];
789
790 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
791 return false;
792
793 m_client_fd = fd[0];
794 m_server_fd = fd[1];
795 return true;
796}
797
798bool
799ProcessMonitor::MonitorCallback(void *callback_baton,
800 lldb::pid_t pid,
801 int signal,
802 int status)
803{
804 ProcessMessage message;
805 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
806 ProcessLinux *process = monitor->m_process;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000807 bool stop_monitoring;
808 siginfo_t info;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000809
Stephen Wilson84ffe702011-03-30 15:55:52 +0000810 if (!monitor->GetSignalInfo(pid, &info))
811 stop_monitoring = true; // pid is gone. Bail.
812 else {
813 switch (info.si_signo)
814 {
815 case SIGTRAP:
816 message = MonitorSIGTRAP(monitor, &info, pid);
817 break;
818
819 default:
820 message = MonitorSignal(monitor, &info, pid);
821 break;
822 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000823
Stephen Wilson84ffe702011-03-30 15:55:52 +0000824 process->SendMessage(message);
825 stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000826 }
827
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000828 return stop_monitoring;
829}
830
831ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +0000832ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
833 const struct siginfo *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000834{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000835 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000836
Stephen Wilson84ffe702011-03-30 15:55:52 +0000837 assert(info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000838
Stephen Wilson84ffe702011-03-30 15:55:52 +0000839 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000840 {
841 default:
842 assert(false && "Unexpected SIGTRAP code!");
843 break;
844
845 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
846 {
847 // The inferior process is about to exit. Maintain the process in a
848 // state of "limbo" until we are explicitly commanded to detach,
849 // destroy, resume, etc.
850 unsigned long data = 0;
851 if (!monitor->GetEventMessage(pid, &data))
852 data = -1;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000853 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000854 break;
855 }
856
857 case 0:
858 case TRAP_TRACE:
859 message = ProcessMessage::Trace(pid);
860 break;
861
862 case SI_KERNEL:
863 case TRAP_BRKPT:
864 message = ProcessMessage::Break(pid);
865 break;
866 }
867
868 return message;
869}
870
Stephen Wilson84ffe702011-03-30 15:55:52 +0000871ProcessMessage
872ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
873 const struct siginfo *info, lldb::pid_t pid)
874{
875 ProcessMessage message;
876 int signo = info->si_signo;
877
878 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
879 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
880 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
881 //
882 // IOW, user generated signals never generate what we consider to be a
883 // "crash".
884 //
885 // Similarly, ACK signals generated by this monitor.
886 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
887 {
888 if (info->si_pid == getpid())
889 return ProcessMessage::SignalDelivered(pid, signo);
890 else
891 return ProcessMessage::Signal(pid, signo);
892 }
893
894 if (signo == SIGSEGV) {
895 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
896 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
897 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
898 }
899
900 if (signo == SIGILL) {
901 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
902 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
903 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
904 }
905
906 if (signo == SIGFPE) {
907 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
908 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
909 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
910 }
911
912 if (signo == SIGBUS) {
913 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
914 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
915 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
916 }
917
918 // Everything else is "normal" and does not require any special action on
919 // our part.
920 return ProcessMessage::Signal(pid, signo);
921}
922
923ProcessMessage::CrashReason
924ProcessMonitor::GetCrashReasonForSIGSEGV(const struct siginfo *info)
925{
926 ProcessMessage::CrashReason reason;
927 assert(info->si_signo == SIGSEGV);
928
929 reason = ProcessMessage::eInvalidCrashReason;
930
931 switch (info->si_code)
932 {
933 default:
934 assert(false && "unexpected si_code for SIGSEGV");
935 break;
936 case SEGV_MAPERR:
937 reason = ProcessMessage::eInvalidAddress;
938 break;
939 case SEGV_ACCERR:
940 reason = ProcessMessage::ePrivilegedAddress;
941 break;
942 }
943
944 return reason;
945}
946
947ProcessMessage::CrashReason
948ProcessMonitor::GetCrashReasonForSIGILL(const struct siginfo *info)
949{
950 ProcessMessage::CrashReason reason;
951 assert(info->si_signo == SIGILL);
952
953 reason = ProcessMessage::eInvalidCrashReason;
954
955 switch (info->si_code)
956 {
957 default:
958 assert(false && "unexpected si_code for SIGILL");
959 break;
960 case ILL_ILLOPC:
961 reason = ProcessMessage::eIllegalOpcode;
962 break;
963 case ILL_ILLOPN:
964 reason = ProcessMessage::eIllegalOperand;
965 break;
966 case ILL_ILLADR:
967 reason = ProcessMessage::eIllegalAddressingMode;
968 break;
969 case ILL_ILLTRP:
970 reason = ProcessMessage::eIllegalTrap;
971 break;
972 case ILL_PRVOPC:
973 reason = ProcessMessage::ePrivilegedOpcode;
974 break;
975 case ILL_PRVREG:
976 reason = ProcessMessage::ePrivilegedRegister;
977 break;
978 case ILL_COPROC:
979 reason = ProcessMessage::eCoprocessorError;
980 break;
981 case ILL_BADSTK:
982 reason = ProcessMessage::eInternalStackError;
983 break;
984 }
985
986 return reason;
987}
988
989ProcessMessage::CrashReason
990ProcessMonitor::GetCrashReasonForSIGFPE(const struct siginfo *info)
991{
992 ProcessMessage::CrashReason reason;
993 assert(info->si_signo == SIGFPE);
994
995 reason = ProcessMessage::eInvalidCrashReason;
996
997 switch (info->si_code)
998 {
999 default:
1000 assert(false && "unexpected si_code for SIGFPE");
1001 break;
1002 case FPE_INTDIV:
1003 reason = ProcessMessage::eIntegerDivideByZero;
1004 break;
1005 case FPE_INTOVF:
1006 reason = ProcessMessage::eIntegerOverflow;
1007 break;
1008 case FPE_FLTDIV:
1009 reason = ProcessMessage::eFloatDivideByZero;
1010 break;
1011 case FPE_FLTOVF:
1012 reason = ProcessMessage::eFloatOverflow;
1013 break;
1014 case FPE_FLTUND:
1015 reason = ProcessMessage::eFloatUnderflow;
1016 break;
1017 case FPE_FLTRES:
1018 reason = ProcessMessage::eFloatInexactResult;
1019 break;
1020 case FPE_FLTINV:
1021 reason = ProcessMessage::eFloatInvalidOperation;
1022 break;
1023 case FPE_FLTSUB:
1024 reason = ProcessMessage::eFloatSubscriptRange;
1025 break;
1026 }
1027
1028 return reason;
1029}
1030
1031ProcessMessage::CrashReason
1032ProcessMonitor::GetCrashReasonForSIGBUS(const struct siginfo *info)
1033{
1034 ProcessMessage::CrashReason reason;
1035 assert(info->si_signo == SIGBUS);
1036
1037 reason = ProcessMessage::eInvalidCrashReason;
1038
1039 switch (info->si_code)
1040 {
1041 default:
1042 assert(false && "unexpected si_code for SIGBUS");
1043 break;
1044 case BUS_ADRALN:
1045 reason = ProcessMessage::eIllegalAlignment;
1046 break;
1047 case BUS_ADRERR:
1048 reason = ProcessMessage::eIllegalAddress;
1049 break;
1050 case BUS_OBJERR:
1051 reason = ProcessMessage::eHardwareError;
1052 break;
1053 }
1054
1055 return reason;
1056}
1057
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001058void
Stephen Wilson570243b2011-01-19 01:37:06 +00001059ProcessMonitor::ServeOperation(LaunchArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001060{
1061 int status;
1062 pollfd fdset;
Stephen Wilson570243b2011-01-19 01:37:06 +00001063 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001064
1065 fdset.fd = monitor->m_server_fd;
1066 fdset.events = POLLIN | POLLPRI;
1067 fdset.revents = 0;
1068
Stephen Wilson570243b2011-01-19 01:37:06 +00001069 // We are finised with the arguments and are ready to go. Sync with the
1070 // parent thread and start serving operations on the inferior.
1071 sem_post(&args->m_semaphore);
1072
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001073 for (;;)
1074 {
1075 if ((status = poll(&fdset, 1, -1)) < 0)
1076 {
1077 switch (errno)
1078 {
1079 default:
1080 assert(false && "Unexpected poll() failure!");
1081 continue;
1082
1083 case EINTR: continue; // Just poll again.
1084 case EBADF: return; // Connection terminated.
1085 }
1086 }
1087
1088 assert(status == 1 && "Too many descriptors!");
1089
1090 if (fdset.revents & POLLIN)
1091 {
1092 Operation *op = NULL;
1093
1094 READ_AGAIN:
1095 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1096 {
1097 // There is only one acceptable failure.
1098 assert(errno == EINTR);
1099 goto READ_AGAIN;
1100 }
1101
1102 assert(status == sizeof(op));
1103 op->Execute(monitor);
1104 write(fdset.fd, &op, sizeof(op));
1105 }
1106 }
1107}
1108
1109void
1110ProcessMonitor::DoOperation(Operation *op)
1111{
1112 int status;
1113 Operation *ack = NULL;
1114 Mutex::Locker lock(m_server_mutex);
1115
1116 // FIXME: Do proper error checking here.
1117 write(m_client_fd, &op, sizeof(op));
1118
1119READ_AGAIN:
1120 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1121 {
1122 // If interrupted by a signal handler try again. Otherwise the monitor
1123 // thread probably died and we have a stale file descriptor -- abort the
1124 // operation.
1125 if (errno == EINTR)
1126 goto READ_AGAIN;
1127 return;
1128 }
1129
1130 assert(status == sizeof(ack));
1131 assert(ack == op && "Invalid monitor thread response!");
1132}
1133
1134size_t
1135ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1136 Error &error)
1137{
1138 size_t result;
1139 ReadOperation op(vm_addr, buf, size, error, result);
1140 DoOperation(&op);
1141 return result;
1142}
1143
1144size_t
1145ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1146 lldb_private::Error &error)
1147{
1148 size_t result;
1149 WriteOperation op(vm_addr, buf, size, error, result);
1150 DoOperation(&op);
1151 return result;
1152}
1153
1154bool
Johnny Chen13e8e1c2011-05-13 21:29:50 +00001155ProcessMonitor::ReadRegisterValue(unsigned offset, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001156{
1157 bool result;
1158 ReadRegOperation op(offset, value, result);
1159 DoOperation(&op);
1160 return result;
1161}
1162
1163bool
Johnny Chen13e8e1c2011-05-13 21:29:50 +00001164ProcessMonitor::WriteRegisterValue(unsigned offset, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001165{
1166 bool result;
1167 WriteRegOperation op(offset, value, result);
1168 DoOperation(&op);
1169 return result;
1170}
1171
1172bool
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001173ProcessMonitor::ReadGPR(void *buf)
1174{
1175 bool result;
1176 ReadGPROperation op(buf, result);
1177 DoOperation(&op);
1178 return result;
1179}
1180
1181bool
1182ProcessMonitor::ReadFPR(void *buf)
1183{
1184 bool result;
1185 ReadFPROperation op(buf, result);
1186 DoOperation(&op);
1187 return result;
1188}
1189
1190bool
Peter Collingbourne10bc0102011-06-03 20:41:02 +00001191ProcessMonitor::WriteGPR(void *buf)
1192{
1193 bool result;
1194 WriteGPROperation op(buf, result);
1195 DoOperation(&op);
1196 return result;
1197}
1198
1199bool
1200ProcessMonitor::WriteFPR(void *buf)
1201{
1202 bool result;
1203 WriteFPROperation op(buf, result);
1204 DoOperation(&op);
1205 return result;
1206}
1207
1208bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001209ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001210{
1211 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001212 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001213 DoOperation(&op);
1214 return result;
1215}
1216
1217bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001218ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001219{
1220 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001221 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001222 DoOperation(&op);
1223 return result;
1224}
1225
1226bool
1227ProcessMonitor::BringProcessIntoLimbo()
1228{
1229 bool result;
1230 KillOperation op(result);
1231 DoOperation(&op);
1232 return result;
1233}
1234
1235bool
1236ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo)
1237{
1238 bool result;
1239 SiginfoOperation op(tid, siginfo, result);
1240 DoOperation(&op);
1241 return result;
1242}
1243
1244bool
1245ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1246{
1247 bool result;
1248 EventMessageOperation op(tid, message, result);
1249 DoOperation(&op);
1250 return result;
1251}
1252
1253bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001254ProcessMonitor::Detach()
1255{
1256 bool result;
1257 KillOperation op(result);
1258 DoOperation(&op);
1259 StopMonitor();
1260 return result;
1261}
1262
1263bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001264ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1265{
1266 int target_fd = open(path, flags);
1267
1268 if (target_fd == -1)
1269 return false;
1270
1271 return (dup2(fd, target_fd) == -1) ? false : true;
1272}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001273
1274void
1275ProcessMonitor::StopMonitoringChildProcess()
1276{
1277 lldb::thread_result_t thread_result;
1278
Stephen Wilsond4182f42011-02-09 20:10:35 +00001279 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001280 {
1281 Host::ThreadCancel(m_monitor_thread, NULL);
1282 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1283 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1284 }
1285}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001286
1287void
1288ProcessMonitor::StopMonitor()
1289{
1290 StopMonitoringChildProcess();
1291 StopOperationThread();
1292 CloseFD(m_terminal_fd);
1293 CloseFD(m_client_fd);
1294 CloseFD(m_server_fd);
1295}
1296
1297void
1298ProcessMonitor::CloseFD(int &fd)
1299{
1300 if (fd != -1)
1301 {
1302 close(fd);
1303 fd = -1;
1304 }
1305}