blob: 48a57a8b01044b5068bfdafdc3a3180fd8315931 [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:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000341 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
342 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000343
344 void Execute(ProcessMonitor *monitor);
345
346private:
347 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000348 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000349 bool &m_result;
350};
351
352void
353ResumeOperation::Execute(ProcessMonitor *monitor)
354{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000355 int data = 0;
356
357 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
358 data = m_signo;
359
360 if (ptrace(PTRACE_CONT, m_tid, NULL, data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000361 m_result = false;
362 else
363 m_result = true;
364}
365
366//------------------------------------------------------------------------------
367/// @class ResumeOperation
368/// @brief Implements ProcessMonitor::SingleStep.
369class SingleStepOperation : public Operation
370{
371public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000372 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
373 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000374
375 void Execute(ProcessMonitor *monitor);
376
377private:
378 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000379 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000380 bool &m_result;
381};
382
383void
384SingleStepOperation::Execute(ProcessMonitor *monitor)
385{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000386 int data = 0;
387
388 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
389 data = m_signo;
390
391 if (ptrace(PTRACE_SINGLESTEP, m_tid, NULL, data))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000392 m_result = false;
393 else
394 m_result = true;
395}
396
397//------------------------------------------------------------------------------
398/// @class SiginfoOperation
399/// @brief Implements ProcessMonitor::GetSignalInfo.
400class SiginfoOperation : public Operation
401{
402public:
403 SiginfoOperation(lldb::tid_t tid, void *info, bool &result)
404 : m_tid(tid), m_info(info), m_result(result) { }
405
406 void Execute(ProcessMonitor *monitor);
407
408private:
409 lldb::tid_t m_tid;
410 void *m_info;
411 bool &m_result;
412};
413
414void
415SiginfoOperation::Execute(ProcessMonitor *monitor)
416{
417 if (ptrace(PTRACE_GETSIGINFO, m_tid, NULL, m_info))
418 m_result = false;
419 else
420 m_result = true;
421}
422
423//------------------------------------------------------------------------------
424/// @class EventMessageOperation
425/// @brief Implements ProcessMonitor::GetEventMessage.
426class EventMessageOperation : public Operation
427{
428public:
429 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
430 : m_tid(tid), m_message(message), m_result(result) { }
431
432 void Execute(ProcessMonitor *monitor);
433
434private:
435 lldb::tid_t m_tid;
436 unsigned long *m_message;
437 bool &m_result;
438};
439
440void
441EventMessageOperation::Execute(ProcessMonitor *monitor)
442{
443 if (ptrace(PTRACE_GETEVENTMSG, m_tid, NULL, m_message))
444 m_result = false;
445 else
446 m_result = true;
447}
448
449//------------------------------------------------------------------------------
450/// @class KillOperation
451/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
452class KillOperation : public Operation
453{
454public:
455 KillOperation(bool &result) : m_result(result) { }
456
457 void Execute(ProcessMonitor *monitor);
458
459private:
460 bool &m_result;
461};
462
463void
464KillOperation::Execute(ProcessMonitor *monitor)
465{
466 lldb::pid_t pid = monitor->GetPID();
467
468 if (ptrace(PTRACE_KILL, pid, NULL, NULL))
469 m_result = false;
470 else
471 m_result = true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000472}
473
474ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
475 lldb_private::Module *module,
476 char const **argv,
477 char const **envp,
478 const char *stdin_path,
479 const char *stdout_path,
480 const char *stderr_path)
481 : m_monitor(monitor),
482 m_module(module),
483 m_argv(argv),
484 m_envp(envp),
485 m_stdin_path(stdin_path),
486 m_stdout_path(stdout_path),
487 m_stderr_path(stderr_path)
488{
489 sem_init(&m_semaphore, 0, 0);
490}
491
492ProcessMonitor::LaunchArgs::~LaunchArgs()
493{
494 sem_destroy(&m_semaphore);
495}
496
497//------------------------------------------------------------------------------
498/// The basic design of the ProcessMonitor is built around two threads.
499///
500/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
501/// for changes in the debugee state. When a change is detected a
502/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
503/// "drives" state changes in the debugger.
504///
505/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000506/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000507/// operations such as register reads/writes, stepping, etc. See the comments
508/// on the Operation class for more info as to why this is needed.
509ProcessMonitor::ProcessMonitor(ProcessLinux *process,
510 Module *module,
511 const char *argv[],
512 const char *envp[],
513 const char *stdin_path,
514 const char *stdout_path,
515 const char *stderr_path,
516 lldb_private::Error &error)
517 : m_process(process),
518 m_operation_thread(LLDB_INVALID_HOST_THREAD),
519 m_pid(LLDB_INVALID_PROCESS_ID),
520 m_terminal_fd(-1),
Stephen Wilson9212d7f2011-01-04 21:40:25 +0000521 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000522 m_client_fd(-1),
523 m_server_fd(-1)
524{
Stephen Wilson57740ec2011-01-15 00:12:41 +0000525 std::auto_ptr<LaunchArgs> args;
526
527 args.reset(new LaunchArgs(this, module, argv, envp,
528 stdin_path, stdout_path, stderr_path));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000529
530 // Server/client descriptors.
531 if (!EnableIPC())
532 {
533 error.SetErrorToGenericError();
534 error.SetErrorString("Monitor failed to initialize.");
535 }
536
Stephen Wilson57740ec2011-01-15 00:12:41 +0000537 StartOperationThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000538 if (!error.Success())
539 return;
540
541WAIT_AGAIN:
542 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000543 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000544 {
545 if (errno == EINTR)
546 goto WAIT_AGAIN;
547 else
548 {
549 error.SetErrorToErrno();
550 return;
551 }
552 }
553
554 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000555 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000556 {
557 StopOperationThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000558 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000559 return;
560 }
561
562 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000563 m_monitor_thread = Host::StartMonitoringChildProcess(
564 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Stephen Wilsond4182f42011-02-09 20:10:35 +0000565 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000566 {
567 error.SetErrorToGenericError();
568 error.SetErrorString("Process launch failed.");
569 return;
570 }
571}
572
573ProcessMonitor::~ProcessMonitor()
574{
Stephen Wilson84ffe702011-03-30 15:55:52 +0000575 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000576}
577
578//------------------------------------------------------------------------------
579// Thread setup and tear down.
580void
581ProcessMonitor::StartOperationThread(LaunchArgs *args, Error &error)
582{
583 static const char *g_thread_name = "lldb.process.linux.operation";
584
Stephen Wilsond4182f42011-02-09 20:10:35 +0000585 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000586 return;
587
588 m_operation_thread =
589 Host::ThreadCreate(g_thread_name, OperationThread, args, &error);
590}
591
592void
593ProcessMonitor::StopOperationThread()
594{
595 lldb::thread_result_t result;
596
Stephen Wilsond4182f42011-02-09 20:10:35 +0000597 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000598 return;
599
600 Host::ThreadCancel(m_operation_thread, NULL);
601 Host::ThreadJoin(m_operation_thread, &result, NULL);
602}
603
604void *
605ProcessMonitor::OperationThread(void *arg)
606{
607 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
608
609 if (!Launch(args))
610 return NULL;
611
Stephen Wilson570243b2011-01-19 01:37:06 +0000612 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000613 return NULL;
614}
615
616bool
617ProcessMonitor::Launch(LaunchArgs *args)
618{
619 ProcessMonitor *monitor = args->m_monitor;
620 ProcessLinux &process = monitor->GetProcess();
621 const char **argv = args->m_argv;
622 const char **envp = args->m_envp;
623 const char *stdin_path = args->m_stdin_path;
624 const char *stdout_path = args->m_stdout_path;
625 const char *stderr_path = args->m_stderr_path;
626
627 lldb_utility::PseudoTerminal terminal;
628 const size_t err_len = 1024;
629 char err_str[err_len];
630 lldb::pid_t pid;
631
632 lldb::ThreadSP inferior;
633
Stephen Wilson57740ec2011-01-15 00:12:41 +0000634 // Propagate the environment if one is not supplied.
635 if (envp == NULL || envp[0] == NULL)
636 envp = const_cast<const char **>(environ);
637
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000638 // Pseudo terminal setup.
639 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
640 {
641 args->m_error.SetErrorToGenericError();
642 args->m_error.SetErrorString("Could not open controlling TTY.");
643 goto FINISH;
644 }
645
646 if ((pid = terminal.Fork(err_str, err_len)) < 0)
647 {
648 args->m_error.SetErrorToGenericError();
649 args->m_error.SetErrorString("Process fork failed.");
650 goto FINISH;
651 }
652
653 // Child process.
654 if (pid == 0)
655 {
656 // Trace this process.
657 ptrace(PTRACE_TRACEME, 0, NULL, NULL);
658
659 // Do not inherit setgid powers.
660 setgid(getgid());
661
662 // Let us have our own process group.
663 setpgid(0, 0);
664
Greg Clayton710dd5a2011-01-08 20:28:42 +0000665 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000666 //
667 // FIXME: If two or more of the paths are the same we needlessly open
668 // the same file multiple times.
669 if (stdin_path != NULL && stdin_path[0])
670 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY | O_CREAT))
671 exit(1);
672
673 if (stdout_path != NULL && stdout_path[0])
674 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
675 exit(1);
676
677 if (stderr_path != NULL && stderr_path[0])
678 if (!DupDescriptor(stderr_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
679 exit(1);
680
681 // Execute. We should never return.
682 execve(argv[0],
683 const_cast<char *const *>(argv),
684 const_cast<char *const *>(envp));
685 exit(-1);
686 }
687
688 // Wait for the child process to to trap on its call to execve.
689 int status;
690 if ((status = waitpid(pid, NULL, 0)) < 0)
691 {
692 // execve likely failed for some reason.
693 args->m_error.SetErrorToErrno();
694 goto FINISH;
695 }
696 assert(status == pid && "Could not sync with inferior process.");
697
698 // Have the child raise an event on exit. This is used to keep the child in
699 // limbo until it is destroyed.
700 if (ptrace(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0)
701 {
702 args->m_error.SetErrorToErrno();
703 goto FINISH;
704 }
705
706 // Release the master terminal descriptor and pass it off to the
707 // ProcessMonitor instance. Similarly stash the inferior pid.
708 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
709 monitor->m_pid = pid;
710
Stephen Wilson26977162011-03-23 02:14:42 +0000711 // Set the terminal fd to be in non blocking mode (it simplifies the
712 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
713 // descriptor to read from).
714 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
715 goto FINISH;
716
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000717 // Update the process thread list with this new thread and mark it as
718 // current.
719 inferior.reset(new LinuxThread(process, pid));
720 process.GetThreadList().AddThread(inferior);
Stephen Wilson5a8feea2011-01-04 21:39:27 +0000721 process.GetThreadList().SetSelectedThreadByID(pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000722
723 // Let our process instance know the thread has stopped.
724 process.SendMessage(ProcessMessage::Trace(pid));
725
726FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000727 return args->m_error.Success();
728}
729
730bool
731ProcessMonitor::EnableIPC()
732{
733 int fd[2];
734
735 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
736 return false;
737
738 m_client_fd = fd[0];
739 m_server_fd = fd[1];
740 return true;
741}
742
743bool
744ProcessMonitor::MonitorCallback(void *callback_baton,
745 lldb::pid_t pid,
746 int signal,
747 int status)
748{
749 ProcessMessage message;
750 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
751 ProcessLinux *process = monitor->m_process;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000752 bool stop_monitoring;
753 siginfo_t info;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000754
Stephen Wilson84ffe702011-03-30 15:55:52 +0000755 if (!monitor->GetSignalInfo(pid, &info))
756 stop_monitoring = true; // pid is gone. Bail.
757 else {
758 switch (info.si_signo)
759 {
760 case SIGTRAP:
761 message = MonitorSIGTRAP(monitor, &info, pid);
762 break;
763
764 default:
765 message = MonitorSignal(monitor, &info, pid);
766 break;
767 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000768
Stephen Wilson84ffe702011-03-30 15:55:52 +0000769 process->SendMessage(message);
770 stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000771 }
772
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000773 return stop_monitoring;
774}
775
776ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +0000777ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
778 const struct siginfo *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000779{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000780 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000781
Stephen Wilson84ffe702011-03-30 15:55:52 +0000782 assert(info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000783
Stephen Wilson84ffe702011-03-30 15:55:52 +0000784 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000785 {
786 default:
787 assert(false && "Unexpected SIGTRAP code!");
788 break;
789
790 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
791 {
792 // The inferior process is about to exit. Maintain the process in a
793 // state of "limbo" until we are explicitly commanded to detach,
794 // destroy, resume, etc.
795 unsigned long data = 0;
796 if (!monitor->GetEventMessage(pid, &data))
797 data = -1;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000798 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000799 break;
800 }
801
802 case 0:
803 case TRAP_TRACE:
804 message = ProcessMessage::Trace(pid);
805 break;
806
807 case SI_KERNEL:
808 case TRAP_BRKPT:
809 message = ProcessMessage::Break(pid);
810 break;
811 }
812
813 return message;
814}
815
Stephen Wilson84ffe702011-03-30 15:55:52 +0000816ProcessMessage
817ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
818 const struct siginfo *info, lldb::pid_t pid)
819{
820 ProcessMessage message;
821 int signo = info->si_signo;
822
823 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
824 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
825 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
826 //
827 // IOW, user generated signals never generate what we consider to be a
828 // "crash".
829 //
830 // Similarly, ACK signals generated by this monitor.
831 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
832 {
833 if (info->si_pid == getpid())
834 return ProcessMessage::SignalDelivered(pid, signo);
835 else
836 return ProcessMessage::Signal(pid, signo);
837 }
838
839 if (signo == SIGSEGV) {
840 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
841 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
842 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
843 }
844
845 if (signo == SIGILL) {
846 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
847 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
848 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
849 }
850
851 if (signo == SIGFPE) {
852 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
853 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
854 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
855 }
856
857 if (signo == SIGBUS) {
858 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
859 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
860 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
861 }
862
863 // Everything else is "normal" and does not require any special action on
864 // our part.
865 return ProcessMessage::Signal(pid, signo);
866}
867
868ProcessMessage::CrashReason
869ProcessMonitor::GetCrashReasonForSIGSEGV(const struct siginfo *info)
870{
871 ProcessMessage::CrashReason reason;
872 assert(info->si_signo == SIGSEGV);
873
874 reason = ProcessMessage::eInvalidCrashReason;
875
876 switch (info->si_code)
877 {
878 default:
879 assert(false && "unexpected si_code for SIGSEGV");
880 break;
881 case SEGV_MAPERR:
882 reason = ProcessMessage::eInvalidAddress;
883 break;
884 case SEGV_ACCERR:
885 reason = ProcessMessage::ePrivilegedAddress;
886 break;
887 }
888
889 return reason;
890}
891
892ProcessMessage::CrashReason
893ProcessMonitor::GetCrashReasonForSIGILL(const struct siginfo *info)
894{
895 ProcessMessage::CrashReason reason;
896 assert(info->si_signo == SIGILL);
897
898 reason = ProcessMessage::eInvalidCrashReason;
899
900 switch (info->si_code)
901 {
902 default:
903 assert(false && "unexpected si_code for SIGILL");
904 break;
905 case ILL_ILLOPC:
906 reason = ProcessMessage::eIllegalOpcode;
907 break;
908 case ILL_ILLOPN:
909 reason = ProcessMessage::eIllegalOperand;
910 break;
911 case ILL_ILLADR:
912 reason = ProcessMessage::eIllegalAddressingMode;
913 break;
914 case ILL_ILLTRP:
915 reason = ProcessMessage::eIllegalTrap;
916 break;
917 case ILL_PRVOPC:
918 reason = ProcessMessage::ePrivilegedOpcode;
919 break;
920 case ILL_PRVREG:
921 reason = ProcessMessage::ePrivilegedRegister;
922 break;
923 case ILL_COPROC:
924 reason = ProcessMessage::eCoprocessorError;
925 break;
926 case ILL_BADSTK:
927 reason = ProcessMessage::eInternalStackError;
928 break;
929 }
930
931 return reason;
932}
933
934ProcessMessage::CrashReason
935ProcessMonitor::GetCrashReasonForSIGFPE(const struct siginfo *info)
936{
937 ProcessMessage::CrashReason reason;
938 assert(info->si_signo == SIGFPE);
939
940 reason = ProcessMessage::eInvalidCrashReason;
941
942 switch (info->si_code)
943 {
944 default:
945 assert(false && "unexpected si_code for SIGFPE");
946 break;
947 case FPE_INTDIV:
948 reason = ProcessMessage::eIntegerDivideByZero;
949 break;
950 case FPE_INTOVF:
951 reason = ProcessMessage::eIntegerOverflow;
952 break;
953 case FPE_FLTDIV:
954 reason = ProcessMessage::eFloatDivideByZero;
955 break;
956 case FPE_FLTOVF:
957 reason = ProcessMessage::eFloatOverflow;
958 break;
959 case FPE_FLTUND:
960 reason = ProcessMessage::eFloatUnderflow;
961 break;
962 case FPE_FLTRES:
963 reason = ProcessMessage::eFloatInexactResult;
964 break;
965 case FPE_FLTINV:
966 reason = ProcessMessage::eFloatInvalidOperation;
967 break;
968 case FPE_FLTSUB:
969 reason = ProcessMessage::eFloatSubscriptRange;
970 break;
971 }
972
973 return reason;
974}
975
976ProcessMessage::CrashReason
977ProcessMonitor::GetCrashReasonForSIGBUS(const struct siginfo *info)
978{
979 ProcessMessage::CrashReason reason;
980 assert(info->si_signo == SIGBUS);
981
982 reason = ProcessMessage::eInvalidCrashReason;
983
984 switch (info->si_code)
985 {
986 default:
987 assert(false && "unexpected si_code for SIGBUS");
988 break;
989 case BUS_ADRALN:
990 reason = ProcessMessage::eIllegalAlignment;
991 break;
992 case BUS_ADRERR:
993 reason = ProcessMessage::eIllegalAddress;
994 break;
995 case BUS_OBJERR:
996 reason = ProcessMessage::eHardwareError;
997 break;
998 }
999
1000 return reason;
1001}
1002
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001003void
Stephen Wilson570243b2011-01-19 01:37:06 +00001004ProcessMonitor::ServeOperation(LaunchArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001005{
1006 int status;
1007 pollfd fdset;
Stephen Wilson570243b2011-01-19 01:37:06 +00001008 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001009
1010 fdset.fd = monitor->m_server_fd;
1011 fdset.events = POLLIN | POLLPRI;
1012 fdset.revents = 0;
1013
Stephen Wilson570243b2011-01-19 01:37:06 +00001014 // We are finised with the arguments and are ready to go. Sync with the
1015 // parent thread and start serving operations on the inferior.
1016 sem_post(&args->m_semaphore);
1017
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001018 for (;;)
1019 {
1020 if ((status = poll(&fdset, 1, -1)) < 0)
1021 {
1022 switch (errno)
1023 {
1024 default:
1025 assert(false && "Unexpected poll() failure!");
1026 continue;
1027
1028 case EINTR: continue; // Just poll again.
1029 case EBADF: return; // Connection terminated.
1030 }
1031 }
1032
1033 assert(status == 1 && "Too many descriptors!");
1034
1035 if (fdset.revents & POLLIN)
1036 {
1037 Operation *op = NULL;
1038
1039 READ_AGAIN:
1040 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1041 {
1042 // There is only one acceptable failure.
1043 assert(errno == EINTR);
1044 goto READ_AGAIN;
1045 }
1046
1047 assert(status == sizeof(op));
1048 op->Execute(monitor);
1049 write(fdset.fd, &op, sizeof(op));
1050 }
1051 }
1052}
1053
1054void
1055ProcessMonitor::DoOperation(Operation *op)
1056{
1057 int status;
1058 Operation *ack = NULL;
1059 Mutex::Locker lock(m_server_mutex);
1060
1061 // FIXME: Do proper error checking here.
1062 write(m_client_fd, &op, sizeof(op));
1063
1064READ_AGAIN:
1065 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1066 {
1067 // If interrupted by a signal handler try again. Otherwise the monitor
1068 // thread probably died and we have a stale file descriptor -- abort the
1069 // operation.
1070 if (errno == EINTR)
1071 goto READ_AGAIN;
1072 return;
1073 }
1074
1075 assert(status == sizeof(ack));
1076 assert(ack == op && "Invalid monitor thread response!");
1077}
1078
1079size_t
1080ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1081 Error &error)
1082{
1083 size_t result;
1084 ReadOperation op(vm_addr, buf, size, error, result);
1085 DoOperation(&op);
1086 return result;
1087}
1088
1089size_t
1090ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1091 lldb_private::Error &error)
1092{
1093 size_t result;
1094 WriteOperation op(vm_addr, buf, size, error, result);
1095 DoOperation(&op);
1096 return result;
1097}
1098
1099bool
1100ProcessMonitor::ReadRegisterValue(unsigned offset, Scalar &value)
1101{
1102 bool result;
1103 ReadRegOperation op(offset, value, result);
1104 DoOperation(&op);
1105 return result;
1106}
1107
1108bool
1109ProcessMonitor::WriteRegisterValue(unsigned offset, const Scalar &value)
1110{
1111 bool result;
1112 WriteRegOperation op(offset, value, result);
1113 DoOperation(&op);
1114 return result;
1115}
1116
1117bool
Stephen Wilsonade1aea2011-01-19 01:31:38 +00001118ProcessMonitor::ReadGPR(void *buf)
1119{
1120 bool result;
1121 ReadGPROperation op(buf, result);
1122 DoOperation(&op);
1123 return result;
1124}
1125
1126bool
1127ProcessMonitor::ReadFPR(void *buf)
1128{
1129 bool result;
1130 ReadFPROperation op(buf, result);
1131 DoOperation(&op);
1132 return result;
1133}
1134
1135bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001136ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001137{
1138 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001139 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001140 DoOperation(&op);
1141 return result;
1142}
1143
1144bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001145ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001146{
1147 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001148 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001149 DoOperation(&op);
1150 return result;
1151}
1152
1153bool
1154ProcessMonitor::BringProcessIntoLimbo()
1155{
1156 bool result;
1157 KillOperation op(result);
1158 DoOperation(&op);
1159 return result;
1160}
1161
1162bool
1163ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo)
1164{
1165 bool result;
1166 SiginfoOperation op(tid, siginfo, result);
1167 DoOperation(&op);
1168 return result;
1169}
1170
1171bool
1172ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1173{
1174 bool result;
1175 EventMessageOperation op(tid, message, result);
1176 DoOperation(&op);
1177 return result;
1178}
1179
1180bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00001181ProcessMonitor::Detach()
1182{
1183 bool result;
1184 KillOperation op(result);
1185 DoOperation(&op);
1186 StopMonitor();
1187 return result;
1188}
1189
1190bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001191ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1192{
1193 int target_fd = open(path, flags);
1194
1195 if (target_fd == -1)
1196 return false;
1197
1198 return (dup2(fd, target_fd) == -1) ? false : true;
1199}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001200
1201void
1202ProcessMonitor::StopMonitoringChildProcess()
1203{
1204 lldb::thread_result_t thread_result;
1205
Stephen Wilsond4182f42011-02-09 20:10:35 +00001206 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00001207 {
1208 Host::ThreadCancel(m_monitor_thread, NULL);
1209 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1210 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1211 }
1212}
Stephen Wilson84ffe702011-03-30 15:55:52 +00001213
1214void
1215ProcessMonitor::StopMonitor()
1216{
1217 StopMonitoringChildProcess();
1218 StopOperationThread();
1219 CloseFD(m_terminal_fd);
1220 CloseFD(m_client_fd);
1221 CloseFD(m_server_fd);
1222}
1223
1224void
1225ProcessMonitor::CloseFD(int &fd)
1226{
1227 if (fd != -1)
1228 {
1229 close(fd);
1230 fd = -1;
1231 }
1232}