1 //===-- NativeProcessLinux.h ---------------------------------- -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #ifndef liblldb_NativeProcessLinux_H_
11 #define liblldb_NativeProcessLinux_H_
12 
13 // C Includes
14 #include <semaphore.h>
15 #include <signal.h>
16 
17 // C++ Includes
18 #include <unordered_set>
19 
20 // Other libraries and framework includes
21 #include "lldb/Core/ArchSpec.h"
22 #include "lldb/lldb-types.h"
23 #include "lldb/Host/Debug.h"
24 #include "lldb/Host/HostThread.h"
25 #include "lldb/Host/Mutex.h"
26 #include "lldb/Target/MemoryRegionInfo.h"
27 
28 #include "Host/common/NativeProcessProtocol.h"
29 
30 namespace lldb_private
31 {
32     class Error;
33     class Module;
34     class Scalar;
35 
36     /// @class NativeProcessLinux
37     /// @brief Manages communication with the inferior (debugee) process.
38     ///
39     /// Upon construction, this class prepares and launches an inferior process for
40     /// debugging.
41     ///
42     /// Changes in the inferior process state are broadcasted.
43     class NativeProcessLinux: public NativeProcessProtocol
44     {
45     public:
46 
47         // ---------------------------------------------------------------------
48         // Public Static Methods
49         // ---------------------------------------------------------------------
50         static lldb_private::Error
51         LaunchProcess (
52             Module *exe_module,
53             ProcessLaunchInfo &launch_info,
54             lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
55             NativeProcessProtocolSP &native_process_sp);
56 
57         static lldb_private::Error
58         AttachToProcess (
59             lldb::pid_t pid,
60             lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
61             NativeProcessProtocolSP &native_process_sp);
62 
63         // ---------------------------------------------------------------------
64         // Public Instance Methods
65         // ---------------------------------------------------------------------
66 
67         ~NativeProcessLinux() override;
68 
69         // ---------------------------------------------------------------------
70         // NativeProcessProtocol Interface
71         // ---------------------------------------------------------------------
72         Error
73         Resume (const ResumeActionList &resume_actions) override;
74 
75         Error
76         Halt () override;
77 
78         Error
79         Detach () override;
80 
81         Error
82         Signal (int signo) override;
83 
84         Error
85         Kill () override;
86 
87         Error
88         GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info) override;
89 
90         Error
91         ReadMemory (lldb::addr_t addr, void *buf, lldb::addr_t size, lldb::addr_t &bytes_read) override;
92 
93         Error
94         WriteMemory (lldb::addr_t addr, const void *buf, lldb::addr_t size, lldb::addr_t &bytes_written) override;
95 
96         Error
97         AllocateMemory (lldb::addr_t size, uint32_t permissions, lldb::addr_t &addr) override;
98 
99         Error
100         DeallocateMemory (lldb::addr_t addr) override;
101 
102         lldb::addr_t
103         GetSharedLibraryInfoAddress () override;
104 
105         size_t
106         UpdateThreads () override;
107 
108         bool
109         GetArchitecture (ArchSpec &arch) const override;
110 
111         Error
112         SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware) override;
113 
114         void
115         DoStopIDBumped (uint32_t newBumpId) override;
116 
117         // ---------------------------------------------------------------------
118         // Interface used by NativeRegisterContext-derived classes.
119         // ---------------------------------------------------------------------
120 
121         /// Reads the contents from the register identified by the given (architecture
122         /// dependent) offset.
123         ///
124         /// This method is provided for use by RegisterContextLinux derivatives.
125         bool
126         ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char *reg_name,
127                           unsigned size, lldb_private::RegisterValue &value);
128 
129         /// Writes the given value to the register identified by the given
130         /// (architecture dependent) offset.
131         ///
132         /// This method is provided for use by RegisterContextLinux derivatives.
133         bool
134         WriteRegisterValue(lldb::tid_t tid, unsigned offset, const char *reg_name,
135                            const lldb_private::RegisterValue &value);
136 
137         /// Reads all general purpose registers into the specified buffer.
138         bool
139         ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size);
140 
141         /// Reads generic floating point registers into the specified buffer.
142         bool
143         ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size);
144 
145         /// Reads the specified register set into the specified buffer.
146         /// For instance, the extended floating-point register set.
147         bool
148         ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset);
149 
150         /// Writes all general purpose registers into the specified buffer.
151         bool
152         WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size);
153 
154         /// Writes generic floating point registers into the specified buffer.
155         bool
156         WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size);
157 
158         /// Writes the specified register set into the specified buffer.
159         /// For instance, the extended floating-point register set.
160         bool
161         WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset);
162 
163     protected:
164         // ---------------------------------------------------------------------
165         // NativeProcessProtocol protected interface
166         // ---------------------------------------------------------------------
167         Error
168         GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes) override;
169 
170     private:
171 
172         lldb_private::ArchSpec m_arch;
173 
174         HostThread m_operation_thread;
175         HostThread m_monitor_thread;
176 
177         // current operation which must be executed on the priviliged thread
178         void *m_operation;
179         lldb_private::Mutex m_operation_mutex;
180 
181         // semaphores notified when Operation is ready to be processed and when
182         // the operation is complete.
183         sem_t m_operation_pending;
184         sem_t m_operation_done;
185 
186         // Set of tids we're waiting to stop before we notify the delegate of
187         // the stopped state.  We only notify the delegate after all threads
188         // ordered to stop have signaled their stop.
189         std::unordered_set<lldb::tid_t> m_wait_for_stop_tids;
190         lldb_private::Mutex m_wait_for_stop_tids_mutex;
191 
192         std::unordered_set<lldb::tid_t> m_wait_for_group_stop_tids;
193         lldb::tid_t m_group_stop_signal_tid;
194         int m_group_stop_signal;
195         lldb_private::Mutex m_wait_for_group_stop_tids_mutex;
196 
197         lldb_private::LazyBool m_supports_mem_region;
198         std::vector<MemoryRegionInfo> m_mem_region_cache;
199         lldb_private::Mutex m_mem_region_cache_mutex;
200 
201 
202         struct OperationArgs
203         {
204             OperationArgs(NativeProcessLinux *monitor);
205 
206             ~OperationArgs();
207 
208             NativeProcessLinux *m_monitor;      // The monitor performing the attach.
209             sem_t m_semaphore;              // Posted to once operation complete.
210             lldb_private::Error m_error;    // Set if process operation failed.
211         };
212 
213         /// @class LauchArgs
214         ///
215         /// @brief Simple structure to pass data to the thread responsible for
216         /// launching a child process.
217         struct LaunchArgs : OperationArgs
218         {
219             LaunchArgs(NativeProcessLinux *monitor,
220                     lldb_private::Module *module,
221                     char const **argv,
222                     char const **envp,
223                     const std::string &stdin_path,
224                     const std::string &stdout_path,
225                     const std::string &stderr_path,
226                     const char *working_dir,
227                     const lldb_private::ProcessLaunchInfo &launch_info);
228 
229             ~LaunchArgs();
230 
231             lldb_private::Module *m_module; // The executable image to launch.
232             char const **m_argv;            // Process arguments.
233             char const **m_envp;            // Process environment.
234             const std::string &m_stdin_path;  // Redirect stdin if not empty.
235             const std::string &m_stdout_path; // Redirect stdout if not empty.
236             const std::string &m_stderr_path; // Redirect stderr if not empty.
237             const char *m_working_dir;      // Working directory or NULL.
238             const lldb_private::ProcessLaunchInfo &m_launch_info;
239         };
240 
241         struct AttachArgs : OperationArgs
242         {
243             AttachArgs(NativeProcessLinux *monitor,
244                        lldb::pid_t pid);
245 
246             ~AttachArgs();
247 
248             lldb::pid_t m_pid;              // pid of the process to be attached.
249         };
250 
251         // ---------------------------------------------------------------------
252         // Private Instance Methods
253         // ---------------------------------------------------------------------
254         NativeProcessLinux ();
255 
256         /// Launches an inferior process ready for debugging.  Forms the
257         /// implementation of Process::DoLaunch.
258         void
259         LaunchInferior (
260             Module *module,
261             char const *argv[],
262             char const *envp[],
263             const std::string &stdin_path,
264             const std::string &stdout_path,
265             const std::string &stderr_path,
266             const char *working_dir,
267             const lldb_private::ProcessLaunchInfo &launch_info,
268             Error &error);
269 
270         /// Attaches to an existing process.  Forms the
271         /// implementation of Process::DoLaunch.
272         void
273         AttachToInferior (lldb::pid_t pid, Error &error);
274 
275         void
276         StartLaunchOpThread(LaunchArgs *args, lldb_private::Error &error);
277 
278         static void *
279         LaunchOpThread(void *arg);
280 
281         static bool
282         Launch(LaunchArgs *args);
283 
284         void
285         StartAttachOpThread(AttachArgs *args, lldb_private::Error &error);
286 
287         static void *
288         AttachOpThread(void *args);
289 
290         static bool
291         Attach(AttachArgs *args);
292 
293         static bool
294         SetDefaultPtraceOpts(const lldb::pid_t);
295 
296         static void
297         ServeOperation(OperationArgs *args);
298 
299         static bool
300         DupDescriptor(const char *path, int fd, int flags);
301 
302         static bool
303         MonitorCallback(void *callback_baton,
304                 lldb::pid_t pid, bool exited, int signal, int status);
305 
306         void
307         MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid);
308 
309         void
310         MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited);
311 
312 #if 0
313         static ::ProcessMessage::CrashReason
314         GetCrashReasonForSIGSEGV(const siginfo_t *info);
315 
316         static ::ProcessMessage::CrashReason
317         GetCrashReasonForSIGILL(const siginfo_t *info);
318 
319         static ::ProcessMessage::CrashReason
320         GetCrashReasonForSIGFPE(const siginfo_t *info);
321 
322         static ::ProcessMessage::CrashReason
323         GetCrashReasonForSIGBUS(const siginfo_t *info);
324 #endif
325 
326         void
327         DoOperation(void *op);
328 
329         /// Stops the child monitor thread.
330         void
331         StopMonitoringChildProcess();
332 
333         /// Stops the operation thread used to attach/launch a process.
334         void
335         StopOpThread();
336 
337         /// Stops monitoring the child process thread.
338         void
339         StopMonitor();
340 
341         bool
342         HasThreadNoLock (lldb::tid_t thread_id);
343 
344         NativeThreadProtocolSP
345         MaybeGetThreadNoLock (lldb::tid_t thread_id);
346 
347         bool
348         StopTrackingThread (lldb::tid_t thread_id);
349 
350         NativeThreadProtocolSP
351         AddThread (lldb::tid_t thread_id);
352 
353         NativeThreadProtocolSP
354         GetOrCreateThread (lldb::tid_t thread_id, bool &created);
355 
356         Error
357         GetSoftwareBreakpointSize (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size);
358 
359         Error
360         FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp);
361 
362         /// Writes a siginfo_t structure corresponding to the given thread ID to the
363         /// memory region pointed to by @p siginfo.
364         bool
365         GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err);
366 
367         /// Writes the raw event message code (vis-a-vis PTRACE_GETEVENTMSG)
368         /// corresponding to the given thread ID to the memory pointed to by @p
369         /// message.
370         bool
371         GetEventMessage(lldb::tid_t tid, unsigned long *message);
372 
373         /// Resumes the given thread.  If @p signo is anything but
374         /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread.
375         bool
376         Resume(lldb::tid_t tid, uint32_t signo);
377 
378         /// Single steps the given thread.  If @p signo is anything but
379         /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread.
380         bool
381         SingleStep(lldb::tid_t tid, uint32_t signo);
382 
383         /// Safely mark all existing threads as waiting for group stop.
384         /// When the final group stop comes in from the set of group stop threads,
385         /// we'll mark the current thread as signaled_thread_tid and set its stop
386         /// reason as the given signo.  All other threads from group stop notification
387         /// will have thread stop reason marked as signaled with no signo.
388         void
389         SetGroupStopTids (lldb::tid_t signaled_thread_tid, int signo);
390 
391         void
392         OnGroupStop (lldb::tid_t tid);
393 
394         lldb_private::Error
395         Detach(lldb::tid_t tid);
396     };
397 } // End lldb_private namespace.
398 
399 #endif // #ifndef liblldb_NativeProcessLinux_H_
400