1 //===-- ProcessMonitor.cpp ------------------------------------ -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
17 #include <sys/ptrace.h>
18 #include <sys/socket.h>
19 #include <sys/types.h>
23 // Other libraries and framework includes
24 #include "lldb/Core/Error.h"
25 #include "lldb/Core/RegisterValue.h"
26 #include "lldb/Core/Scalar.h"
27 #include "lldb/Host/Host.h"
28 #include "lldb/Target/Thread.h"
29 #include "lldb/Target/RegisterContext.h"
30 #include "lldb/Utility/PseudoTerminal.h"
33 #include "POSIXThread.h"
34 #include "ProcessFreeBSD.h"
35 #include "ProcessPOSIXLog.h"
36 #include "ProcessMonitor.h"
39 extern char ** environ;
43 using namespace lldb_private;
45 // We disable the tracing of ptrace calls for integration builds to
46 // avoid the additional indirection and checks.
47 #ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
48 // Wrapper for ptrace to catch errors and log calls.
54 case PIOD_READ_D: return "READ_D";
55 case PIOD_WRITE_D: return "WRITE_D";
56 case PIOD_READ_I: return "READ_I";
57 case PIOD_WRITE_I: return "WRITE_I";
58 default: return "Unknown op";
62 // Wrapper for ptrace to catch errors and log calls.
63 // Note that ptrace sets errno on error because -1 is reserved as a valid result.
65 PtraceWrapper(int req, lldb::pid_t pid, void *addr, int data,
66 const char* reqName, const char* file, int line)
70 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
73 log->Printf("ptrace(%s, %lu, %p, %x) called from file %s line %d",
74 reqName, pid, addr, data, file, line);
76 struct ptrace_io_desc *pi = (struct ptrace_io_desc *) addr;
78 log->Printf("PT_IO: op=%s offs=%zx size=%ld",
79 Get_PT_IO_OP(pi->piod_op), (size_t)pi->piod_offs, pi->piod_len);
83 //PtraceDisplayBytes(req, data);
86 result = ptrace(req, pid, (caddr_t) addr, data);
88 //PtraceDisplayBytes(req, data);
90 if (log && errno != 0)
95 case ESRCH: str = "ESRCH"; break;
96 case EINVAL: str = "EINVAL"; break;
97 case EBUSY: str = "EBUSY"; break;
98 case EPERM: str = "EPERM"; break;
99 default: str = "<unknown>";
101 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
106 if (req == PT_GETREGS) {
107 struct reg *r = (struct reg *) addr;
109 log->Printf("PT_GETREGS: ip=0x%lx", r->r_rip);
110 log->Printf("PT_GETREGS: sp=0x%lx", r->r_rsp);
111 log->Printf("PT_GETREGS: bp=0x%lx", r->r_rbp);
112 log->Printf("PT_GETREGS: ax=0x%lx", r->r_rax);
120 // Wrapper for ptrace when logging is not required.
121 // Sets errno to 0 prior to calling ptrace.
123 PtraceWrapper(int req, lldb::pid_t pid, void *addr, int data)
127 result = ptrace(req, pid, (caddr_t)addr, data);
131 #define PTRACE(req, pid, addr, data) \
132 PtraceWrapper((req), (pid), (addr), (data), #req, __FILE__, __LINE__)
134 PtraceWrapper((req), (pid), (addr), (data))
137 //------------------------------------------------------------------------------
138 // Static implementations of ProcessMonitor::ReadMemory and
139 // ProcessMonitor::WriteMemory. This enables mutual recursion between these
140 // functions without needed to go thru the thread funnel.
143 DoReadMemory(lldb::pid_t pid, lldb::addr_t vm_addr, void *buf, size_t size,
146 struct ptrace_io_desc pi_desc;
148 pi_desc.piod_op = PIOD_READ_D;
149 pi_desc.piod_offs = (void *)vm_addr;
150 pi_desc.piod_addr = buf;
151 pi_desc.piod_len = size;
153 if (PTRACE(PT_IO, pid, (caddr_t)&pi_desc, 0) < 0)
154 error.SetErrorToErrno();
155 return pi_desc.piod_len;
159 DoWriteMemory(lldb::pid_t pid, lldb::addr_t vm_addr, const void *buf,
160 size_t size, Error &error)
162 struct ptrace_io_desc pi_desc;
164 pi_desc.piod_op = PIOD_WRITE_D;
165 pi_desc.piod_offs = (void *)vm_addr;
166 pi_desc.piod_addr = (void *)buf;
167 pi_desc.piod_len = size;
169 if (PTRACE(PT_IO, pid, (caddr_t)&pi_desc, 0) < 0)
170 error.SetErrorToErrno();
171 return pi_desc.piod_len;
174 // Simple helper function to ensure flags are enabled on the given file
177 EnsureFDFlags(int fd, int flags, Error &error)
181 if ((status = fcntl(fd, F_GETFL)) == -1)
183 error.SetErrorToErrno();
187 if (fcntl(fd, F_SETFL, status | flags) == -1)
189 error.SetErrorToErrno();
196 //------------------------------------------------------------------------------
198 /// @brief Represents a ProcessMonitor operation.
200 /// Under FreeBSD, it is not possible to ptrace() from any other thread but the
201 /// one that spawned or attached to the process from the start. Therefore, when
202 /// a ProcessMonitor is asked to deliver or change the state of an inferior
203 /// process the operation must be "funneled" to a specific thread to perform the
204 /// task. The Operation class provides an abstract base for all services the
205 /// ProcessMonitor must perform via the single virtual function Execute, thus
206 /// encapsulating the code that needs to run in the privileged context.
210 virtual ~Operation() {}
211 virtual void Execute(ProcessMonitor *monitor) = 0;
214 //------------------------------------------------------------------------------
215 /// @class ReadOperation
216 /// @brief Implements ProcessMonitor::ReadMemory.
217 class ReadOperation : public Operation
220 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
221 Error &error, size_t &result)
222 : m_addr(addr), m_buff(buff), m_size(size),
223 m_error(error), m_result(result)
226 void Execute(ProcessMonitor *monitor);
237 ReadOperation::Execute(ProcessMonitor *monitor)
239 lldb::pid_t pid = monitor->GetPID();
241 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
244 //------------------------------------------------------------------------------
245 /// @class WriteOperation
246 /// @brief Implements ProcessMonitor::WriteMemory.
247 class WriteOperation : public Operation
250 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
251 Error &error, size_t &result)
252 : m_addr(addr), m_buff(buff), m_size(size),
253 m_error(error), m_result(result)
256 void Execute(ProcessMonitor *monitor);
267 WriteOperation::Execute(ProcessMonitor *monitor)
269 lldb::pid_t pid = monitor->GetPID();
271 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
274 //------------------------------------------------------------------------------
275 /// @class ReadRegOperation
276 /// @brief Implements ProcessMonitor::ReadRegisterValue.
277 class ReadRegOperation : public Operation
280 ReadRegOperation(lldb::tid_t tid, unsigned offset, unsigned size,
281 RegisterValue &value, bool &result)
282 : m_tid(tid), m_offset(offset), m_size(size),
283 m_value(value), m_result(result)
286 void Execute(ProcessMonitor *monitor);
292 RegisterValue &m_value;
297 ReadRegOperation::Execute(ProcessMonitor *monitor)
302 if ((rc = PTRACE(PT_GETREGS, m_tid, (caddr_t)®s, 0)) < 0) {
305 if (m_size == sizeof(uintptr_t))
306 m_value = *(uintptr_t *)(((caddr_t)®s) + m_offset);
308 memcpy(&m_value, (((caddr_t)®s) + m_offset), m_size);
313 //------------------------------------------------------------------------------
314 /// @class WriteRegOperation
315 /// @brief Implements ProcessMonitor::WriteRegisterValue.
316 class WriteRegOperation : public Operation
319 WriteRegOperation(lldb::tid_t tid, unsigned offset,
320 const RegisterValue &value, bool &result)
321 : m_tid(tid), m_offset(offset),
322 m_value(value), m_result(result)
325 void Execute(ProcessMonitor *monitor);
330 const RegisterValue &m_value;
335 WriteRegOperation::Execute(ProcessMonitor *monitor)
339 if (PTRACE(PT_GETREGS, m_tid, (caddr_t)®s, 0) < 0) {
343 *(uintptr_t *)(((caddr_t)®s) + m_offset) = (uintptr_t)m_value.GetAsUInt64();
344 if (PTRACE(PT_SETREGS, m_tid, (caddr_t)®s, 0) < 0)
350 //------------------------------------------------------------------------------
351 /// @class ReadGPROperation
352 /// @brief Implements ProcessMonitor::ReadGPR.
353 class ReadGPROperation : public Operation
356 ReadGPROperation(lldb::tid_t tid, void *buf, bool &result)
357 : m_tid(tid), m_buf(buf), m_result(result)
360 void Execute(ProcessMonitor *monitor);
369 ReadGPROperation::Execute(ProcessMonitor *monitor)
374 rc = PTRACE(PT_GETREGS, m_tid, (caddr_t)m_buf, 0);
381 //------------------------------------------------------------------------------
382 /// @class ReadFPROperation
383 /// @brief Implements ProcessMonitor::ReadFPR.
384 class ReadFPROperation : public Operation
387 ReadFPROperation(lldb::tid_t tid, void *buf, bool &result)
388 : m_tid(tid), m_buf(buf), m_result(result)
391 void Execute(ProcessMonitor *monitor);
400 ReadFPROperation::Execute(ProcessMonitor *monitor)
402 if (PTRACE(PT_GETFPREGS, m_tid, (caddr_t)m_buf, 0) < 0)
408 //------------------------------------------------------------------------------
409 /// @class WriteGPROperation
410 /// @brief Implements ProcessMonitor::WriteGPR.
411 class WriteGPROperation : public Operation
414 WriteGPROperation(lldb::tid_t tid, void *buf, bool &result)
415 : m_tid(tid), m_buf(buf), m_result(result)
418 void Execute(ProcessMonitor *monitor);
427 WriteGPROperation::Execute(ProcessMonitor *monitor)
429 if (PTRACE(PT_SETREGS, m_tid, (caddr_t)m_buf, 0) < 0)
435 //------------------------------------------------------------------------------
436 /// @class WriteFPROperation
437 /// @brief Implements ProcessMonitor::WriteFPR.
438 class WriteFPROperation : public Operation
441 WriteFPROperation(lldb::tid_t tid, void *buf, bool &result)
442 : m_tid(tid), m_buf(buf), m_result(result)
445 void Execute(ProcessMonitor *monitor);
454 WriteFPROperation::Execute(ProcessMonitor *monitor)
456 if (PTRACE(PT_SETFPREGS, m_tid, (caddr_t)m_buf, 0) < 0)
462 //------------------------------------------------------------------------------
463 /// @class ResumeOperation
464 /// @brief Implements ProcessMonitor::Resume.
465 class ResumeOperation : public Operation
468 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
469 m_tid(tid), m_signo(signo), m_result(result) { }
471 void Execute(ProcessMonitor *monitor);
480 ResumeOperation::Execute(ProcessMonitor *monitor)
484 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
487 if (PTRACE(PT_CONTINUE, m_tid, (caddr_t)1, data))
489 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
492 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, strerror(errno));
499 //------------------------------------------------------------------------------
500 /// @class SingleStepOperation
501 /// @brief Implements ProcessMonitor::SingleStep.
502 class SingleStepOperation : public Operation
505 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
506 : m_tid(tid), m_signo(signo), m_result(result) { }
508 void Execute(ProcessMonitor *monitor);
517 SingleStepOperation::Execute(ProcessMonitor *monitor)
521 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
524 if (PTRACE(PT_STEP, m_tid, NULL, data))
530 //------------------------------------------------------------------------------
531 /// @class LwpInfoOperation
532 /// @brief Implements ProcessMonitor::GetLwpInfo.
533 class LwpInfoOperation : public Operation
536 LwpInfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
537 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
539 void Execute(ProcessMonitor *monitor);
549 LwpInfoOperation::Execute(ProcessMonitor *monitor)
551 struct ptrace_lwpinfo plwp;
553 if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp))) {
557 memcpy(m_info, &plwp, sizeof(plwp));
562 //------------------------------------------------------------------------------
563 /// @class EventMessageOperation
564 /// @brief Implements ProcessMonitor::GetEventMessage.
565 class EventMessageOperation : public Operation
568 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
569 : m_tid(tid), m_message(message), m_result(result) { }
571 void Execute(ProcessMonitor *monitor);
575 unsigned long *m_message;
580 EventMessageOperation::Execute(ProcessMonitor *monitor)
582 struct ptrace_lwpinfo plwp;
584 if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp)))
587 if (plwp.pl_flags & PL_FLAG_FORKED) {
588 m_message = (unsigned long *)plwp.pl_child_pid;
595 //------------------------------------------------------------------------------
596 /// @class KillOperation
597 /// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
598 class KillOperation : public Operation
601 KillOperation(bool &result) : m_result(result) { }
603 void Execute(ProcessMonitor *monitor);
610 KillOperation::Execute(ProcessMonitor *monitor)
612 lldb::pid_t pid = monitor->GetPID();
614 if (PTRACE(PT_KILL, pid, NULL, 0))
620 //------------------------------------------------------------------------------
621 /// @class DetachOperation
622 /// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
623 class DetachOperation : public Operation
626 DetachOperation(Error &result) : m_error(result) { }
628 void Execute(ProcessMonitor *monitor);
635 DetachOperation::Execute(ProcessMonitor *monitor)
637 lldb::pid_t pid = monitor->GetPID();
639 if (PTRACE(PT_DETACH, pid, NULL, 0) < 0)
640 m_error.SetErrorToErrno();
644 ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
647 sem_init(&m_semaphore, 0, 0);
650 ProcessMonitor::OperationArgs::~OperationArgs()
652 sem_destroy(&m_semaphore);
655 ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
656 lldb_private::Module *module,
659 const char *stdin_path,
660 const char *stdout_path,
661 const char *stderr_path,
662 const char *working_dir)
663 : OperationArgs(monitor),
667 m_stdin_path(stdin_path),
668 m_stdout_path(stdout_path),
669 m_stderr_path(stderr_path),
670 m_working_dir(working_dir) { }
672 ProcessMonitor::LaunchArgs::~LaunchArgs()
675 ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
677 : OperationArgs(monitor), m_pid(pid) { }
679 ProcessMonitor::AttachArgs::~AttachArgs()
682 //------------------------------------------------------------------------------
683 /// The basic design of the ProcessMonitor is built around two threads.
685 /// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
686 /// for changes in the debugee state. When a change is detected a
687 /// ProcessMessage is sent to the associated ProcessFreeBSD instance. This thread
688 /// "drives" state changes in the debugger.
690 /// The second thread (@see OperationThread) is responsible for two things 1)
691 /// launching or attaching to the inferior process, and then 2) servicing
692 /// operations such as register reads/writes, stepping, etc. See the comments
693 /// on the Operation class for more info as to why this is needed.
694 ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
698 const char *stdin_path,
699 const char *stdout_path,
700 const char *stderr_path,
701 const char *working_dir,
702 lldb_private::Error &error)
703 : m_process(static_cast<ProcessFreeBSD *>(process)),
704 m_operation_thread(LLDB_INVALID_HOST_THREAD),
705 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
706 m_pid(LLDB_INVALID_PROCESS_ID),
707 m_server_mutex(Mutex::eMutexTypeRecursive),
712 std::unique_ptr<LaunchArgs> args;
714 args.reset(new LaunchArgs(this, module, argv, envp,
715 stdin_path, stdout_path, stderr_path, working_dir));
718 // Server/client descriptors.
721 error.SetErrorToGenericError();
722 error.SetErrorString("Monitor failed to initialize.");
725 StartLaunchOpThread(args.get(), error);
726 if (!error.Success())
730 // Wait for the operation thread to initialize.
731 if (sem_wait(&args->m_semaphore))
737 error.SetErrorToErrno();
742 // Check that the launch was a success.
743 if (!args->m_error.Success())
746 error = args->m_error;
750 // Finally, start monitoring the child process for change in state.
751 m_monitor_thread = Host::StartMonitoringChildProcess(
752 ProcessMonitor::MonitorCallback, this, GetPID(), true);
753 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
755 error.SetErrorToGenericError();
756 error.SetErrorString("Process launch failed.");
761 ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
763 lldb_private::Error &error)
764 : m_process(static_cast<ProcessFreeBSD *>(process)),
765 m_operation_thread(LLDB_INVALID_HOST_THREAD),
766 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
768 m_server_mutex(Mutex::eMutexTypeRecursive),
773 std::unique_ptr<AttachArgs> args;
775 args.reset(new AttachArgs(this, pid));
777 // Server/client descriptors.
780 error.SetErrorToGenericError();
781 error.SetErrorString("Monitor failed to initialize.");
784 StartAttachOpThread(args.get(), error);
785 if (!error.Success())
789 // Wait for the operation thread to initialize.
790 if (sem_wait(&args->m_semaphore))
796 error.SetErrorToErrno();
801 // Check that the attach was a success.
802 if (!args->m_error.Success())
805 error = args->m_error;
809 // Finally, start monitoring the child process for change in state.
810 m_monitor_thread = Host::StartMonitoringChildProcess(
811 ProcessMonitor::MonitorCallback, this, GetPID(), true);
812 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
814 error.SetErrorToGenericError();
815 error.SetErrorString("Process attach failed.");
820 ProcessMonitor::~ProcessMonitor()
825 //------------------------------------------------------------------------------
826 // Thread setup and tear down.
828 ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
830 static const char *g_thread_name = "lldb.process.freebsd.operation";
832 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
836 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
840 ProcessMonitor::LaunchOpThread(void *arg)
842 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
845 sem_post(&args->m_semaphore);
849 ServeOperation(args);
854 ProcessMonitor::Launch(LaunchArgs *args)
856 ProcessMonitor *monitor = args->m_monitor;
857 ProcessFreeBSD &process = monitor->GetProcess();
858 lldb::ProcessSP processSP = process.shared_from_this();
859 const char **argv = args->m_argv;
860 const char **envp = args->m_envp;
861 const char *stdin_path = args->m_stdin_path;
862 const char *stdout_path = args->m_stdout_path;
863 const char *stderr_path = args->m_stderr_path;
864 const char *working_dir = args->m_working_dir;
866 lldb_utility::PseudoTerminal terminal;
867 const size_t err_len = 1024;
868 char err_str[err_len];
871 lldb::ThreadSP inferior;
872 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
874 // Propagate the environment if one is not supplied.
875 if (envp == NULL || envp[0] == NULL)
876 envp = const_cast<const char **>(environ);
878 // Pseudo terminal setup.
879 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
881 args->m_error.SetErrorToGenericError();
882 args->m_error.SetErrorString("Could not open controlling TTY.");
886 if ((pid = terminal.Fork(err_str, err_len)) == -1)
888 args->m_error.SetErrorToGenericError();
889 args->m_error.SetErrorString("Process fork failed.");
893 // Recognized child exit status codes.
906 // Trace this process.
907 if (PTRACE(PT_TRACE_ME, 0, NULL, 0) < 0)
910 // Do not inherit setgid powers.
913 // Let us have our own process group.
916 // Dup file descriptors if needed.
918 // FIXME: If two or more of the paths are the same we needlessly open
919 // the same file multiple times.
920 if (stdin_path != NULL && stdin_path[0])
921 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
922 exit(eDupStdinFailed);
924 if (stdout_path != NULL && stdout_path[0])
925 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
926 exit(eDupStdoutFailed);
928 if (stderr_path != NULL && stderr_path[0])
929 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
930 exit(eDupStderrFailed);
932 // Change working directory
933 if (working_dir != NULL && working_dir[0])
934 if (0 != ::chdir(working_dir))
937 // Execute. We should never return.
939 const_cast<char *const *>(argv),
940 const_cast<char *const *>(envp));
944 // Wait for the child process to to trap on its call to execve.
947 if ((wpid = waitpid(pid, &status, 0)) < 0)
949 args->m_error.SetErrorToErrno();
952 else if (WIFEXITED(status))
954 // open, dup or execve likely failed for some reason.
955 args->m_error.SetErrorToGenericError();
956 switch (WEXITSTATUS(status))
959 args->m_error.SetErrorString("Child ptrace failed.");
961 case eDupStdinFailed:
962 args->m_error.SetErrorString("Child open stdin failed.");
964 case eDupStdoutFailed:
965 args->m_error.SetErrorString("Child open stdout failed.");
967 case eDupStderrFailed:
968 args->m_error.SetErrorString("Child open stderr failed.");
971 args->m_error.SetErrorString("Child failed to set working directory.");
974 args->m_error.SetErrorString("Child exec failed.");
977 args->m_error.SetErrorString("Child returned unknown exit status.");
982 assert(WIFSTOPPED(status) && wpid == pid &&
983 "Could not sync with inferior process.");
986 // Have the child raise an event on exit. This is used to keep the child in
987 // limbo until it is destroyed.
988 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0)
990 args->m_error.SetErrorToErrno();
994 // Release the master terminal descriptor and pass it off to the
995 // ProcessMonitor instance. Similarly stash the inferior pid.
996 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
997 monitor->m_pid = pid;
999 // Set the terminal fd to be in non blocking mode (it simplifies the
1000 // implementation of ProcessFreeBSD::GetSTDOUT to have a non-blocking
1001 // descriptor to read from).
1002 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1005 // Update the process thread list with this new thread.
1006 inferior.reset(process.CreateNewPOSIXThread(*processSP, pid));
1008 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1009 process.GetThreadList().AddThread(inferior);
1011 // Let our process instance know the thread has stopped.
1012 process.SendMessage(ProcessMessage::Trace(pid));
1015 return args->m_error.Success();
1019 ProcessMonitor::EnableIPC()
1023 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
1026 m_client_fd = fd[0];
1027 m_server_fd = fd[1];
1032 ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1034 static const char *g_thread_name = "lldb.process.freebsd.operation";
1036 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1039 m_operation_thread =
1040 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1044 ProcessMonitor::AttachOpThread(void *arg)
1046 AttachArgs *args = static_cast<AttachArgs*>(arg);
1051 ServeOperation(args);
1056 ProcessMonitor::Attach(AttachArgs *args)
1058 lldb::pid_t pid = args->m_pid;
1060 ProcessMonitor *monitor = args->m_monitor;
1061 ProcessFreeBSD &process = monitor->GetProcess();
1062 lldb::ProcessSP processSP = process.shared_from_this();
1063 ThreadList &tl = process.GetThreadList();
1064 lldb::ThreadSP inferior;
1068 args->m_error.SetErrorToGenericError();
1069 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1073 // Attach to the requested process.
1074 if (PTRACE(PT_ATTACH, pid, NULL, 0) < 0)
1076 args->m_error.SetErrorToErrno();
1081 if ((status = waitpid(pid, NULL, 0)) < 0)
1083 args->m_error.SetErrorToErrno();
1087 // Update the process thread list with the attached thread.
1088 inferior.reset(process.CreateNewPOSIXThread(*processSP, pid));
1089 tl.AddThread(inferior);
1091 // Let our process instance know the thread has stopped.
1092 process.SendMessage(ProcessMessage::Trace(pid));
1095 return args->m_error.Success();
1099 ProcessMonitor::MonitorCallback(void *callback_baton,
1105 ProcessMessage message;
1106 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
1107 ProcessFreeBSD *process = monitor->m_process;
1109 bool stop_monitoring;
1110 struct ptrace_lwpinfo plwp;
1113 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1118 log->Printf ("ProcessMonitor::%s() got exit signal, tid = %" PRIu64, __FUNCTION__, pid);
1119 message = ProcessMessage::Exit(pid, status);
1120 process->SendMessage(message);
1121 return pid == process->GetID();
1124 if (!monitor->GetLwpInfo(pid, &plwp, ptrace_err))
1125 stop_monitoring = true; // pid is gone. Bail.
1127 switch (plwp.pl_siginfo.si_signo)
1130 message = MonitorSIGTRAP(monitor, &plwp.pl_siginfo, pid);
1134 message = MonitorSignal(monitor, &plwp.pl_siginfo, pid);
1138 process->SendMessage(message);
1139 stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
1142 return stop_monitoring;
1146 ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
1147 const siginfo_t *info, lldb::pid_t pid)
1149 ProcessMessage message;
1151 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1154 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1156 switch (info->si_code)
1159 assert(false && "Unexpected SIGTRAP code!");
1162 case (SIGTRAP /* | (PTRACE_EVENT_EXIT << 8) */):
1164 // The inferior process is about to exit. Maintain the process in a
1165 // state of "limbo" until we are explicitly commanded to detach,
1166 // destroy, resume, etc.
1167 unsigned long data = 0;
1168 if (!monitor->GetEventMessage(pid, &data))
1171 log->Printf ("ProcessMonitor::%s() received exit? event, data = %lx, pid = %" PRIu64, __FUNCTION__, data, pid);
1172 message = ProcessMessage::Limbo(pid, (data >> 8));
1179 log->Printf ("ProcessMonitor::%s() received trace event, pid = %" PRIu64, __FUNCTION__, pid);
1180 message = ProcessMessage::Trace(pid);
1186 log->Printf ("ProcessMonitor::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
1187 message = ProcessMessage::Break(pid);
1195 ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
1196 const siginfo_t *info, lldb::pid_t pid)
1198 ProcessMessage message;
1199 int signo = info->si_signo;
1201 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1203 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1204 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1205 // kill(2) or raise(3). Similarly for tgkill(2) on FreeBSD.
1207 // IOW, user generated signals never generate what we consider to be a
1210 // Similarly, ACK signals generated by this monitor.
1211 if (info->si_code == SI_USER)
1214 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
1216 monitor->m_process->GetUnixSignals().GetSignalAsCString (signo),
1219 if (info->si_pid == getpid())
1220 return ProcessMessage::SignalDelivered(pid, signo);
1222 return ProcessMessage::Signal(pid, signo);
1226 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals().GetSignalAsCString (signo));
1228 if (signo == SIGSEGV) {
1229 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1230 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1231 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1234 if (signo == SIGILL) {
1235 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1236 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1237 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1240 if (signo == SIGFPE) {
1241 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1242 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1243 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1246 if (signo == SIGBUS) {
1247 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1248 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1249 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1252 // Everything else is "normal" and does not require any special action on
1254 return ProcessMessage::Signal(pid, signo);
1257 ProcessMessage::CrashReason
1258 ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1260 ProcessMessage::CrashReason reason;
1261 assert(info->si_signo == SIGSEGV);
1263 reason = ProcessMessage::eInvalidCrashReason;
1265 switch (info->si_code)
1268 assert(false && "unexpected si_code for SIGSEGV");
1271 reason = ProcessMessage::eInvalidAddress;
1274 reason = ProcessMessage::ePrivilegedAddress;
1281 ProcessMessage::CrashReason
1282 ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
1284 ProcessMessage::CrashReason reason;
1285 assert(info->si_signo == SIGILL);
1287 reason = ProcessMessage::eInvalidCrashReason;
1289 switch (info->si_code)
1292 assert(false && "unexpected si_code for SIGILL");
1295 reason = ProcessMessage::eIllegalOpcode;
1298 reason = ProcessMessage::eIllegalOperand;
1301 reason = ProcessMessage::eIllegalAddressingMode;
1304 reason = ProcessMessage::eIllegalTrap;
1307 reason = ProcessMessage::ePrivilegedOpcode;
1310 reason = ProcessMessage::ePrivilegedRegister;
1313 reason = ProcessMessage::eCoprocessorError;
1316 reason = ProcessMessage::eInternalStackError;
1323 ProcessMessage::CrashReason
1324 ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
1326 ProcessMessage::CrashReason reason;
1327 assert(info->si_signo == SIGFPE);
1329 reason = ProcessMessage::eInvalidCrashReason;
1331 switch (info->si_code)
1334 assert(false && "unexpected si_code for SIGFPE");
1337 reason = ProcessMessage::eIntegerDivideByZero;
1340 reason = ProcessMessage::eIntegerOverflow;
1343 reason = ProcessMessage::eFloatDivideByZero;
1346 reason = ProcessMessage::eFloatOverflow;
1349 reason = ProcessMessage::eFloatUnderflow;
1352 reason = ProcessMessage::eFloatInexactResult;
1355 reason = ProcessMessage::eFloatInvalidOperation;
1358 reason = ProcessMessage::eFloatSubscriptRange;
1365 ProcessMessage::CrashReason
1366 ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
1368 ProcessMessage::CrashReason reason;
1369 assert(info->si_signo == SIGBUS);
1371 reason = ProcessMessage::eInvalidCrashReason;
1373 switch (info->si_code)
1376 assert(false && "unexpected si_code for SIGBUS");
1379 reason = ProcessMessage::eIllegalAlignment;
1382 reason = ProcessMessage::eIllegalAddress;
1385 reason = ProcessMessage::eHardwareError;
1393 ProcessMonitor::ServeOperation(OperationArgs *args)
1398 ProcessMonitor *monitor = args->m_monitor;
1400 fdset.fd = monitor->m_server_fd;
1401 fdset.events = POLLIN | POLLPRI;
1404 // We are finised with the arguments and are ready to go. Sync with the
1405 // parent thread and start serving operations on the inferior.
1406 sem_post(&args->m_semaphore);
1410 if ((status = poll(&fdset, 1, -1)) < 0)
1415 assert(false && "Unexpected poll() failure!");
1418 case EINTR: continue; // Just poll again.
1419 case EBADF: return; // Connection terminated.
1423 assert(status == 1 && "Too many descriptors!");
1425 if (fdset.revents & POLLIN)
1427 Operation *op = NULL;
1430 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1432 // There is only one acceptable failure.
1433 assert(errno == EINTR);
1437 continue; // Poll again. The connection probably terminated.
1438 assert(status == sizeof(op));
1439 op->Execute(monitor);
1440 write(fdset.fd, &op, sizeof(op));
1446 ProcessMonitor::DoOperation(Operation *op)
1449 Operation *ack = NULL;
1450 Mutex::Locker lock(m_server_mutex);
1452 // FIXME: Do proper error checking here.
1453 write(m_client_fd, &op, sizeof(op));
1456 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1458 // If interrupted by a signal handler try again. Otherwise the monitor
1459 // thread probably died and we have a stale file descriptor -- abort the
1466 assert(status == sizeof(ack));
1467 assert(ack == op && "Invalid monitor thread response!");
1471 ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1475 ReadOperation op(vm_addr, buf, size, error, result);
1481 ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1482 lldb_private::Error &error)
1485 WriteOperation op(vm_addr, buf, size, error, result);
1491 ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
1492 unsigned size, RegisterValue &value)
1495 ReadRegOperation op(tid, offset, size, value, result);
1501 ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
1502 const char* reg_name, const RegisterValue &value)
1505 WriteRegOperation op(tid, offset, value, result);
1511 ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
1514 ReadGPROperation op(tid, buf, result);
1520 ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
1523 ReadFPROperation op(tid, buf, result);
1529 ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1535 ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
1538 WriteGPROperation op(tid, buf, result);
1544 ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
1547 WriteFPROperation op(tid, buf, result);
1553 ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1559 ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
1562 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1565 log->Printf ("ProcessMonitor::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
1566 m_process->GetUnixSignals().GetSignalAsCString (signo));
1567 ResumeOperation op(tid, signo, result);
1570 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
1575 ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
1578 SingleStepOperation op(tid, signo, result);
1584 ProcessMonitor::BringProcessIntoLimbo()
1587 KillOperation op(result);
1593 ProcessMonitor::GetLwpInfo(lldb::tid_t tid, void *lwpinfo, int &ptrace_err)
1596 LwpInfoOperation op(tid, lwpinfo, result, ptrace_err);
1602 ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1605 EventMessageOperation op(tid, message, result);
1611 ProcessMonitor::Detach(lldb::tid_t tid)
1613 lldb_private::Error error;
1614 if (tid != LLDB_INVALID_THREAD_ID)
1616 DetachOperation op(error);
1623 ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
1625 int target_fd = open(path, flags, 0666);
1627 if (target_fd == -1)
1630 return (dup2(target_fd, fd) == -1) ? false : true;
1634 ProcessMonitor::StopMonitoringChildProcess()
1636 lldb::thread_result_t thread_result;
1638 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
1640 Host::ThreadCancel(m_monitor_thread, NULL);
1641 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
1642 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
1647 ProcessMonitor::StopMonitor()
1649 StopMonitoringChildProcess();
1651 CloseFD(m_terminal_fd);
1652 CloseFD(m_client_fd);
1653 CloseFD(m_server_fd);
1657 ProcessMonitor::StopOpThread()
1659 lldb::thread_result_t result;
1661 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1664 Host::ThreadCancel(m_operation_thread, NULL);
1665 Host::ThreadJoin(m_operation_thread, &result, NULL);
1666 m_operation_thread = LLDB_INVALID_HOST_THREAD;
1670 ProcessMonitor::CloseFD(int &fd)