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/Host/ThreadLauncher.h"
29 #include "lldb/Target/Thread.h"
30 #include "lldb/Target/RegisterContext.h"
31 #include "lldb/Target/UnixSignals.h"
32 #include "lldb/Utility/PseudoTerminal.h"
34 #include "Plugins/Process/POSIX/CrashReason.h"
35 #include "FreeBSDThread.h"
36 #include "ProcessFreeBSD.h"
37 #include "ProcessPOSIXLog.h"
38 #include "ProcessMonitor.h"
41 extern char ** environ;
45 using namespace lldb_private;
47 // We disable the tracing of ptrace calls for integration builds to
48 // avoid the additional indirection and checks.
49 #ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
50 // Wrapper for ptrace to catch errors and log calls.
56 case PIOD_READ_D: return "READ_D";
57 case PIOD_WRITE_D: return "WRITE_D";
58 case PIOD_READ_I: return "READ_I";
59 case PIOD_WRITE_I: return "WRITE_I";
60 default: return "Unknown op";
64 // Wrapper for ptrace to catch errors and log calls.
65 // Note that ptrace sets errno on error because -1 is reserved as a valid result.
67 PtraceWrapper(int req, lldb::pid_t pid, void *addr, int data,
68 const char* reqName, const char* file, int line)
72 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
75 log->Printf("ptrace(%s, %" PRIu64 ", %p, %x) called from file %s line %d",
76 reqName, pid, addr, data, file, line);
78 struct ptrace_io_desc *pi = (struct ptrace_io_desc *) addr;
80 log->Printf("PT_IO: op=%s offs=%zx size=%zu",
81 Get_PT_IO_OP(pi->piod_op), (size_t)pi->piod_offs, pi->piod_len);
85 //PtraceDisplayBytes(req, data);
88 result = ptrace(req, pid, (caddr_t) addr, data);
90 //PtraceDisplayBytes(req, data);
92 if (log && errno != 0)
97 case ESRCH: str = "ESRCH"; break;
98 case EINVAL: str = "EINVAL"; break;
99 case EBUSY: str = "EBUSY"; break;
100 case EPERM: str = "EPERM"; break;
101 default: str = "<unknown>";
103 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
108 if (req == PT_GETREGS) {
109 struct reg *r = (struct reg *) addr;
111 log->Printf("PT_GETREGS: rip=0x%lx rsp=0x%lx rbp=0x%lx rax=0x%lx",
112 r->r_rip, r->r_rsp, r->r_rbp, r->r_rax);
114 if (req == PT_GETDBREGS || req == PT_SETDBREGS) {
115 struct dbreg *r = (struct dbreg *) addr;
116 char setget = (req == PT_GETDBREGS) ? 'G' : 'S';
118 for (int i = 0; i <= 7; i++)
119 log->Printf("PT_%cETDBREGS: dr[%d]=0x%lx", setget, i, r->dr[i]);
127 // Wrapper for ptrace when logging is not required.
128 // Sets errno to 0 prior to calling ptrace.
130 PtraceWrapper(int req, lldb::pid_t pid, void *addr, int data)
134 result = ptrace(req, pid, (caddr_t)addr, data);
138 #define PTRACE(req, pid, addr, data) \
139 PtraceWrapper((req), (pid), (addr), (data), #req, __FILE__, __LINE__)
141 PtraceWrapper((req), (pid), (addr), (data))
144 //------------------------------------------------------------------------------
145 // Static implementations of ProcessMonitor::ReadMemory and
146 // ProcessMonitor::WriteMemory. This enables mutual recursion between these
147 // functions without needed to go thru the thread funnel.
150 DoReadMemory(lldb::pid_t pid, lldb::addr_t vm_addr, void *buf, size_t size,
153 struct ptrace_io_desc pi_desc;
155 pi_desc.piod_op = PIOD_READ_D;
156 pi_desc.piod_offs = (void *)vm_addr;
157 pi_desc.piod_addr = buf;
158 pi_desc.piod_len = size;
160 if (PTRACE(PT_IO, pid, (caddr_t)&pi_desc, 0) < 0)
161 error.SetErrorToErrno();
162 return pi_desc.piod_len;
166 DoWriteMemory(lldb::pid_t pid, lldb::addr_t vm_addr, const void *buf,
167 size_t size, Error &error)
169 struct ptrace_io_desc pi_desc;
171 pi_desc.piod_op = PIOD_WRITE_D;
172 pi_desc.piod_offs = (void *)vm_addr;
173 pi_desc.piod_addr = (void *)buf;
174 pi_desc.piod_len = size;
176 if (PTRACE(PT_IO, pid, (caddr_t)&pi_desc, 0) < 0)
177 error.SetErrorToErrno();
178 return pi_desc.piod_len;
181 // Simple helper function to ensure flags are enabled on the given file
184 EnsureFDFlags(int fd, int flags, Error &error)
188 if ((status = fcntl(fd, F_GETFL)) == -1)
190 error.SetErrorToErrno();
194 if (fcntl(fd, F_SETFL, status | flags) == -1)
196 error.SetErrorToErrno();
203 //------------------------------------------------------------------------------
205 /// @brief Represents a ProcessMonitor operation.
207 /// Under FreeBSD, it is not possible to ptrace() from any other thread but the
208 /// one that spawned or attached to the process from the start. Therefore, when
209 /// a ProcessMonitor is asked to deliver or change the state of an inferior
210 /// process the operation must be "funneled" to a specific thread to perform the
211 /// task. The Operation class provides an abstract base for all services the
212 /// ProcessMonitor must perform via the single virtual function Execute, thus
213 /// encapsulating the code that needs to run in the privileged context.
217 virtual ~Operation() {}
218 virtual void Execute(ProcessMonitor *monitor) = 0;
221 //------------------------------------------------------------------------------
222 /// @class ReadOperation
223 /// @brief Implements ProcessMonitor::ReadMemory.
224 class ReadOperation : public Operation
227 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
228 Error &error, size_t &result)
229 : m_addr(addr), m_buff(buff), m_size(size),
230 m_error(error), m_result(result)
233 void Execute(ProcessMonitor *monitor);
244 ReadOperation::Execute(ProcessMonitor *monitor)
246 lldb::pid_t pid = monitor->GetPID();
248 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
251 //------------------------------------------------------------------------------
252 /// @class WriteOperation
253 /// @brief Implements ProcessMonitor::WriteMemory.
254 class WriteOperation : public Operation
257 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
258 Error &error, size_t &result)
259 : m_addr(addr), m_buff(buff), m_size(size),
260 m_error(error), m_result(result)
263 void Execute(ProcessMonitor *monitor);
274 WriteOperation::Execute(ProcessMonitor *monitor)
276 lldb::pid_t pid = monitor->GetPID();
278 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
281 //------------------------------------------------------------------------------
282 /// @class ReadRegOperation
283 /// @brief Implements ProcessMonitor::ReadRegisterValue.
284 class ReadRegOperation : public Operation
287 ReadRegOperation(lldb::tid_t tid, unsigned offset, unsigned size,
288 RegisterValue &value, bool &result)
289 : m_tid(tid), m_offset(offset), m_size(size),
290 m_value(value), m_result(result)
293 void Execute(ProcessMonitor *monitor);
299 RegisterValue &m_value;
304 ReadRegOperation::Execute(ProcessMonitor *monitor)
309 if ((rc = PTRACE(PT_GETREGS, m_tid, (caddr_t)®s, 0)) < 0) {
312 // 'struct reg' contains only 32- or 64-bit register values. Punt on
313 // others. Also, not all entries may be uintptr_t sized, such as 32-bit
314 // processes on powerpc64 (probably the same for i386 on amd64)
315 if (m_size == sizeof(uint32_t))
316 m_value = *(uint32_t *)(((caddr_t)®s) + m_offset);
317 else if (m_size == sizeof(uint64_t))
318 m_value = *(uint64_t *)(((caddr_t)®s) + m_offset);
320 memcpy((void *)&m_value, (((caddr_t)®s) + m_offset), m_size);
325 //------------------------------------------------------------------------------
326 /// @class WriteRegOperation
327 /// @brief Implements ProcessMonitor::WriteRegisterValue.
328 class WriteRegOperation : public Operation
331 WriteRegOperation(lldb::tid_t tid, unsigned offset,
332 const RegisterValue &value, bool &result)
333 : m_tid(tid), m_offset(offset),
334 m_value(value), m_result(result)
337 void Execute(ProcessMonitor *monitor);
342 const RegisterValue &m_value;
347 WriteRegOperation::Execute(ProcessMonitor *monitor)
351 if (PTRACE(PT_GETREGS, m_tid, (caddr_t)®s, 0) < 0) {
355 *(uintptr_t *)(((caddr_t)®s) + m_offset) = (uintptr_t)m_value.GetAsUInt64();
356 if (PTRACE(PT_SETREGS, m_tid, (caddr_t)®s, 0) < 0)
362 //------------------------------------------------------------------------------
363 /// @class ReadDebugRegOperation
364 /// @brief Implements ProcessMonitor::ReadDebugRegisterValue.
365 class ReadDebugRegOperation : public Operation
368 ReadDebugRegOperation(lldb::tid_t tid, unsigned offset, unsigned size,
369 RegisterValue &value, bool &result)
370 : m_tid(tid), m_offset(offset), m_size(size),
371 m_value(value), m_result(result)
374 void Execute(ProcessMonitor *monitor);
380 RegisterValue &m_value;
385 ReadDebugRegOperation::Execute(ProcessMonitor *monitor)
390 if ((rc = PTRACE(PT_GETDBREGS, m_tid, (caddr_t)®s, 0)) < 0) {
393 if (m_size == sizeof(uintptr_t))
394 m_value = *(uintptr_t *)(((caddr_t)®s) + m_offset);
396 memcpy((void *)&m_value, (((caddr_t)®s) + m_offset), m_size);
401 //------------------------------------------------------------------------------
402 /// @class WriteDebugRegOperation
403 /// @brief Implements ProcessMonitor::WriteDebugRegisterValue.
404 class WriteDebugRegOperation : public Operation
407 WriteDebugRegOperation(lldb::tid_t tid, unsigned offset,
408 const RegisterValue &value, bool &result)
409 : m_tid(tid), m_offset(offset),
410 m_value(value), m_result(result)
413 void Execute(ProcessMonitor *monitor);
418 const RegisterValue &m_value;
423 WriteDebugRegOperation::Execute(ProcessMonitor *monitor)
427 if (PTRACE(PT_GETDBREGS, m_tid, (caddr_t)®s, 0) < 0) {
431 *(uintptr_t *)(((caddr_t)®s) + m_offset) = (uintptr_t)m_value.GetAsUInt64();
432 if (PTRACE(PT_SETDBREGS, m_tid, (caddr_t)®s, 0) < 0)
438 //------------------------------------------------------------------------------
439 /// @class ReadGPROperation
440 /// @brief Implements ProcessMonitor::ReadGPR.
441 class ReadGPROperation : public Operation
444 ReadGPROperation(lldb::tid_t tid, void *buf, bool &result)
445 : m_tid(tid), m_buf(buf), m_result(result)
448 void Execute(ProcessMonitor *monitor);
457 ReadGPROperation::Execute(ProcessMonitor *monitor)
462 rc = PTRACE(PT_GETREGS, m_tid, (caddr_t)m_buf, 0);
469 //------------------------------------------------------------------------------
470 /// @class ReadFPROperation
471 /// @brief Implements ProcessMonitor::ReadFPR.
472 class ReadFPROperation : public Operation
475 ReadFPROperation(lldb::tid_t tid, void *buf, bool &result)
476 : m_tid(tid), m_buf(buf), m_result(result)
479 void Execute(ProcessMonitor *monitor);
488 ReadFPROperation::Execute(ProcessMonitor *monitor)
490 if (PTRACE(PT_GETFPREGS, m_tid, (caddr_t)m_buf, 0) < 0)
496 //------------------------------------------------------------------------------
497 /// @class WriteGPROperation
498 /// @brief Implements ProcessMonitor::WriteGPR.
499 class WriteGPROperation : public Operation
502 WriteGPROperation(lldb::tid_t tid, void *buf, bool &result)
503 : m_tid(tid), m_buf(buf), m_result(result)
506 void Execute(ProcessMonitor *monitor);
515 WriteGPROperation::Execute(ProcessMonitor *monitor)
517 if (PTRACE(PT_SETREGS, m_tid, (caddr_t)m_buf, 0) < 0)
523 //------------------------------------------------------------------------------
524 /// @class WriteFPROperation
525 /// @brief Implements ProcessMonitor::WriteFPR.
526 class WriteFPROperation : public Operation
529 WriteFPROperation(lldb::tid_t tid, void *buf, bool &result)
530 : m_tid(tid), m_buf(buf), m_result(result)
533 void Execute(ProcessMonitor *monitor);
542 WriteFPROperation::Execute(ProcessMonitor *monitor)
544 if (PTRACE(PT_SETFPREGS, m_tid, (caddr_t)m_buf, 0) < 0)
550 //------------------------------------------------------------------------------
551 /// @class ResumeOperation
552 /// @brief Implements ProcessMonitor::Resume.
553 class ResumeOperation : public Operation
556 ResumeOperation(uint32_t signo, bool &result) :
557 m_signo(signo), m_result(result) { }
559 void Execute(ProcessMonitor *monitor);
567 ResumeOperation::Execute(ProcessMonitor *monitor)
569 lldb::pid_t pid = monitor->GetPID();
572 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
575 if (PTRACE(PT_CONTINUE, pid, (caddr_t)1, data))
577 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
580 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", pid, strerror(errno));
587 //------------------------------------------------------------------------------
588 /// @class SingleStepOperation
589 /// @brief Implements ProcessMonitor::SingleStep.
590 class SingleStepOperation : public Operation
593 SingleStepOperation(uint32_t signo, bool &result)
594 : m_signo(signo), m_result(result) { }
596 void Execute(ProcessMonitor *monitor);
604 SingleStepOperation::Execute(ProcessMonitor *monitor)
606 lldb::pid_t pid = monitor->GetPID();
609 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
612 if (PTRACE(PT_STEP, pid, NULL, data))
618 //------------------------------------------------------------------------------
619 /// @class LwpInfoOperation
620 /// @brief Implements ProcessMonitor::GetLwpInfo.
621 class LwpInfoOperation : public Operation
624 LwpInfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
625 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
627 void Execute(ProcessMonitor *monitor);
637 LwpInfoOperation::Execute(ProcessMonitor *monitor)
639 struct ptrace_lwpinfo plwp;
641 if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp))) {
645 memcpy(m_info, &plwp, sizeof(plwp));
650 //------------------------------------------------------------------------------
651 /// @class ThreadSuspendOperation
652 /// @brief Implements ProcessMonitor::ThreadSuspend.
653 class ThreadSuspendOperation : public Operation
656 ThreadSuspendOperation(lldb::tid_t tid, bool suspend, bool &result)
657 : m_tid(tid), m_suspend(suspend), m_result(result) { }
659 void Execute(ProcessMonitor *monitor);
668 ThreadSuspendOperation::Execute(ProcessMonitor *monitor)
670 m_result = !PTRACE(m_suspend ? PT_SUSPEND : PT_RESUME, m_tid, NULL, 0);
675 //------------------------------------------------------------------------------
676 /// @class EventMessageOperation
677 /// @brief Implements ProcessMonitor::GetEventMessage.
678 class EventMessageOperation : public Operation
681 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
682 : m_tid(tid), m_message(message), m_result(result) { }
684 void Execute(ProcessMonitor *monitor);
688 unsigned long *m_message;
693 EventMessageOperation::Execute(ProcessMonitor *monitor)
695 struct ptrace_lwpinfo plwp;
697 if (PTRACE(PT_LWPINFO, m_tid, (caddr_t)&plwp, sizeof(plwp)))
700 if (plwp.pl_flags & PL_FLAG_FORKED) {
701 *m_message = plwp.pl_child_pid;
708 //------------------------------------------------------------------------------
709 /// @class KillOperation
710 /// @brief Implements ProcessMonitor::Kill.
711 class KillOperation : public Operation
714 KillOperation(bool &result) : m_result(result) { }
716 void Execute(ProcessMonitor *monitor);
723 KillOperation::Execute(ProcessMonitor *monitor)
725 lldb::pid_t pid = monitor->GetPID();
727 if (PTRACE(PT_KILL, pid, NULL, 0))
733 //------------------------------------------------------------------------------
734 /// @class DetachOperation
735 /// @brief Implements ProcessMonitor::Detach.
736 class DetachOperation : public Operation
739 DetachOperation(Error &result) : m_error(result) { }
741 void Execute(ProcessMonitor *monitor);
748 DetachOperation::Execute(ProcessMonitor *monitor)
750 lldb::pid_t pid = monitor->GetPID();
752 if (PTRACE(PT_DETACH, pid, NULL, 0) < 0)
753 m_error.SetErrorToErrno();
757 ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
760 sem_init(&m_semaphore, 0, 0);
763 ProcessMonitor::OperationArgs::~OperationArgs()
765 sem_destroy(&m_semaphore);
768 ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
769 lldb_private::Module *module,
772 const FileSpec &stdin_file_spec,
773 const FileSpec &stdout_file_spec,
774 const FileSpec &stderr_file_spec,
775 const FileSpec &working_dir)
776 : OperationArgs(monitor),
780 m_stdin_file_spec(stdin_file_spec),
781 m_stdout_file_spec(stdout_file_spec),
782 m_stderr_file_spec(stderr_file_spec),
783 m_working_dir(working_dir) { }
785 ProcessMonitor::LaunchArgs::~LaunchArgs()
788 ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
790 : OperationArgs(monitor), m_pid(pid) { }
792 ProcessMonitor::AttachArgs::~AttachArgs()
795 //------------------------------------------------------------------------------
796 /// The basic design of the ProcessMonitor is built around two threads.
798 /// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
799 /// for changes in the debugee state. When a change is detected a
800 /// ProcessMessage is sent to the associated ProcessFreeBSD instance. This thread
801 /// "drives" state changes in the debugger.
803 /// The second thread (@see OperationThread) is responsible for two things 1)
804 /// launching or attaching to the inferior process, and then 2) servicing
805 /// operations such as register reads/writes, stepping, etc. See the comments
806 /// on the Operation class for more info as to why this is needed.
807 ProcessMonitor::ProcessMonitor(ProcessFreeBSD *process,
811 const FileSpec &stdin_file_spec,
812 const FileSpec &stdout_file_spec,
813 const FileSpec &stderr_file_spec,
814 const FileSpec &working_dir,
815 const lldb_private::ProcessLaunchInfo & /* launch_info */,
816 lldb_private::Error &error)
817 : m_process(static_cast<ProcessFreeBSD *>(process)),
818 m_pid(LLDB_INVALID_PROCESS_ID),
822 using namespace std::placeholders;
824 std::unique_ptr<LaunchArgs> args(new LaunchArgs(this, module, argv, envp,
831 sem_init(&m_operation_pending, 0, 0);
832 sem_init(&m_operation_done, 0, 0);
834 StartLaunchOpThread(args.get(), error);
835 if (!error.Success())
839 // Wait for the operation thread to initialize.
840 if (sem_wait(&args->m_semaphore))
846 error.SetErrorToErrno();
851 // Check that the launch was a success.
852 if (!args->m_error.Success())
855 error = args->m_error;
859 // Finally, start monitoring the child process for change in state.
860 m_monitor_thread = Host::StartMonitoringChildProcess(
861 std::bind(&ProcessMonitor::MonitorCallback, this, _1, _2, _3, _4), GetPID(), true);
862 if (!m_monitor_thread.IsJoinable())
864 error.SetErrorToGenericError();
865 error.SetErrorString("Process launch failed.");
870 ProcessMonitor::ProcessMonitor(ProcessFreeBSD *process,
872 lldb_private::Error &error)
873 : m_process(static_cast<ProcessFreeBSD *>(process)),
878 using namespace std::placeholders;
880 sem_init(&m_operation_pending, 0, 0);
881 sem_init(&m_operation_done, 0, 0);
884 std::unique_ptr<AttachArgs> args(new AttachArgs(this, pid));
886 StartAttachOpThread(args.get(), error);
887 if (!error.Success())
891 // Wait for the operation thread to initialize.
892 if (sem_wait(&args->m_semaphore))
898 error.SetErrorToErrno();
903 // Check that the attach was a success.
904 if (!args->m_error.Success())
907 error = args->m_error;
911 // Finally, start monitoring the child process for change in state.
912 m_monitor_thread = Host::StartMonitoringChildProcess(
913 std::bind(&ProcessMonitor::MonitorCallback, this, _1, _2, _3, _4), GetPID(), true);
914 if (!m_monitor_thread.IsJoinable())
916 error.SetErrorToGenericError();
917 error.SetErrorString("Process attach failed.");
922 ProcessMonitor::~ProcessMonitor()
927 //------------------------------------------------------------------------------
928 // Thread setup and tear down.
930 ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
932 static const char *g_thread_name = "lldb.process.freebsd.operation";
934 if (m_operation_thread.IsJoinable())
937 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
941 ProcessMonitor::LaunchOpThread(void *arg)
943 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
946 sem_post(&args->m_semaphore);
950 ServeOperation(args);
955 ProcessMonitor::Launch(LaunchArgs *args)
957 ProcessMonitor *monitor = args->m_monitor;
958 ProcessFreeBSD &process = monitor->GetProcess();
959 const char **argv = args->m_argv;
960 const char **envp = args->m_envp;
961 const FileSpec &stdin_file_spec = args->m_stdin_file_spec;
962 const FileSpec &stdout_file_spec = args->m_stdout_file_spec;
963 const FileSpec &stderr_file_spec = args->m_stderr_file_spec;
964 const FileSpec &working_dir = args->m_working_dir;
966 lldb_utility::PseudoTerminal terminal;
967 const size_t err_len = 1024;
968 char err_str[err_len];
971 // Propagate the environment if one is not supplied.
972 if (envp == NULL || envp[0] == NULL)
973 envp = const_cast<const char **>(environ);
975 if ((pid = terminal.Fork(err_str, err_len)) == -1)
977 args->m_error.SetErrorToGenericError();
978 args->m_error.SetErrorString("Process fork failed.");
982 // Recognized child exit status codes.
996 // Trace this process.
997 if (PTRACE(PT_TRACE_ME, 0, NULL, 0) < 0)
1000 // terminal has already dupped the tty descriptors to stdin/out/err.
1001 // This closes original fd from which they were copied (and avoids
1002 // leaking descriptors to the debugged process.
1003 terminal.CloseSlaveFileDescriptor();
1005 // Do not inherit setgid powers.
1006 if (setgid(getgid()) != 0)
1007 exit(eSetGidFailed);
1009 // Let us have our own process group.
1012 // Dup file descriptors if needed.
1014 // FIXME: If two or more of the paths are the same we needlessly open
1015 // the same file multiple times.
1016 if (stdin_file_spec)
1017 if (!DupDescriptor(stdin_file_spec, STDIN_FILENO, O_RDONLY))
1018 exit(eDupStdinFailed);
1020 if (stdout_file_spec)
1021 if (!DupDescriptor(stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT))
1022 exit(eDupStdoutFailed);
1024 if (stderr_file_spec)
1025 if (!DupDescriptor(stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT))
1026 exit(eDupStderrFailed);
1028 // Change working directory
1029 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
1032 // Execute. We should never return.
1034 const_cast<char *const *>(argv),
1035 const_cast<char *const *>(envp));
1039 // Wait for the child process to to trap on its call to execve.
1042 if ((wpid = waitpid(pid, &status, 0)) < 0)
1044 args->m_error.SetErrorToErrno();
1047 else if (WIFEXITED(status))
1049 // open, dup or execve likely failed for some reason.
1050 args->m_error.SetErrorToGenericError();
1051 switch (WEXITSTATUS(status))
1054 args->m_error.SetErrorString("Child ptrace failed.");
1056 case eDupStdinFailed:
1057 args->m_error.SetErrorString("Child open stdin failed.");
1059 case eDupStdoutFailed:
1060 args->m_error.SetErrorString("Child open stdout failed.");
1062 case eDupStderrFailed:
1063 args->m_error.SetErrorString("Child open stderr failed.");
1066 args->m_error.SetErrorString("Child failed to set working directory.");
1069 args->m_error.SetErrorString("Child exec failed.");
1072 args->m_error.SetErrorString("Child setgid failed.");
1075 args->m_error.SetErrorString("Child returned unknown exit status.");
1080 assert(WIFSTOPPED(status) && wpid == (::pid_t)pid &&
1081 "Could not sync with inferior process.");
1084 // Have the child raise an event on exit. This is used to keep the child in
1085 // limbo until it is destroyed.
1086 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0)
1088 args->m_error.SetErrorToErrno();
1092 // Release the master terminal descriptor and pass it off to the
1093 // ProcessMonitor instance. Similarly stash the inferior pid.
1094 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1095 monitor->m_pid = pid;
1097 // Set the terminal fd to be in non blocking mode (it simplifies the
1098 // implementation of ProcessFreeBSD::GetSTDOUT to have a non-blocking
1099 // descriptor to read from).
1100 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1103 process.SendMessage(ProcessMessage::Attach(pid));
1106 return args->m_error.Success();
1110 ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1112 static const char *g_thread_name = "lldb.process.freebsd.operation";
1114 if (m_operation_thread.IsJoinable())
1117 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
1121 ProcessMonitor::AttachOpThread(void *arg)
1123 AttachArgs *args = static_cast<AttachArgs*>(arg);
1127 ServeOperation(args);
1132 ProcessMonitor::Attach(AttachArgs *args)
1134 lldb::pid_t pid = args->m_pid;
1136 ProcessMonitor *monitor = args->m_monitor;
1137 ProcessFreeBSD &process = monitor->GetProcess();
1141 args->m_error.SetErrorToGenericError();
1142 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1146 // Attach to the requested process.
1147 if (PTRACE(PT_ATTACH, pid, NULL, 0) < 0)
1149 args->m_error.SetErrorToErrno();
1154 if ((status = waitpid(pid, NULL, 0)) < 0)
1156 args->m_error.SetErrorToErrno();
1160 process.SendMessage(ProcessMessage::Attach(pid));
1164 ProcessMonitor::GetCurrentThreadIDs(std::vector<lldb::tid_t>&thread_ids)
1171 tdcnt = PTRACE(PT_GETNUMLWPS, m_pid, NULL, 0);
1174 tids = (lwpid_t *)malloc(tdcnt * sizeof(*tids));
1177 if (PTRACE(PT_GETLWPLIST, m_pid, (void *)tids, tdcnt) < 0) {
1181 thread_ids = std::vector<lldb::tid_t>(tids, tids + tdcnt);
1183 return thread_ids.size();
1187 ProcessMonitor::MonitorCallback(ProcessMonitor *monitor, lldb::pid_t pid, bool exited, int signal, int status)
1189 ProcessMessage message;
1190 ProcessFreeBSD *process = monitor->m_process;
1192 bool stop_monitoring;
1193 struct ptrace_lwpinfo plwp;
1196 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1201 log->Printf ("ProcessMonitor::%s() got exit signal, tid = %" PRIu64, __FUNCTION__, pid);
1202 message = ProcessMessage::Exit(pid, status);
1203 process->SendMessage(message);
1204 return pid == process->GetID();
1207 if (!monitor->GetLwpInfo(pid, &plwp, ptrace_err))
1208 stop_monitoring = true; // pid is gone. Bail.
1210 switch (plwp.pl_siginfo.si_signo)
1213 message = MonitorSIGTRAP(monitor, &plwp.pl_siginfo, plwp.pl_lwpid);
1217 message = MonitorSignal(monitor, &plwp.pl_siginfo, plwp.pl_lwpid);
1221 process->SendMessage(message);
1222 stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
1225 return stop_monitoring;
1229 ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
1230 const siginfo_t *info, lldb::tid_t tid)
1232 ProcessMessage message;
1234 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1237 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1239 switch (info->si_code)
1242 assert(false && "Unexpected SIGTRAP code!");
1245 case (SIGTRAP /* | (PTRACE_EVENT_EXIT << 8) */):
1247 // The inferior process is about to exit. Maintain the process in a
1248 // state of "limbo" until we are explicitly commanded to detach,
1249 // destroy, resume, etc.
1250 unsigned long data = 0;
1251 if (!monitor->GetEventMessage(tid, &data))
1254 log->Printf ("ProcessMonitor::%s() received exit? event, data = %lx, tid = %" PRIu64, __FUNCTION__, data, tid);
1255 message = ProcessMessage::Limbo(tid, (data >> 8));
1262 log->Printf ("ProcessMonitor::%s() received trace event, tid = %" PRIu64 " : si_code = %d", __FUNCTION__, tid, info->si_code);
1263 message = ProcessMessage::Trace(tid);
1269 log->Printf ("ProcessMonitor::%s() received breakpoint event, tid = %" PRIu64, __FUNCTION__, tid);
1270 message = ProcessMessage::Break(tid);
1278 ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
1279 const siginfo_t *info, lldb::tid_t tid)
1281 ProcessMessage message;
1282 int signo = info->si_signo;
1284 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1286 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1287 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1288 // kill(2) or raise(3). Similarly for tgkill(2) on FreeBSD.
1290 // IOW, user generated signals never generate what we consider to be a
1293 // Similarly, ACK signals generated by this monitor.
1294 if (info->si_code == SI_USER)
1297 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
1299 monitor->m_process->GetUnixSignals()->GetSignalAsCString (signo),
1302 if (info->si_pid == getpid())
1303 return ProcessMessage::SignalDelivered(tid, signo);
1305 return ProcessMessage::Signal(tid, signo);
1309 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals()->GetSignalAsCString (signo));
1317 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1318 const auto reason = GetCrashReason(*info);
1319 return ProcessMessage::Crash(tid, reason, signo, fault_addr);
1322 // Everything else is "normal" and does not require any special action on
1324 return ProcessMessage::Signal(tid, signo);
1328 ProcessMonitor::ServeOperation(OperationArgs *args)
1330 ProcessMonitor *monitor = args->m_monitor;
1332 // We are finised with the arguments and are ready to go. Sync with the
1333 // parent thread and start serving operations on the inferior.
1334 sem_post(&args->m_semaphore);
1338 // wait for next pending operation
1339 sem_wait(&monitor->m_operation_pending);
1341 monitor->m_operation->Execute(monitor);
1343 // notify calling thread that operation is complete
1344 sem_post(&monitor->m_operation_done);
1349 ProcessMonitor::DoOperation(Operation *op)
1351 std::lock_guard<std::mutex> guard(m_operation_mutex);
1355 // notify operation thread that an operation is ready to be processed
1356 sem_post(&m_operation_pending);
1358 // wait for operation to complete
1359 sem_wait(&m_operation_done);
1363 ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1367 ReadOperation op(vm_addr, buf, size, error, result);
1373 ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1374 lldb_private::Error &error)
1377 WriteOperation op(vm_addr, buf, size, error, result);
1383 ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
1384 unsigned size, RegisterValue &value)
1387 ReadRegOperation op(tid, offset, size, value, result);
1393 ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
1394 const char* reg_name, const RegisterValue &value)
1397 WriteRegOperation op(tid, offset, value, result);
1403 ProcessMonitor::ReadDebugRegisterValue(lldb::tid_t tid, unsigned offset,
1404 const char *reg_name, unsigned size,
1405 lldb_private::RegisterValue &value)
1408 ReadDebugRegOperation op(tid, offset, size, value, result);
1414 ProcessMonitor::WriteDebugRegisterValue(lldb::tid_t tid, unsigned offset,
1415 const char *reg_name,
1416 const lldb_private::RegisterValue &value)
1419 WriteDebugRegOperation op(tid, offset, value, result);
1425 ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
1428 ReadGPROperation op(tid, buf, result);
1434 ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
1437 ReadFPROperation op(tid, buf, result);
1443 ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1449 ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
1452 WriteGPROperation op(tid, buf, result);
1458 ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
1461 WriteFPROperation op(tid, buf, result);
1467 ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1473 ProcessMonitor::ReadThreadPointer(lldb::tid_t tid, lldb::addr_t &value)
1479 ProcessMonitor::Resume(lldb::tid_t unused, uint32_t signo)
1482 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1485 const char *signame = m_process->GetUnixSignals()->GetSignalAsCString (signo);
1486 if (signame == nullptr)
1488 log->Printf("ProcessMonitor::%s() resuming pid %" PRIu64 " with signal %s",
1489 __FUNCTION__, GetPID(), signame);
1491 ResumeOperation op(signo, result);
1494 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
1499 ProcessMonitor::SingleStep(lldb::tid_t unused, uint32_t signo)
1502 SingleStepOperation op(signo, result);
1508 ProcessMonitor::Kill()
1511 KillOperation op(result);
1517 ProcessMonitor::GetLwpInfo(lldb::tid_t tid, void *lwpinfo, int &ptrace_err)
1520 LwpInfoOperation op(tid, lwpinfo, result, ptrace_err);
1526 ProcessMonitor::ThreadSuspend(lldb::tid_t tid, bool suspend)
1529 ThreadSuspendOperation op(tid, suspend, result);
1535 ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1538 EventMessageOperation op(tid, message, result);
1544 ProcessMonitor::Detach(lldb::tid_t tid)
1546 lldb_private::Error error;
1547 if (tid != LLDB_INVALID_THREAD_ID)
1549 DetachOperation op(error);
1556 ProcessMonitor::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
1558 int target_fd = open(file_spec.GetCString(), flags, 0666);
1560 if (target_fd == -1)
1563 if (dup2(target_fd, fd) == -1)
1566 return (close(target_fd) == -1) ? false : true;
1570 ProcessMonitor::StopMonitoringChildProcess()
1572 if (m_monitor_thread.IsJoinable())
1574 m_monitor_thread.Cancel();
1575 m_monitor_thread.Join(nullptr);
1576 m_monitor_thread.Reset();
1581 ProcessMonitor::StopMonitor()
1583 StopMonitoringChildProcess();
1585 sem_destroy(&m_operation_pending);
1586 sem_destroy(&m_operation_done);
1587 if (m_terminal_fd >= 0) {
1588 close(m_terminal_fd);
1593 // FIXME: On Linux, when a new thread is created, we receive to notifications,
1594 // (1) a SIGTRAP|PTRACE_EVENT_CLONE from the main process thread with the
1595 // child thread id as additional information, and (2) a SIGSTOP|SI_USER from
1596 // the new child thread indicating that it has is stopped because we attached.
1597 // We have no guarantee of the order in which these arrive, but we need both
1598 // before we are ready to proceed. We currently keep a list of threads which
1599 // have sent the initial SIGSTOP|SI_USER event. Then when we receive the
1600 // SIGTRAP|PTRACE_EVENT_CLONE notification, if the initial stop has not occurred
1601 // we call ProcessMonitor::WaitForInitialTIDStop() to wait for it.
1603 // Right now, the above logic is in ProcessPOSIX, so we need a definition of
1604 // this function in the FreeBSD ProcessMonitor implementation even if it isn't
1605 // logically needed.
1607 // We really should figure out what actually happens on FreeBSD and move the
1608 // Linux-specific logic out of ProcessPOSIX as needed.
1611 ProcessMonitor::WaitForInitialTIDStop(lldb::tid_t tid)
1617 ProcessMonitor::StopOpThread()
1619 if (!m_operation_thread.IsJoinable())
1622 m_operation_thread.Cancel();
1623 m_operation_thread.Join(nullptr);
1624 m_operation_thread.Reset();