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 
32 namespace lldb_private {
33     class Error;
34     class Module;
35     class Scalar;
36 
37 namespace process_linux {
38     /// @class NativeProcessLinux
39     /// @brief Manages communication with the inferior (debugee) process.
40     ///
41     /// Upon construction, this class prepares and launches an inferior process for
42     /// debugging.
43     ///
44     /// Changes in the inferior process state are broadcasted.
45     class NativeProcessLinux: public NativeProcessProtocol
46     {
47     public:
48 
49         static Error
50         LaunchProcess (
51             Module *exe_module,
52             ProcessLaunchInfo &launch_info,
53             NativeProcessProtocol::NativeDelegate &native_delegate,
54             NativeProcessProtocolSP &native_process_sp);
55 
56         static Error
57         AttachToProcess (
58             lldb::pid_t pid,
59             NativeProcessProtocol::NativeDelegate &native_delegate,
60             NativeProcessProtocolSP &native_process_sp);
61 
62         // ---------------------------------------------------------------------
63         // NativeProcessProtocol Interface
64         // ---------------------------------------------------------------------
65         Error
66         Resume (const ResumeActionList &resume_actions) override;
67 
68         Error
69         Halt () override;
70 
71         Error
72         Detach () override;
73 
74         Error
75         Signal (int signo) override;
76 
77         Error
78         Interrupt () override;
79 
80         Error
81         Kill () override;
82 
83         Error
84         GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info) override;
85 
86         Error
87         ReadMemory(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) override;
88 
89         Error
90         ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) override;
91 
92         Error
93         WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written) override;
94 
95         Error
96         AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr) override;
97 
98         Error
99         DeallocateMemory (lldb::addr_t addr) override;
100 
101         lldb::addr_t
102         GetSharedLibraryInfoAddress () override;
103 
104         size_t
105         UpdateThreads () override;
106 
107         bool
108         GetArchitecture (ArchSpec &arch) const override;
109 
110         Error
111         SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware) override;
112 
113         Error
114         SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware) override;
115 
116         Error
117         RemoveWatchpoint (lldb::addr_t addr) override;
118 
119         void
120         DoStopIDBumped (uint32_t newBumpId) override;
121 
122         void
123         Terminate () override;
124 
125         // ---------------------------------------------------------------------
126         // Interface used by NativeRegisterContext-derived classes.
127         // ---------------------------------------------------------------------
128 
129         /// Reads the contents from the register identified by the given (architecture
130         /// dependent) offset.
131         ///
132         /// This method is provided for use by RegisterContextLinux derivatives.
133         Error
134         ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char *reg_name,
135                           unsigned size, RegisterValue &value);
136 
137         /// Writes the given value to the register identified by the given
138         /// (architecture dependent) offset.
139         ///
140         /// This method is provided for use by RegisterContextLinux derivatives.
141         Error
142         WriteRegisterValue(lldb::tid_t tid, unsigned offset, const char *reg_name,
143                            const RegisterValue &value);
144 
145         /// Reads all general purpose registers into the specified buffer.
146         Error
147         ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size);
148 
149         /// Reads generic floating point registers into the specified buffer.
150         Error
151         ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size);
152 
153         /// Reads the specified register set into the specified buffer.
154         /// For instance, the extended floating-point register set.
155         Error
156         ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset);
157 
158         /// Writes all general purpose registers into the specified buffer.
159         Error
160         WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size);
161 
162         /// Writes generic floating point registers into the specified buffer.
163         Error
164         WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size);
165 
166         /// Writes the specified register set into the specified buffer.
167         /// For instance, the extended floating-point register set.
168         Error
169         WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset);
170 
171         Error
172         GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec) override;
173 
174     protected:
175         // ---------------------------------------------------------------------
176         // NativeProcessProtocol protected interface
177         // ---------------------------------------------------------------------
178         Error
179         GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes) override;
180 
181     private:
182 
183         class Monitor;
184 
185         ArchSpec m_arch;
186 
187         std::unique_ptr<Monitor> m_monitor_up;
188 
189         LazyBool m_supports_mem_region;
190         std::vector<MemoryRegionInfo> m_mem_region_cache;
191         Mutex m_mem_region_cache_mutex;
192 
193         // List of thread ids stepping with a breakpoint with the address of
194         // the relevan breakpoint
195         std::map<lldb::tid_t, lldb::addr_t> m_threads_stepping_with_breakpoint;
196 
197         /// @class LauchArgs
198         ///
199         /// @brief Simple structure to pass data to the thread responsible for
200         /// launching a child process.
201         struct LaunchArgs
202         {
203             LaunchArgs(Module *module,
204                     char const **argv,
205                     char const **envp,
206                     const std::string &stdin_path,
207                     const std::string &stdout_path,
208                     const std::string &stderr_path,
209                     const char *working_dir,
210                     const ProcessLaunchInfo &launch_info);
211 
212             ~LaunchArgs();
213 
214             Module *m_module;                 // The executable image to launch.
215             char const **m_argv;              // Process arguments.
216             char const **m_envp;              // Process environment.
217             const std::string &m_stdin_path;  // Redirect stdin if not empty.
218             const std::string &m_stdout_path; // Redirect stdout if not empty.
219             const std::string &m_stderr_path; // Redirect stderr if not empty.
220             const char *m_working_dir;        // Working directory or NULL.
221             const ProcessLaunchInfo &m_launch_info;
222         };
223 
224         typedef std::function<::pid_t(Error &)> InitialOperation;
225 
226         // ---------------------------------------------------------------------
227         // Private Instance Methods
228         // ---------------------------------------------------------------------
229         NativeProcessLinux ();
230 
231         /// Launches an inferior process ready for debugging.  Forms the
232         /// implementation of Process::DoLaunch.
233         void
234         LaunchInferior (
235             Module *module,
236             char const *argv[],
237             char const *envp[],
238             const std::string &stdin_path,
239             const std::string &stdout_path,
240             const std::string &stderr_path,
241             const char *working_dir,
242             const ProcessLaunchInfo &launch_info,
243             Error &error);
244 
245         /// Attaches to an existing process.  Forms the
246         /// implementation of Process::DoAttach
247         void
248         AttachToInferior (lldb::pid_t pid, Error &error);
249 
250         void
251         StartMonitorThread(const InitialOperation &operation, Error &error);
252 
253         ::pid_t
254         Launch(LaunchArgs *args, Error &error);
255 
256         ::pid_t
257         Attach(lldb::pid_t pid, Error &error);
258 
259         static Error
260         SetDefaultPtraceOpts(const lldb::pid_t);
261 
262         static bool
263         DupDescriptor(const char *path, int fd, int flags);
264 
265         static void *
266         MonitorThread(void *baton);
267 
268         void
269         MonitorCallback(lldb::pid_t pid, bool exited, int signal, int status);
270 
271         void
272         WaitForNewThread(::pid_t tid);
273 
274         void
275         MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid);
276 
277         void
278         MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp);
279 
280         void
281         MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp);
282 
283         void
284         MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index);
285 
286         void
287         MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited);
288 
289         bool
290         SupportHardwareSingleStepping() const;
291 
292         Error
293         SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp);
294 
295 #if 0
296         static ::ProcessMessage::CrashReason
297         GetCrashReasonForSIGSEGV(const siginfo_t *info);
298 
299         static ::ProcessMessage::CrashReason
300         GetCrashReasonForSIGILL(const siginfo_t *info);
301 
302         static ::ProcessMessage::CrashReason
303         GetCrashReasonForSIGFPE(const siginfo_t *info);
304 
305         static ::ProcessMessage::CrashReason
306         GetCrashReasonForSIGBUS(const siginfo_t *info);
307 #endif
308 
309         bool
310         HasThreadNoLock (lldb::tid_t thread_id);
311 
312         NativeThreadProtocolSP
313         MaybeGetThreadNoLock (lldb::tid_t thread_id);
314 
315         bool
316         StopTrackingThread (lldb::tid_t thread_id);
317 
318         NativeThreadProtocolSP
319         AddThread (lldb::tid_t thread_id);
320 
321         Error
322         GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size);
323 
324         Error
325         FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp);
326 
327         /// Writes a siginfo_t structure corresponding to the given thread ID to the
328         /// memory region pointed to by @p siginfo.
329         Error
330         GetSignalInfo(lldb::tid_t tid, void *siginfo);
331 
332         /// Writes the raw event message code (vis-a-vis PTRACE_GETEVENTMSG)
333         /// corresponding to the given thread ID to the memory pointed to by @p
334         /// message.
335         Error
336         GetEventMessage(lldb::tid_t tid, unsigned long *message);
337 
338         /// Resumes the given thread.  If @p signo is anything but
339         /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread.
340         Error
341         Resume(lldb::tid_t tid, uint32_t signo);
342 
343         /// Single steps the given thread.  If @p signo is anything but
344         /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread.
345         Error
346         SingleStep(lldb::tid_t tid, uint32_t signo);
347 
348         // ThreadStateCoordinator helper methods.
349         void
350         NotifyThreadCreateStopped (lldb::tid_t tid);
351 
352         void
353         NotifyThreadCreateRunning (lldb::tid_t tid);
354 
355         void
356         NotifyThreadDeath (lldb::tid_t tid);
357 
358         void
359         NotifyThreadStop (lldb::tid_t tid);
360 
361         void
362         StopRunningThreads (lldb::tid_t triggering_tid);
363 
364         void
365         StopRunningThreadsWithSkipTID (lldb::tid_t deferred_signal_tid,
366                                                 lldb::tid_t skip_stop_request_tid);
367 
368         Error
369         Detach(lldb::tid_t tid);
370 
371         Error
372         RequestThreadStop (const lldb::pid_t pid, const lldb::tid_t tid);
373 
374 
375     public:
376         // Typedefs.
377         typedef std::unordered_set<lldb::tid_t> ThreadIDSet;
378 
379         // Callback/block definitions.
380         typedef std::function<void (const char *format, va_list args)> LogFunction;
381         typedef std::function<void (const std::string &error_message)> ErrorFunction;
382         typedef std::function<Error (lldb::tid_t tid)> StopThreadFunction;
383         typedef std::function<Error (lldb::tid_t tid, bool supress_signal)> ResumeThreadFunction;
384 
385     private:
386         // Notify the coordinator when a thread is created and/or starting to be
387         // tracked.  is_stopped should be true if the thread is currently stopped;
388         // otherwise, it should be set false if it is already running.  Will
389         // call the error function if the thread id is already tracked.
390         void
391         NotifyThreadCreate (lldb::tid_t tid,
392                             bool is_stopped,
393                             const ErrorFunction &error_function);
394 
395         // Notify the coordinator when a previously-existing thread should no
396         // longer be tracked.  The error_function will trigger if the thread
397         // is not being tracked.
398         void
399         NotifyThreadDeath (lldb::tid_t tid,
400                            const ErrorFunction &error_function);
401 
402 
403         // Notify the delegate after a given set of threads stops. The triggering_tid will be set
404         // as the current thread. The error_function will be fired if either the triggering tid
405         // or any of the wait_for_stop_tids are unknown.
406         void
407         StopThreads(lldb::tid_t triggering_tid,
408                               const ThreadIDSet &wait_for_stop_tids,
409                               const StopThreadFunction &request_thread_stop_function,
410                               const ErrorFunction &error_function);
411 
412         // Notify the delegate after all non-stopped threads stop. The triggering_tid will be set
413         // as the current thread. The error_function will be fired if the triggering tid
414         // is unknown.
415         void
416         StopRunningThreads(lldb::tid_t triggering_tid,
417                                      const StopThreadFunction &request_thread_stop_function,
418                                      const ErrorFunction &error_function);
419 
420         // Notify the delegate after all non-stopped threads stop. The triggering_tid will be set
421         // as the current thread. The error_function will be fired if either the triggering tid
422         // or any of the wait_for_stop_tids are unknown.  This variant will send stop requests to
423         // all non-stopped threads except for any contained in skip_stop_request_tids.
424         void
425         StopRunningThreadsWithSkipTID(lldb::tid_t triggering_tid,
426                                                  const ThreadIDSet &skip_stop_request_tids,
427                                                  const StopThreadFunction &request_thread_stop_function,
428                                                  const ErrorFunction &error_function);
429 
430         // Notify the thread stopped.  Will trigger error at time of execution if we
431         // already think it is stopped.
432         void
433         NotifyThreadStop (lldb::tid_t tid,
434                           bool initiated_by_llgs,
435                           const ErrorFunction &error_function);
436 
437         // Request that the given thread id should have the request_thread_resume_function
438         // called.  Will trigger the error_function if the thread is thought to be running
439         // already at that point.  This call signals an error if the thread resume is for
440         // a thread that is already in a running state.
441         void
442         RequestThreadResume (lldb::tid_t tid,
443                              const ResumeThreadFunction &request_thread_resume_function,
444                              const ErrorFunction &error_function);
445 
446         // Request that the given thread id should have the request_thread_resume_function
447         // called.  Will trigger the error_function if the thread is thought to be running
448         // already at that point.  This call ignores threads that are already running and
449         // does not trigger an error in that case.
450         void
451         RequestThreadResumeAsNeeded (lldb::tid_t tid,
452                                      const ResumeThreadFunction &request_thread_resume_function,
453                                      const ErrorFunction &error_function);
454 
455         // Indicate the calling process did an exec and that the thread state
456         // should be 100% cleared.
457         void
458         ResetForExec ();
459 
460         // Enable/disable verbose logging of event processing.
461         void
462         LogEnableEventProcessing (bool enabled);
463 
464     private:
465 
466         enum class ThreadState
467         {
468             Running,
469             Stopped
470         };
471 
472         struct ThreadContext
473         {
474             ThreadState m_state;
475             bool m_stop_requested = false;
476             ResumeThreadFunction m_request_resume_function;
477         };
478         typedef std::unordered_map<lldb::tid_t, ThreadContext> TIDContextMap;
479 
480         struct PendingNotification
481         {
482             PendingNotification (lldb::tid_t triggering_tid,
483                                        const ThreadIDSet &wait_for_stop_tids,
484                                        const StopThreadFunction &request_thread_stop_function,
485                                        const ErrorFunction &error_function):
486             triggering_tid (triggering_tid),
487             wait_for_stop_tids (wait_for_stop_tids),
488             original_wait_for_stop_tids (wait_for_stop_tids),
489             request_thread_stop_function (request_thread_stop_function),
490             error_function (error_function),
491             request_stop_on_all_unstopped_threads (false),
492             skip_stop_request_tids ()
493             {
494             }
495 
496             PendingNotification (lldb::tid_t triggering_tid,
497                                        const StopThreadFunction &request_thread_stop_function,
498                                        const ErrorFunction &error_function) :
499             triggering_tid (triggering_tid),
500             wait_for_stop_tids (),
501             original_wait_for_stop_tids (),
502             request_thread_stop_function (request_thread_stop_function),
503             error_function (error_function),
504             request_stop_on_all_unstopped_threads (true),
505             skip_stop_request_tids ()
506             {
507             }
508 
509             PendingNotification (lldb::tid_t triggering_tid,
510                                        const StopThreadFunction &request_thread_stop_function,
511                                        const ThreadIDSet &skip_stop_request_tids,
512                                        const ErrorFunction &error_function) :
513             triggering_tid (triggering_tid),
514             wait_for_stop_tids (),
515             original_wait_for_stop_tids (),
516             request_thread_stop_function (request_thread_stop_function),
517             error_function (error_function),
518             request_stop_on_all_unstopped_threads (true),
519             skip_stop_request_tids (skip_stop_request_tids)
520             {
521             }
522 
523             const lldb::tid_t  triggering_tid;
524             ThreadIDSet        wait_for_stop_tids;
525             const ThreadIDSet  original_wait_for_stop_tids;
526             StopThreadFunction request_thread_stop_function;
527             ErrorFunction      error_function;
528             const bool         request_stop_on_all_unstopped_threads;
529             ThreadIDSet        skip_stop_request_tids;
530         };
531         typedef std::unique_ptr<PendingNotification> PendingNotificationUP;
532 
533         // Fire pending notification if no pending thread stops remain.
534         void SignalIfRequirementsSatisfied();
535 
536         bool
537         RequestStopOnAllSpecifiedThreads();
538 
539         void
540         RequestStopOnAllRunningThreads();
541 
542         void
543         RequestThreadStop (lldb::tid_t tid, ThreadContext& context);
544 
545         std::mutex m_event_mutex; // Serializes execution of ProcessEvent. XXX
546 
547         void
548         ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs, const ErrorFunction &error_function);
549 
550         void
551         DoResume(lldb::tid_t tid, ResumeThreadFunction request_thread_resume_function,
552                 ErrorFunction error_function, bool error_when_already_running);
553 
554         void
555         DoStopThreads(PendingNotificationUP &&notification_up);
556 
557         void
558         ThreadWasCreated (lldb::tid_t tid, bool is_stopped, const ErrorFunction &error_function);
559 
560         void
561         ThreadDidDie (lldb::tid_t tid, const ErrorFunction &error_function);
562 
563         bool
564         IsKnownThread(lldb::tid_t tid) const;
565 
566         void
567         TSCLog (const char *format, ...);
568 
569         // Member variables.
570         LogFunction m_log_function;
571         PendingNotificationUP m_pending_notification_up;
572 
573         // Maps known TIDs to ThreadContext.
574         TIDContextMap m_tid_map;
575 
576         bool m_log_event_processing;
577     };
578 
579 } // namespace process_linux
580 } // namespace lldb_private
581 
582 #endif // #ifndef liblldb_NativeProcessLinux_H_
583