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 "POSIXThread.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(&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(&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(ProcessPOSIX *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 std::unique_ptr<LaunchArgs> args(new LaunchArgs(this, module, argv, envp,
829 sem_init(&m_operation_pending, 0, 0);
830 sem_init(&m_operation_done, 0, 0);
832 StartLaunchOpThread(args.get(), error);
833 if (!error.Success())
837 // Wait for the operation thread to initialize.
838 if (sem_wait(&args->m_semaphore))
844 error.SetErrorToErrno();
849 // Check that the launch was a success.
850 if (!args->m_error.Success())
853 error = args->m_error;
857 // Finally, start monitoring the child process for change in state.
858 m_monitor_thread = Host::StartMonitoringChildProcess(
859 ProcessMonitor::MonitorCallback, this, GetPID(), true);
860 if (!m_monitor_thread.IsJoinable())
862 error.SetErrorToGenericError();
863 error.SetErrorString("Process launch failed.");
868 ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
870 lldb_private::Error &error)
871 : m_process(static_cast<ProcessFreeBSD *>(process)),
876 sem_init(&m_operation_pending, 0, 0);
877 sem_init(&m_operation_done, 0, 0);
880 std::unique_ptr<AttachArgs> args(new AttachArgs(this, pid));
882 StartAttachOpThread(args.get(), error);
883 if (!error.Success())
887 // Wait for the operation thread to initialize.
888 if (sem_wait(&args->m_semaphore))
894 error.SetErrorToErrno();
899 // Check that the attach was a success.
900 if (!args->m_error.Success())
903 error = args->m_error;
907 // Finally, start monitoring the child process for change in state.
908 m_monitor_thread = Host::StartMonitoringChildProcess(
909 ProcessMonitor::MonitorCallback, this, GetPID(), true);
910 if (!m_monitor_thread.IsJoinable())
912 error.SetErrorToGenericError();
913 error.SetErrorString("Process attach failed.");
918 ProcessMonitor::~ProcessMonitor()
923 //------------------------------------------------------------------------------
924 // Thread setup and tear down.
926 ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
928 static const char *g_thread_name = "lldb.process.freebsd.operation";
930 if (m_operation_thread.IsJoinable())
933 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
937 ProcessMonitor::LaunchOpThread(void *arg)
939 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
942 sem_post(&args->m_semaphore);
946 ServeOperation(args);
951 ProcessMonitor::Launch(LaunchArgs *args)
953 ProcessMonitor *monitor = args->m_monitor;
954 ProcessFreeBSD &process = monitor->GetProcess();
955 const char **argv = args->m_argv;
956 const char **envp = args->m_envp;
957 const FileSpec &stdin_file_spec = args->m_stdin_file_spec;
958 const FileSpec &stdout_file_spec = args->m_stdout_file_spec;
959 const FileSpec &stderr_file_spec = args->m_stderr_file_spec;
960 const FileSpec &working_dir = args->m_working_dir;
962 lldb_utility::PseudoTerminal terminal;
963 const size_t err_len = 1024;
964 char err_str[err_len];
967 // Propagate the environment if one is not supplied.
968 if (envp == NULL || envp[0] == NULL)
969 envp = const_cast<const char **>(environ);
971 if ((pid = terminal.Fork(err_str, err_len)) == -1)
973 args->m_error.SetErrorToGenericError();
974 args->m_error.SetErrorString("Process fork failed.");
978 // Recognized child exit status codes.
992 // Trace this process.
993 if (PTRACE(PT_TRACE_ME, 0, NULL, 0) < 0)
996 // terminal has already dupped the tty descriptors to stdin/out/err.
997 // This closes original fd from which they were copied (and avoids
998 // leaking descriptors to the debugged process.
999 terminal.CloseSlaveFileDescriptor();
1001 // Do not inherit setgid powers.
1002 if (setgid(getgid()) != 0)
1003 exit(eSetGidFailed);
1005 // Let us have our own process group.
1008 // Dup file descriptors if needed.
1010 // FIXME: If two or more of the paths are the same we needlessly open
1011 // the same file multiple times.
1012 if (stdin_file_spec)
1013 if (!DupDescriptor(stdin_file_spec, STDIN_FILENO, O_RDONLY))
1014 exit(eDupStdinFailed);
1016 if (stdout_file_spec)
1017 if (!DupDescriptor(stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT))
1018 exit(eDupStdoutFailed);
1020 if (stderr_file_spec)
1021 if (!DupDescriptor(stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT))
1022 exit(eDupStderrFailed);
1024 // Change working directory
1025 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
1028 // Execute. We should never return.
1030 const_cast<char *const *>(argv),
1031 const_cast<char *const *>(envp));
1035 // Wait for the child process to to trap on its call to execve.
1038 if ((wpid = waitpid(pid, &status, 0)) < 0)
1040 args->m_error.SetErrorToErrno();
1043 else if (WIFEXITED(status))
1045 // open, dup or execve likely failed for some reason.
1046 args->m_error.SetErrorToGenericError();
1047 switch (WEXITSTATUS(status))
1050 args->m_error.SetErrorString("Child ptrace failed.");
1052 case eDupStdinFailed:
1053 args->m_error.SetErrorString("Child open stdin failed.");
1055 case eDupStdoutFailed:
1056 args->m_error.SetErrorString("Child open stdout failed.");
1058 case eDupStderrFailed:
1059 args->m_error.SetErrorString("Child open stderr failed.");
1062 args->m_error.SetErrorString("Child failed to set working directory.");
1065 args->m_error.SetErrorString("Child exec failed.");
1068 args->m_error.SetErrorString("Child setgid failed.");
1071 args->m_error.SetErrorString("Child returned unknown exit status.");
1076 assert(WIFSTOPPED(status) && wpid == (::pid_t)pid &&
1077 "Could not sync with inferior process.");
1080 // Have the child raise an event on exit. This is used to keep the child in
1081 // limbo until it is destroyed.
1082 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACEEXIT) < 0)
1084 args->m_error.SetErrorToErrno();
1088 // Release the master terminal descriptor and pass it off to the
1089 // ProcessMonitor instance. Similarly stash the inferior pid.
1090 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1091 monitor->m_pid = pid;
1093 // Set the terminal fd to be in non blocking mode (it simplifies the
1094 // implementation of ProcessFreeBSD::GetSTDOUT to have a non-blocking
1095 // descriptor to read from).
1096 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1099 process.SendMessage(ProcessMessage::Attach(pid));
1102 return args->m_error.Success();
1106 ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1108 static const char *g_thread_name = "lldb.process.freebsd.operation";
1110 if (m_operation_thread.IsJoinable())
1113 m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
1117 ProcessMonitor::AttachOpThread(void *arg)
1119 AttachArgs *args = static_cast<AttachArgs*>(arg);
1123 ServeOperation(args);
1128 ProcessMonitor::Attach(AttachArgs *args)
1130 lldb::pid_t pid = args->m_pid;
1132 ProcessMonitor *monitor = args->m_monitor;
1133 ProcessFreeBSD &process = monitor->GetProcess();
1137 args->m_error.SetErrorToGenericError();
1138 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1142 // Attach to the requested process.
1143 if (PTRACE(PT_ATTACH, pid, NULL, 0) < 0)
1145 args->m_error.SetErrorToErrno();
1150 if ((status = waitpid(pid, NULL, 0)) < 0)
1152 args->m_error.SetErrorToErrno();
1156 process.SendMessage(ProcessMessage::Attach(pid));
1160 ProcessMonitor::GetCurrentThreadIDs(std::vector<lldb::tid_t>&thread_ids)
1167 tdcnt = PTRACE(PT_GETNUMLWPS, m_pid, NULL, 0);
1170 tids = (lwpid_t *)malloc(tdcnt * sizeof(*tids));
1173 if (PTRACE(PT_GETLWPLIST, m_pid, (void *)tids, tdcnt) < 0) {
1177 thread_ids = std::vector<lldb::tid_t>(tids, tids + tdcnt);
1179 return thread_ids.size();
1183 ProcessMonitor::MonitorCallback(void *callback_baton,
1189 ProcessMessage message;
1190 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
1191 ProcessFreeBSD *process = monitor->m_process;
1193 bool stop_monitoring;
1194 struct ptrace_lwpinfo plwp;
1197 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1202 log->Printf ("ProcessMonitor::%s() got exit signal, tid = %" PRIu64, __FUNCTION__, pid);
1203 message = ProcessMessage::Exit(pid, status);
1204 process->SendMessage(message);
1205 return pid == process->GetID();
1208 if (!monitor->GetLwpInfo(pid, &plwp, ptrace_err))
1209 stop_monitoring = true; // pid is gone. Bail.
1211 switch (plwp.pl_siginfo.si_signo)
1214 message = MonitorSIGTRAP(monitor, &plwp.pl_siginfo, plwp.pl_lwpid);
1218 message = MonitorSignal(monitor, &plwp.pl_siginfo, plwp.pl_lwpid);
1222 process->SendMessage(message);
1223 stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage;
1226 return stop_monitoring;
1230 ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
1231 const siginfo_t *info, lldb::tid_t tid)
1233 ProcessMessage message;
1235 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1238 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1240 switch (info->si_code)
1243 assert(false && "Unexpected SIGTRAP code!");
1246 case (SIGTRAP /* | (PTRACE_EVENT_EXIT << 8) */):
1248 // The inferior process is about to exit. Maintain the process in a
1249 // state of "limbo" until we are explicitly commanded to detach,
1250 // destroy, resume, etc.
1251 unsigned long data = 0;
1252 if (!monitor->GetEventMessage(tid, &data))
1255 log->Printf ("ProcessMonitor::%s() received exit? event, data = %lx, tid = %" PRIu64, __FUNCTION__, data, tid);
1256 message = ProcessMessage::Limbo(tid, (data >> 8));
1263 log->Printf ("ProcessMonitor::%s() received trace event, tid = %" PRIu64 " : si_code = %d", __FUNCTION__, tid, info->si_code);
1264 message = ProcessMessage::Trace(tid);
1270 log->Printf ("ProcessMonitor::%s() received breakpoint event, tid = %" PRIu64, __FUNCTION__, tid);
1271 message = ProcessMessage::Break(tid);
1279 ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
1280 const siginfo_t *info, lldb::tid_t tid)
1282 ProcessMessage message;
1283 int signo = info->si_signo;
1285 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1287 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1288 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1289 // kill(2) or raise(3). Similarly for tgkill(2) on FreeBSD.
1291 // IOW, user generated signals never generate what we consider to be a
1294 // Similarly, ACK signals generated by this monitor.
1295 if (info->si_code == SI_USER)
1298 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
1300 monitor->m_process->GetUnixSignals().GetSignalAsCString (signo),
1303 if (info->si_pid == getpid())
1304 return ProcessMessage::SignalDelivered(tid, signo);
1306 return ProcessMessage::Signal(tid, signo);
1310 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals().GetSignalAsCString (signo));
1318 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1319 const auto reason = GetCrashReason(*info);
1320 return ProcessMessage::Crash(tid, reason, signo, fault_addr);
1323 // Everything else is "normal" and does not require any special action on
1325 return ProcessMessage::Signal(tid, signo);
1329 ProcessMonitor::ServeOperation(OperationArgs *args)
1331 ProcessMonitor *monitor = args->m_monitor;
1333 // We are finised with the arguments and are ready to go. Sync with the
1334 // parent thread and start serving operations on the inferior.
1335 sem_post(&args->m_semaphore);
1339 // wait for next pending operation
1340 sem_wait(&monitor->m_operation_pending);
1342 monitor->m_operation->Execute(monitor);
1344 // notify calling thread that operation is complete
1345 sem_post(&monitor->m_operation_done);
1350 ProcessMonitor::DoOperation(Operation *op)
1352 Mutex::Locker lock(m_operation_mutex);
1356 // notify operation thread that an operation is ready to be processed
1357 sem_post(&m_operation_pending);
1359 // wait for operation to complete
1360 sem_wait(&m_operation_done);
1364 ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1368 ReadOperation op(vm_addr, buf, size, error, result);
1374 ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1375 lldb_private::Error &error)
1378 WriteOperation op(vm_addr, buf, size, error, result);
1384 ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
1385 unsigned size, RegisterValue &value)
1388 ReadRegOperation op(tid, offset, size, value, result);
1394 ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
1395 const char* reg_name, const RegisterValue &value)
1398 WriteRegOperation op(tid, offset, value, result);
1404 ProcessMonitor::ReadDebugRegisterValue(lldb::tid_t tid, unsigned offset,
1405 const char *reg_name, unsigned size,
1406 lldb_private::RegisterValue &value)
1409 ReadDebugRegOperation op(tid, offset, size, value, result);
1415 ProcessMonitor::WriteDebugRegisterValue(lldb::tid_t tid, unsigned offset,
1416 const char *reg_name,
1417 const lldb_private::RegisterValue &value)
1420 WriteDebugRegOperation op(tid, offset, value, result);
1426 ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
1429 ReadGPROperation op(tid, buf, result);
1435 ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
1438 ReadFPROperation op(tid, buf, result);
1444 ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1450 ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
1453 WriteGPROperation op(tid, buf, result);
1459 ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
1462 WriteFPROperation op(tid, buf, result);
1468 ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
1474 ProcessMonitor::ReadThreadPointer(lldb::tid_t tid, lldb::addr_t &value)
1480 ProcessMonitor::Resume(lldb::tid_t unused, uint32_t signo)
1483 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1486 const char *signame = m_process->GetUnixSignals().GetSignalAsCString (signo);
1487 if (signame == nullptr)
1489 log->Printf("ProcessMonitor::%s() resuming pid %" PRIu64 " with signal %s",
1490 __FUNCTION__, GetPID(), signame);
1492 ResumeOperation op(signo, result);
1495 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
1500 ProcessMonitor::SingleStep(lldb::tid_t unused, uint32_t signo)
1503 SingleStepOperation op(signo, result);
1509 ProcessMonitor::Kill()
1512 KillOperation op(result);
1518 ProcessMonitor::GetLwpInfo(lldb::tid_t tid, void *lwpinfo, int &ptrace_err)
1521 LwpInfoOperation op(tid, lwpinfo, result, ptrace_err);
1527 ProcessMonitor::ThreadSuspend(lldb::tid_t tid, bool suspend)
1530 ThreadSuspendOperation op(tid, suspend, result);
1536 ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
1539 EventMessageOperation op(tid, message, result);
1545 ProcessMonitor::Detach(lldb::tid_t tid)
1547 lldb_private::Error error;
1548 if (tid != LLDB_INVALID_THREAD_ID)
1550 DetachOperation op(error);
1557 ProcessMonitor::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
1559 int target_fd = open(file_spec.GetCString(), flags, 0666);
1561 if (target_fd == -1)
1564 if (dup2(target_fd, fd) == -1)
1567 return (close(target_fd) == -1) ? false : true;
1571 ProcessMonitor::StopMonitoringChildProcess()
1573 if (m_monitor_thread.IsJoinable())
1575 m_monitor_thread.Cancel();
1576 m_monitor_thread.Join(nullptr);
1577 m_monitor_thread.Reset();
1582 ProcessMonitor::StopMonitor()
1584 StopMonitoringChildProcess();
1586 sem_destroy(&m_operation_pending);
1587 sem_destroy(&m_operation_done);
1588 if (m_terminal_fd >= 0) {
1589 close(m_terminal_fd);
1594 // FIXME: On Linux, when a new thread is created, we receive to notifications,
1595 // (1) a SIGTRAP|PTRACE_EVENT_CLONE from the main process thread with the
1596 // child thread id as additional information, and (2) a SIGSTOP|SI_USER from
1597 // the new child thread indicating that it has is stopped because we attached.
1598 // We have no guarantee of the order in which these arrive, but we need both
1599 // before we are ready to proceed. We currently keep a list of threads which
1600 // have sent the initial SIGSTOP|SI_USER event. Then when we receive the
1601 // SIGTRAP|PTRACE_EVENT_CLONE notification, if the initial stop has not occurred
1602 // we call ProcessMonitor::WaitForInitialTIDStop() to wait for it.
1604 // Right now, the above logic is in ProcessPOSIX, so we need a definition of
1605 // this function in the FreeBSD ProcessMonitor implementation even if it isn't
1606 // logically needed.
1608 // We really should figure out what actually happens on FreeBSD and move the
1609 // Linux-specific logic out of ProcessPOSIX as needed.
1612 ProcessMonitor::WaitForInitialTIDStop(lldb::tid_t tid)
1618 ProcessMonitor::StopOpThread()
1620 if (!m_operation_thread.IsJoinable())
1623 m_operation_thread.Cancel();
1624 m_operation_thread.Join(nullptr);
1625 m_operation_thread.Reset();