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 <unordered_set>
15 
16 // Other libraries and framework includes
17 #include "lldb/Core/ArchSpec.h"
18 #include "lldb/lldb-types.h"
19 #include "lldb/Host/Debug.h"
20 #include "lldb/Host/FileSpec.h"
21 #include "lldb/Host/HostThread.h"
22 #include "lldb/Host/Mutex.h"
23 #include "lldb/Target/MemoryRegionInfo.h"
24 
25 #include "lldb/Host/common/NativeProcessProtocol.h"
26 #include "NativeThreadLinux.h"
27 
28 namespace lldb_private {
29     class Error;
30     class Module;
31     class Scalar;
32 
33 namespace process_linux {
34     /// @class NativeProcessLinux
35     /// @brief Manages communication with the inferior (debugee) process.
36     ///
37     /// Upon construction, this class prepares and launches an inferior process for
38     /// debugging.
39     ///
40     /// Changes in the inferior process state are broadcasted.
41     class NativeProcessLinux: public NativeProcessProtocol
42     {
43     public:
44 
45         static Error
46         LaunchProcess (
47             Module *exe_module,
48             ProcessLaunchInfo &launch_info,
49             NativeProcessProtocol::NativeDelegate &native_delegate,
50             NativeProcessProtocolSP &native_process_sp);
51 
52         static Error
53         AttachToProcess (
54             lldb::pid_t pid,
55             NativeProcessProtocol::NativeDelegate &native_delegate,
56             NativeProcessProtocolSP &native_process_sp);
57 
58         //------------------------------------------------------------------------------
59         /// @class Operation
60         /// @brief Represents a NativeProcessLinux operation.
61         ///
62         /// Under Linux, it is not possible to ptrace() from any other thread but the
63         /// one that spawned or attached to the process from the start.  Therefore, when
64         /// a NativeProcessLinux is asked to deliver or change the state of an inferior
65         /// process the operation must be "funneled" to a specific thread to perform the
66         /// task.
67         typedef std::function<Error()> Operation;
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         Interrupt () override;
86 
87         Error
88         Kill () override;
89 
90         Error
91         GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info) override;
92 
93         Error
94         ReadMemory(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) override;
95 
96         Error
97         ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) override;
98 
99         Error
100         WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written) override;
101 
102         Error
103         AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr) override;
104 
105         Error
106         DeallocateMemory (lldb::addr_t addr) override;
107 
108         lldb::addr_t
109         GetSharedLibraryInfoAddress () override;
110 
111         size_t
112         UpdateThreads () override;
113 
114         bool
115         GetArchitecture (ArchSpec &arch) const override;
116 
117         Error
118         SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware) override;
119 
120         Error
121         SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware) override;
122 
123         Error
124         RemoveWatchpoint (lldb::addr_t addr) override;
125 
126         void
127         DoStopIDBumped (uint32_t newBumpId) override;
128 
129         void
130         Terminate () override;
131 
132         Error
133         GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec) override;
134 
135         Error
136         GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr) override;
137 
138         // ---------------------------------------------------------------------
139         // Interface used by NativeRegisterContext-derived classes.
140         // ---------------------------------------------------------------------
141         Error
142         DoOperation(const Operation &op);
143 
144         static Error
145         PtraceWrapper(int req,
146                       lldb::pid_t pid,
147                       void *addr = nullptr,
148                       void *data = nullptr,
149                       size_t data_size = 0,
150                       long *result = nullptr);
151 
152     protected:
153         // ---------------------------------------------------------------------
154         // NativeProcessProtocol protected interface
155         // ---------------------------------------------------------------------
156         Error
157         GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes) override;
158 
159     private:
160 
161         class Monitor;
162 
163         ArchSpec m_arch;
164 
165         std::unique_ptr<Monitor> m_monitor_up;
166 
167         LazyBool m_supports_mem_region;
168         std::vector<MemoryRegionInfo> m_mem_region_cache;
169         Mutex m_mem_region_cache_mutex;
170 
171         // List of thread ids stepping with a breakpoint with the address of
172         // the relevan breakpoint
173         std::map<lldb::tid_t, lldb::addr_t> m_threads_stepping_with_breakpoint;
174 
175         /// @class LauchArgs
176         ///
177         /// @brief Simple structure to pass data to the thread responsible for
178         /// launching a child process.
179         struct LaunchArgs
180         {
181             LaunchArgs(Module *module,
182                     char const **argv,
183                     char const **envp,
184                     const FileSpec &stdin_file_spec,
185                     const FileSpec &stdout_file_spec,
186                     const FileSpec &stderr_file_spec,
187                     const FileSpec &working_dir,
188                     const ProcessLaunchInfo &launch_info);
189 
190             ~LaunchArgs();
191 
192             Module *m_module;                  // The executable image to launch.
193             char const **m_argv;               // Process arguments.
194             char const **m_envp;               // Process environment.
195             const FileSpec m_stdin_file_spec;  // Redirect stdin if not empty.
196             const FileSpec m_stdout_file_spec; // Redirect stdout if not empty.
197             const FileSpec m_stderr_file_spec; // Redirect stderr if not empty.
198             const FileSpec m_working_dir;      // Working directory or empty.
199             const ProcessLaunchInfo &m_launch_info;
200         };
201 
202         typedef std::function<::pid_t(Error &)> InitialOperation;
203 
204         // ---------------------------------------------------------------------
205         // Private Instance Methods
206         // ---------------------------------------------------------------------
207         NativeProcessLinux ();
208 
209         /// Launches an inferior process ready for debugging.  Forms the
210         /// implementation of Process::DoLaunch.
211         void
212         LaunchInferior (
213             Module *module,
214             char const *argv[],
215             char const *envp[],
216             const FileSpec &stdin_file_spec,
217             const FileSpec &stdout_file_spec,
218             const FileSpec &stderr_file_spec,
219             const FileSpec &working_dir,
220             const ProcessLaunchInfo &launch_info,
221             Error &error);
222 
223         /// Attaches to an existing process.  Forms the
224         /// implementation of Process::DoAttach
225         void
226         AttachToInferior (lldb::pid_t pid, Error &error);
227 
228         void
229         StartMonitorThread(const InitialOperation &operation, Error &error);
230 
231         ::pid_t
232         Launch(LaunchArgs *args, Error &error);
233 
234         ::pid_t
235         Attach(lldb::pid_t pid, Error &error);
236 
237         static Error
238         SetDefaultPtraceOpts(const lldb::pid_t);
239 
240         static bool
241         DupDescriptor(const FileSpec &file_spec, int fd, int flags);
242 
243         static void *
244         MonitorThread(void *baton);
245 
246         void
247         MonitorCallback(lldb::pid_t pid, bool exited, int signal, int status);
248 
249         void
250         WaitForNewThread(::pid_t tid);
251 
252         void
253         MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid);
254 
255         void
256         MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp);
257 
258         void
259         MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp);
260 
261         void
262         MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index);
263 
264         void
265         MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited);
266 
267         bool
268         SupportHardwareSingleStepping() const;
269 
270         Error
271         SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp);
272 
273 #if 0
274         static ::ProcessMessage::CrashReason
275         GetCrashReasonForSIGSEGV(const siginfo_t *info);
276 
277         static ::ProcessMessage::CrashReason
278         GetCrashReasonForSIGILL(const siginfo_t *info);
279 
280         static ::ProcessMessage::CrashReason
281         GetCrashReasonForSIGFPE(const siginfo_t *info);
282 
283         static ::ProcessMessage::CrashReason
284         GetCrashReasonForSIGBUS(const siginfo_t *info);
285 #endif
286 
287         bool
288         HasThreadNoLock (lldb::tid_t thread_id);
289 
290         NativeThreadProtocolSP
291         MaybeGetThreadNoLock (lldb::tid_t thread_id);
292 
293         bool
294         StopTrackingThread (lldb::tid_t thread_id);
295 
296         NativeThreadProtocolSP
297         AddThread (lldb::tid_t thread_id);
298 
299         Error
300         GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size);
301 
302         Error
303         FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp);
304 
305         /// Writes a siginfo_t structure corresponding to the given thread ID to the
306         /// memory region pointed to by @p siginfo.
307         Error
308         GetSignalInfo(lldb::tid_t tid, void *siginfo);
309 
310         /// Writes the raw event message code (vis-a-vis PTRACE_GETEVENTMSG)
311         /// corresponding to the given thread ID to the memory pointed to by @p
312         /// message.
313         Error
314         GetEventMessage(lldb::tid_t tid, unsigned long *message);
315 
316         /// Resumes the given thread.  If @p signo is anything but
317         /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread.
318         Error
319         Resume(lldb::tid_t tid, uint32_t signo);
320 
321         /// Single steps the given thread.  If @p signo is anything but
322         /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread.
323         Error
324         SingleStep(lldb::tid_t tid, uint32_t signo);
325 
326         void
327         NotifyThreadDeath (lldb::tid_t tid);
328 
329         Error
330         Detach(lldb::tid_t tid);
331 
332 
333         // Typedefs.
334         typedef std::unordered_set<lldb::tid_t> ThreadIDSet;
335 
336         // This method is requests a stop on all threads which are still running. It sets up a
337         // deferred delegate notification, which will fire once threads report as stopped. The
338         // triggerring_tid will be set as the current thread (main stop reason).
339         void
340         StopRunningThreads(lldb::tid_t triggering_tid);
341 
342         struct PendingNotification
343         {
344             PendingNotification (lldb::tid_t triggering_tid):
345                 triggering_tid (triggering_tid),
346                 wait_for_stop_tids ()
347             {
348             }
349 
350             const lldb::tid_t  triggering_tid;
351             ThreadIDSet        wait_for_stop_tids;
352         };
353         typedef std::unique_ptr<PendingNotification> PendingNotificationUP;
354 
355         // Notify the delegate if all threads have stopped.
356         void SignalIfAllThreadsStopped();
357 
358         void
359         RequestStopOnAllRunningThreads();
360 
361         Error
362         ThreadDidStop(lldb::tid_t tid, bool initiated_by_llgs);
363 
364         // Resume the thread with the given thread id using the request_thread_resume_function
365         // called. If error_when_already_running is then then an error is raised if we think this
366         // thread is already running.
367         Error
368         ResumeThread(lldb::tid_t tid, NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
369                 bool error_when_already_running);
370 
371         void
372         DoStopThreads(PendingNotificationUP &&notification_up);
373 
374         void
375         ThreadWasCreated (lldb::tid_t tid);
376 
377         // Member variables.
378         PendingNotificationUP m_pending_notification_up;
379     };
380 
381 } // namespace process_linux
382 } // namespace lldb_private
383 
384 #endif // #ifndef liblldb_NativeProcessLinux_H_
385