1 //===-- ProcessMonitor.h -------------------------------------- -*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef liblldb_ProcessMonitor_H_
10 #define liblldb_ProcessMonitor_H_
11 
12 #include <semaphore.h>
13 #include <signal.h>
14 
15 #include <mutex>
16 
17 #include "lldb/Host/HostThread.h"
18 #include "lldb/Utility/FileSpec.h"
19 #include "lldb/lldb-types.h"
20 
21 namespace lldb_private {
22 class Status;
23 class Module;
24 class Scalar;
25 } // End lldb_private namespace.
26 
27 class ProcessFreeBSD;
28 class Operation;
29 
30 /// \class ProcessMonitor
31 /// Manages communication with the inferior (debugee) process.
32 ///
33 /// Upon construction, this class prepares and launches an inferior process
34 /// for debugging.
35 ///
36 /// Changes in the inferior process state are propagated to the associated
37 /// ProcessFreeBSD instance by calling ProcessFreeBSD::SendMessage with the
38 /// appropriate ProcessMessage events.
39 ///
40 /// A purposely minimal set of operations are provided to interrogate and change
41 /// the inferior process state.
42 class ProcessMonitor {
43 public:
44   /// Launches an inferior process ready for debugging.  Forms the
45   /// implementation of Process::DoLaunch.
46   ProcessMonitor(ProcessFreeBSD *process, lldb_private::Module *module,
47                  char const *argv[], lldb_private::Environment env,
48                  const lldb_private::FileSpec &stdin_file_spec,
49                  const lldb_private::FileSpec &stdout_file_spec,
50                  const lldb_private::FileSpec &stderr_file_spec,
51                  const lldb_private::FileSpec &working_dir,
52                  const lldb_private::ProcessLaunchInfo &launch_info,
53                  lldb_private::Status &error);
54 
55   ProcessMonitor(ProcessFreeBSD *process, lldb::pid_t pid,
56                  lldb_private::Status &error);
57 
58   ~ProcessMonitor();
59 
60   /// Provides the process number of debugee.
GetPID()61   lldb::pid_t GetPID() const { return m_pid; }
62 
63   /// Returns the process associated with this ProcessMonitor.
GetProcess()64   ProcessFreeBSD &GetProcess() { return *m_process; }
65 
66   /// Returns a file descriptor to the controlling terminal of the inferior
67   /// process.
68   ///
69   /// Reads from this file descriptor yield both the standard output and
70   /// standard error of this debugee.  Even if stderr and stdout were
71   /// redirected on launch it may still happen that data is available on this
72   /// descriptor (if the inferior process opens /dev/tty, for example). This
73   /// descriptor is closed after a call to StopMonitor().
74   ///
75   /// If this monitor was attached to an existing process this method returns
76   /// -1.
GetTerminalFD()77   int GetTerminalFD() const { return m_terminal_fd; }
78 
79   /// Reads \p size bytes from address @vm_adder in the inferior process
80   /// address space.
81   ///
82   /// This method is provided to implement Process::DoReadMemory.
83   size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
84                     lldb_private::Status &error);
85 
86   /// Writes \p size bytes from address \p vm_adder in the inferior process
87   /// address space.
88   ///
89   /// This method is provided to implement Process::DoWriteMemory.
90   size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
91                      lldb_private::Status &error);
92 
93   /// Reads the contents from the register identified by the given
94   /// (architecture dependent) offset.
95   ///
96   /// This method is provided for use by RegisterContextFreeBSD derivatives.
97   bool ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char *reg_name,
98                          unsigned size, lldb_private::RegisterValue &value);
99 
100   /// Writes the given value to the register identified by the given
101   /// (architecture dependent) offset.
102   ///
103   /// This method is provided for use by RegisterContextFreeBSD derivatives.
104   bool WriteRegisterValue(lldb::tid_t tid, unsigned offset,
105                           const char *reg_name,
106                           const lldb_private::RegisterValue &value);
107 
108   /// Reads the contents from the debug register identified by the given
109   /// (architecture dependent) offset.
110   ///
111   /// This method is provided for use by RegisterContextFreeBSD derivatives.
112   bool ReadDebugRegisterValue(lldb::tid_t tid, unsigned offset,
113                               const char *reg_name, unsigned size,
114                               lldb_private::RegisterValue &value);
115 
116   /// Writes the given value to the debug register identified by the given
117   /// (architecture dependent) offset.
118   ///
119   /// This method is provided for use by RegisterContextFreeBSD derivatives.
120   bool WriteDebugRegisterValue(lldb::tid_t tid, unsigned offset,
121                                const char *reg_name,
122                                const lldb_private::RegisterValue &value);
123   /// Reads all general purpose registers into the specified buffer.
124   bool ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size);
125 
126   /// Reads all floating point registers into the specified buffer.
127   bool ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size);
128 
129   /// Reads the specified register set into the specified buffer.
130   ///
131   /// This method is provided for use by RegisterContextFreeBSD derivatives.
132   bool ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size,
133                        unsigned int regset);
134 
135   /// Writes all general purpose registers into the specified buffer.
136   bool WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size);
137 
138   /// Writes all floating point registers into the specified buffer.
139   bool WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size);
140 
141   /// Writes the specified register set into the specified buffer.
142   ///
143   /// This method is provided for use by RegisterContextFreeBSD derivatives.
144   bool WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size,
145                         unsigned int regset);
146 
147   /// Reads the value of the thread-specific pointer for a given thread ID.
148   bool ReadThreadPointer(lldb::tid_t tid, lldb::addr_t &value);
149 
150   /// Returns current thread IDs in process
151   size_t GetCurrentThreadIDs(std::vector<lldb::tid_t> &thread_ids);
152 
153   /// Writes a ptrace_lwpinfo structure corresponding to the given thread ID
154   /// to the memory region pointed to by \p lwpinfo.
155   bool GetLwpInfo(lldb::tid_t tid, void *lwpinfo, int &error_no);
156 
157   /// Suspends or unsuspends a thread prior to process resume or step.
158   bool ThreadSuspend(lldb::tid_t tid, bool suspend);
159 
160   /// Writes the raw event message code (vis-a-vis PTRACE_GETEVENTMSG)
161   /// corresponding to the given thread IDto the memory pointed to by @p
162   /// message.
163   bool GetEventMessage(lldb::tid_t tid, unsigned long *message);
164 
165   /// Resumes the process.  If \p signo is anything but
166   /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the process.
167   bool Resume(lldb::tid_t unused, uint32_t signo);
168 
169   /// Single steps the process.  If \p signo is anything but
170   /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the process.
171   bool SingleStep(lldb::tid_t unused, uint32_t signo);
172 
173   /// Terminate the traced process.
174   bool Kill();
175 
176   lldb_private::Status Detach(lldb::tid_t tid);
177 
178   void StopMonitor();
179 
180   // Waits for the initial stop message from a new thread.
181   bool WaitForInitialTIDStop(lldb::tid_t tid);
182 
183 private:
184   ProcessFreeBSD *m_process;
185 
186   llvm::Optional<lldb_private::HostThread> m_operation_thread;
187   llvm::Optional<lldb_private::HostThread> m_monitor_thread;
188   lldb::pid_t m_pid;
189 
190   int m_terminal_fd;
191 
192   // current operation which must be executed on the privileged thread
193   Operation *m_operation;
194   std::mutex m_operation_mutex;
195 
196   // semaphores notified when Operation is ready to be processed and when
197   // the operation is complete.
198   sem_t m_operation_pending;
199   sem_t m_operation_done;
200 
201   struct OperationArgs {
202     OperationArgs(ProcessMonitor *monitor);
203 
204     ~OperationArgs();
205 
206     ProcessMonitor *m_monitor;   // The monitor performing the attach.
207     sem_t m_semaphore;           // Posted to once operation complete.
208     lldb_private::Status m_error; // Set if process operation failed.
209   };
210 
211   /// \class LauchArgs
212   ///
213   /// Simple structure to pass data to the thread responsible for launching a
214   /// child process.
215   struct LaunchArgs : OperationArgs {
216     LaunchArgs(ProcessMonitor *monitor, lldb_private::Module *module,
217                char const **argv, lldb_private::Environment env,
218                const lldb_private::FileSpec &stdin_file_spec,
219                const lldb_private::FileSpec &stdout_file_spec,
220                const lldb_private::FileSpec &stderr_file_spec,
221                const lldb_private::FileSpec &working_dir);
222 
223     ~LaunchArgs();
224 
225     lldb_private::Module *m_module; // The executable image to launch.
226     char const **m_argv;            // Process arguments.
227     lldb_private::Environment m_env;                // Process environment.
228     const lldb_private::FileSpec m_stdin_file_spec; // Redirect stdin or empty.
229     const lldb_private::FileSpec
230         m_stdout_file_spec; // Redirect stdout or empty.
231     const lldb_private::FileSpec
232         m_stderr_file_spec;                     // Redirect stderr or empty.
233     const lldb_private::FileSpec m_working_dir; // Working directory or empty.
234   };
235 
236   void StartLaunchOpThread(LaunchArgs *args, lldb_private::Status &error);
237 
238   static void *LaunchOpThread(void *arg);
239 
240   static bool Launch(LaunchArgs *args);
241 
242   struct AttachArgs : OperationArgs {
243     AttachArgs(ProcessMonitor *monitor, lldb::pid_t pid);
244 
245     ~AttachArgs();
246 
247     lldb::pid_t m_pid; // pid of the process to be attached.
248   };
249 
250   void StartAttachOpThread(AttachArgs *args, lldb_private::Status &error);
251 
252   static void *AttachOpThread(void *args);
253 
254   static void Attach(AttachArgs *args);
255 
256   static void ServeOperation(OperationArgs *args);
257 
258   static bool DupDescriptor(const lldb_private::FileSpec &file_spec, int fd,
259                             int flags);
260 
261   static bool MonitorCallback(ProcessMonitor *monitor, lldb::pid_t pid,
262                               bool exited, int signal, int status);
263 
264   static ProcessMessage MonitorSIGTRAP(ProcessMonitor *monitor,
265                                        const siginfo_t *info, lldb::pid_t pid);
266 
267   static ProcessMessage MonitorSignal(ProcessMonitor *monitor,
268                                       const siginfo_t *info, lldb::pid_t pid);
269 
270   void DoOperation(Operation *op);
271 
272   /// Stops the child monitor thread.
273   void StopMonitoringChildProcess();
274 
275   /// Stops the operation thread used to attach/launch a process.
276   void StopOpThread();
277 };
278 
279 #endif // #ifndef liblldb_ProcessMonitor_H_
280