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 <mutex>
19 #include <unordered_map>
20 #include <unordered_set>
21 
22 // Other libraries and framework includes
23 #include "lldb/Core/ArchSpec.h"
24 #include "lldb/lldb-types.h"
25 #include "lldb/Host/Debug.h"
26 #include "lldb/Host/HostThread.h"
27 #include "lldb/Host/Mutex.h"
28 #include "lldb/Target/MemoryRegionInfo.h"
29 
30 #include "lldb/Host/common/NativeProcessProtocol.h"
31 #include "NativeThreadLinux.h"
32 
33 namespace lldb_private {
34     class Error;
35     class Module;
36     class Scalar;
37 
38 namespace process_linux {
39     /// @class NativeProcessLinux
40     /// @brief Manages communication with the inferior (debugee) process.
41     ///
42     /// Upon construction, this class prepares and launches an inferior process for
43     /// debugging.
44     ///
45     /// Changes in the inferior process state are broadcasted.
46     class NativeProcessLinux: public NativeProcessProtocol
47     {
48     public:
49 
50         static Error
51         LaunchProcess (
52             Module *exe_module,
53             ProcessLaunchInfo &launch_info,
54             NativeProcessProtocol::NativeDelegate &native_delegate,
55             NativeProcessProtocolSP &native_process_sp);
56 
57         static Error
58         AttachToProcess (
59             lldb::pid_t pid,
60             NativeProcessProtocol::NativeDelegate &native_delegate,
61             NativeProcessProtocolSP &native_process_sp);
62 
63         // ---------------------------------------------------------------------
64         // NativeProcessProtocol Interface
65         // ---------------------------------------------------------------------
66         Error
67         Resume (const ResumeActionList &resume_actions) override;
68 
69         Error
70         Halt () override;
71 
72         Error
73         Detach () override;
74 
75         Error
76         Signal (int signo) override;
77 
78         Error
79         Interrupt () override;
80 
81         Error
82         Kill () override;
83 
84         Error
85         GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info) override;
86 
87         Error
88         ReadMemory(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) override;
89 
90         Error
91         ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) override;
92 
93         Error
94         WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written) override;
95 
96         Error
97         AllocateMemory(size_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         Error
115         SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware) override;
116 
117         Error
118         RemoveWatchpoint (lldb::addr_t addr) override;
119 
120         void
121         DoStopIDBumped (uint32_t newBumpId) override;
122 
123         void
124         Terminate () override;
125 
126         // ---------------------------------------------------------------------
127         // Interface used by NativeRegisterContext-derived classes.
128         // ---------------------------------------------------------------------
129 
130         /// Reads the contents from the register identified by the given (architecture
131         /// dependent) offset.
132         ///
133         /// This method is provided for use by RegisterContextLinux derivatives.
134         Error
135         ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char *reg_name,
136                           unsigned size, RegisterValue &value);
137 
138         /// Writes the given value to the register identified by the given
139         /// (architecture dependent) offset.
140         ///
141         /// This method is provided for use by RegisterContextLinux derivatives.
142         Error
143         WriteRegisterValue(lldb::tid_t tid, unsigned offset, const char *reg_name,
144                            const RegisterValue &value);
145 
146         /// Reads all general purpose registers into the specified buffer.
147         Error
148         ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size);
149 
150         /// Reads generic floating point registers into the specified buffer.
151         Error
152         ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size);
153 
154         /// Reads hardware breakpoints and watchpoints capability information.
155         Error
156         ReadHardwareDebugInfo (lldb::tid_t tid, unsigned int &watch_count ,
157                                unsigned int &break_count);
158 
159         /// Write hardware breakpoint/watchpoint control and address registers.
160         Error
161         WriteHardwareDebugRegs (lldb::tid_t tid, lldb::addr_t *addr_buf,
162                                 uint32_t *cntrl_buf, int type, int count);
163 
164         /// Reads the specified register set into the specified buffer.
165         /// For instance, the extended floating-point register set.
166         Error
167         ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset);
168 
169         /// Writes all general purpose registers into the specified buffer.
170         Error
171         WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size);
172 
173         /// Writes generic floating point registers into the specified buffer.
174         Error
175         WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size);
176 
177         /// Writes the specified register set into the specified buffer.
178         /// For instance, the extended floating-point register set.
179         Error
180         WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset);
181 
182         Error
183         GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec) override;
184 
185     protected:
186         // ---------------------------------------------------------------------
187         // NativeProcessProtocol protected interface
188         // ---------------------------------------------------------------------
189         Error
190         GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes) override;
191 
192     private:
193 
194         class Monitor;
195 
196         ArchSpec m_arch;
197 
198         std::unique_ptr<Monitor> m_monitor_up;
199 
200         LazyBool m_supports_mem_region;
201         std::vector<MemoryRegionInfo> m_mem_region_cache;
202         Mutex m_mem_region_cache_mutex;
203 
204         // List of thread ids stepping with a breakpoint with the address of
205         // the relevan breakpoint
206         std::map<lldb::tid_t, lldb::addr_t> m_threads_stepping_with_breakpoint;
207 
208         /// @class LauchArgs
209         ///
210         /// @brief Simple structure to pass data to the thread responsible for
211         /// launching a child process.
212         struct LaunchArgs
213         {
214             LaunchArgs(Module *module,
215                     char const **argv,
216                     char const **envp,
217                     const std::string &stdin_path,
218                     const std::string &stdout_path,
219                     const std::string &stderr_path,
220                     const char *working_dir,
221                     const ProcessLaunchInfo &launch_info);
222 
223             ~LaunchArgs();
224 
225             Module *m_module;                 // The executable image to launch.
226             char const **m_argv;              // Process arguments.
227             char const **m_envp;              // Process environment.
228             const std::string &m_stdin_path;  // Redirect stdin if not empty.
229             const std::string &m_stdout_path; // Redirect stdout if not empty.
230             const std::string &m_stderr_path; // Redirect stderr if not empty.
231             const char *m_working_dir;        // Working directory or NULL.
232             const ProcessLaunchInfo &m_launch_info;
233         };
234 
235         typedef std::function<::pid_t(Error &)> InitialOperation;
236 
237         // ---------------------------------------------------------------------
238         // Private Instance Methods
239         // ---------------------------------------------------------------------
240         NativeProcessLinux ();
241 
242         /// Launches an inferior process ready for debugging.  Forms the
243         /// implementation of Process::DoLaunch.
244         void
245         LaunchInferior (
246             Module *module,
247             char const *argv[],
248             char const *envp[],
249             const std::string &stdin_path,
250             const std::string &stdout_path,
251             const std::string &stderr_path,
252             const char *working_dir,
253             const ProcessLaunchInfo &launch_info,
254             Error &error);
255 
256         /// Attaches to an existing process.  Forms the
257         /// implementation of Process::DoAttach
258         void
259         AttachToInferior (lldb::pid_t pid, Error &error);
260 
261         void
262         StartMonitorThread(const InitialOperation &operation, Error &error);
263 
264         ::pid_t
265         Launch(LaunchArgs *args, Error &error);
266 
267         ::pid_t
268         Attach(lldb::pid_t pid, Error &error);
269 
270         static Error
271         SetDefaultPtraceOpts(const lldb::pid_t);
272 
273         static bool
274         DupDescriptor(const char *path, int fd, int flags);
275 
276         static void *
277         MonitorThread(void *baton);
278 
279         void
280         MonitorCallback(lldb::pid_t pid, bool exited, int signal, int status);
281 
282         void
283         WaitForNewThread(::pid_t tid);
284 
285         void
286         MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid);
287 
288         void
289         MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp);
290 
291         void
292         MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp);
293 
294         void
295         MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index);
296 
297         void
298         MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited);
299 
300         bool
301         SupportHardwareSingleStepping() const;
302 
303         Error
304         SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp);
305 
306 #if 0
307         static ::ProcessMessage::CrashReason
308         GetCrashReasonForSIGSEGV(const siginfo_t *info);
309 
310         static ::ProcessMessage::CrashReason
311         GetCrashReasonForSIGILL(const siginfo_t *info);
312 
313         static ::ProcessMessage::CrashReason
314         GetCrashReasonForSIGFPE(const siginfo_t *info);
315 
316         static ::ProcessMessage::CrashReason
317         GetCrashReasonForSIGBUS(const siginfo_t *info);
318 #endif
319 
320         bool
321         HasThreadNoLock (lldb::tid_t thread_id);
322 
323         NativeThreadProtocolSP
324         MaybeGetThreadNoLock (lldb::tid_t thread_id);
325 
326         bool
327         StopTrackingThread (lldb::tid_t thread_id);
328 
329         NativeThreadProtocolSP
330         AddThread (lldb::tid_t thread_id);
331 
332         Error
333         GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size);
334 
335         Error
336         FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp);
337 
338         /// Writes a siginfo_t structure corresponding to the given thread ID to the
339         /// memory region pointed to by @p siginfo.
340         Error
341         GetSignalInfo(lldb::tid_t tid, void *siginfo);
342 
343         /// Writes the raw event message code (vis-a-vis PTRACE_GETEVENTMSG)
344         /// corresponding to the given thread ID to the memory pointed to by @p
345         /// message.
346         Error
347         GetEventMessage(lldb::tid_t tid, unsigned long *message);
348 
349         /// Resumes the given thread.  If @p signo is anything but
350         /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread.
351         Error
352         Resume(lldb::tid_t tid, uint32_t signo);
353 
354         /// Single steps the given thread.  If @p signo is anything but
355         /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread.
356         Error
357         SingleStep(lldb::tid_t tid, uint32_t signo);
358 
359         void
360         NotifyThreadDeath (lldb::tid_t tid);
361 
362         Error
363         Detach(lldb::tid_t tid);
364 
365 
366         // Typedefs.
367         typedef std::unordered_set<lldb::tid_t> ThreadIDSet;
368 
369         // This method is requests a stop on all threads which are still running. It sets up a
370         // deferred delegate notification, which will fire once threads report as stopped. The
371         // triggerring_tid will be set as the current thread (main stop reason).
372         void
373         StopRunningThreads(lldb::tid_t triggering_tid);
374 
375         struct PendingNotification
376         {
377             PendingNotification (lldb::tid_t triggering_tid):
378                 triggering_tid (triggering_tid),
379                 wait_for_stop_tids ()
380             {
381             }
382 
383             const lldb::tid_t  triggering_tid;
384             ThreadIDSet        wait_for_stop_tids;
385         };
386         typedef std::unique_ptr<PendingNotification> PendingNotificationUP;
387 
388         // Notify the delegate if all threads have stopped.
389         void SignalIfAllThreadsStopped();
390 
391         void
392         RequestStopOnAllRunningThreads();
393 
394         Error
395         ThreadDidStop(lldb::tid_t tid, bool initiated_by_llgs);
396 
397         // Resume the thread with the given thread id using the request_thread_resume_function
398         // called. If error_when_already_running is then then an error is raised if we think this
399         // thread is already running.
400         Error
401         ResumeThread(lldb::tid_t tid, NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
402                 bool error_when_already_running);
403 
404         void
405         DoStopThreads(PendingNotificationUP &&notification_up);
406 
407         void
408         ThreadWasCreated (lldb::tid_t tid);
409 
410         // Member variables.
411         PendingNotificationUP m_pending_notification_up;
412     };
413 
414 } // namespace process_linux
415 } // namespace lldb_private
416 
417 #endif // #ifndef liblldb_NativeProcessLinux_H_
418