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 #include <csignal>
14 #include <unordered_set>
15 
16 #include "lldb/Host/Debug.h"
17 #include "lldb/Host/HostThread.h"
18 #include "lldb/Host/linux/Support.h"
19 #include "lldb/Target/MemoryRegionInfo.h"
20 #include "lldb/Utility/ArchSpec.h"
21 #include "lldb/Utility/FileSpec.h"
22 #include "lldb/lldb-types.h"
23 
24 #include "NativeThreadLinux.h"
25 #include "ProcessorTrace.h"
26 #include "lldb/Host/common/NativeProcessProtocol.h"
27 
28 namespace lldb_private {
29 class Status;
30 class Scalar;
31 
32 namespace process_linux {
33 /// @class NativeProcessLinux
34 /// Manages communication with the inferior (debugee) process.
35 ///
36 /// Upon construction, this class prepares and launches an inferior process
37 /// for debugging.
38 ///
39 /// Changes in the inferior process state are broadcasted.
40 class NativeProcessLinux : public NativeProcessProtocol {
41 public:
42   class Factory : public NativeProcessProtocol::Factory {
43   public:
44     llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
45     Launch(ProcessLaunchInfo &launch_info, NativeDelegate &native_delegate,
46            MainLoop &mainloop) const override;
47 
48     llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
49     Attach(lldb::pid_t pid, NativeDelegate &native_delegate,
50            MainLoop &mainloop) const override;
51   };
52 
53   // ---------------------------------------------------------------------
54   // NativeProcessProtocol Interface
55   // ---------------------------------------------------------------------
56   Status Resume(const ResumeActionList &resume_actions) override;
57 
58   Status Halt() override;
59 
60   Status Detach() override;
61 
62   Status Signal(int signo) override;
63 
64   Status Interrupt() override;
65 
66   Status Kill() override;
67 
68   Status GetMemoryRegionInfo(lldb::addr_t load_addr,
69                              MemoryRegionInfo &range_info) override;
70 
71   Status ReadMemory(lldb::addr_t addr, void *buf, size_t size,
72                     size_t &bytes_read) override;
73 
74   Status ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size,
75                                size_t &bytes_read) override;
76 
77   Status WriteMemory(lldb::addr_t addr, const void *buf, size_t size,
78                      size_t &bytes_written) override;
79 
80   Status AllocateMemory(size_t size, uint32_t permissions,
81                         lldb::addr_t &addr) override;
82 
83   Status DeallocateMemory(lldb::addr_t addr) override;
84 
85   lldb::addr_t GetSharedLibraryInfoAddress() override;
86 
87   size_t UpdateThreads() override;
88 
89   const ArchSpec &GetArchitecture() const override { return m_arch; }
90 
91   Status SetBreakpoint(lldb::addr_t addr, uint32_t size,
92                        bool hardware) override;
93 
94   Status RemoveBreakpoint(lldb::addr_t addr, bool hardware = false) override;
95 
96   void DoStopIDBumped(uint32_t newBumpId) override;
97 
98   Status GetLoadedModuleFileSpec(const char *module_path,
99                                  FileSpec &file_spec) override;
100 
101   Status GetFileLoadAddress(const llvm::StringRef &file_name,
102                             lldb::addr_t &load_addr) override;
103 
104   NativeThreadLinux *GetThreadByID(lldb::tid_t id);
105 
106   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
107   GetAuxvData() const override {
108     return getProcFile(GetID(), "auxv");
109   }
110 
111   lldb::user_id_t StartTrace(const TraceOptions &config,
112                              Status &error) override;
113 
114   Status StopTrace(lldb::user_id_t traceid,
115                    lldb::tid_t thread) override;
116 
117   Status GetData(lldb::user_id_t traceid, lldb::tid_t thread,
118                  llvm::MutableArrayRef<uint8_t> &buffer,
119                  size_t offset = 0) override;
120 
121   Status GetMetaData(lldb::user_id_t traceid, lldb::tid_t thread,
122                      llvm::MutableArrayRef<uint8_t> &buffer,
123                      size_t offset = 0) override;
124 
125   Status GetTraceConfig(lldb::user_id_t traceid, TraceOptions &config) override;
126 
127   // ---------------------------------------------------------------------
128   // Interface used by NativeRegisterContext-derived classes.
129   // ---------------------------------------------------------------------
130   static Status PtraceWrapper(int req, lldb::pid_t pid, void *addr = nullptr,
131                               void *data = nullptr, size_t data_size = 0,
132                               long *result = nullptr);
133 
134   bool SupportHardwareSingleStepping() const;
135 
136 protected:
137   // ---------------------------------------------------------------------
138   // NativeProcessProtocol protected interface
139   // ---------------------------------------------------------------------
140   Status
141   GetSoftwareBreakpointTrapOpcode(size_t trap_opcode_size_hint,
142                                   size_t &actual_opcode_size,
143                                   const uint8_t *&trap_opcode_bytes) override;
144 
145 private:
146   MainLoop::SignalHandleUP m_sigchld_handle;
147   ArchSpec m_arch;
148 
149   LazyBool m_supports_mem_region = eLazyBoolCalculate;
150   std::vector<std::pair<MemoryRegionInfo, FileSpec>> m_mem_region_cache;
151 
152   lldb::tid_t m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
153 
154   // List of thread ids stepping with a breakpoint with the address of
155   // the relevan breakpoint
156   std::map<lldb::tid_t, lldb::addr_t> m_threads_stepping_with_breakpoint;
157 
158   // ---------------------------------------------------------------------
159   // Private Instance Methods
160   // ---------------------------------------------------------------------
161   NativeProcessLinux(::pid_t pid, int terminal_fd, NativeDelegate &delegate,
162                      const ArchSpec &arch, MainLoop &mainloop,
163                      llvm::ArrayRef<::pid_t> tids);
164 
165   // Returns a list of process threads that we have attached to.
166   static llvm::Expected<std::vector<::pid_t>> Attach(::pid_t pid);
167 
168   static Status SetDefaultPtraceOpts(const lldb::pid_t);
169 
170   void MonitorCallback(lldb::pid_t pid, bool exited, WaitStatus status);
171 
172   void WaitForNewThread(::pid_t tid);
173 
174   void MonitorSIGTRAP(const siginfo_t &info, NativeThreadLinux &thread);
175 
176   void MonitorTrace(NativeThreadLinux &thread);
177 
178   void MonitorBreakpoint(NativeThreadLinux &thread);
179 
180   void MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index);
181 
182   void MonitorSignal(const siginfo_t &info, NativeThreadLinux &thread,
183                      bool exited);
184 
185   Status SetupSoftwareSingleStepping(NativeThreadLinux &thread);
186 
187   bool HasThreadNoLock(lldb::tid_t thread_id);
188 
189   bool StopTrackingThread(lldb::tid_t thread_id);
190 
191   NativeThreadLinux &AddThread(lldb::tid_t thread_id);
192 
193   Status GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size);
194 
195   Status FixupBreakpointPCAsNeeded(NativeThreadLinux &thread);
196 
197   /// Writes a siginfo_t structure corresponding to the given thread ID to the
198   /// memory region pointed to by @p siginfo.
199   Status GetSignalInfo(lldb::tid_t tid, void *siginfo);
200 
201   /// Writes the raw event message code (vis-a-vis PTRACE_GETEVENTMSG)
202   /// corresponding to the given thread ID to the memory pointed to by @p
203   /// message.
204   Status GetEventMessage(lldb::tid_t tid, unsigned long *message);
205 
206   void NotifyThreadDeath(lldb::tid_t tid);
207 
208   Status Detach(lldb::tid_t tid);
209 
210   // This method is requests a stop on all threads which are still running. It
211   // sets up a
212   // deferred delegate notification, which will fire once threads report as
213   // stopped. The
214   // triggerring_tid will be set as the current thread (main stop reason).
215   void StopRunningThreads(lldb::tid_t triggering_tid);
216 
217   // Notify the delegate if all threads have stopped.
218   void SignalIfAllThreadsStopped();
219 
220   // Resume the given thread, optionally passing it the given signal. The type
221   // of resume
222   // operation (continue, single-step) depends on the state parameter.
223   Status ResumeThread(NativeThreadLinux &thread, lldb::StateType state,
224                       int signo);
225 
226   void ThreadWasCreated(NativeThreadLinux &thread);
227 
228   void SigchldHandler();
229 
230   Status PopulateMemoryRegionCache();
231 
232   lldb::user_id_t StartTraceGroup(const TraceOptions &config,
233                                          Status &error);
234 
235   // This function is intended to be used to stop tracing
236   // on a thread that exited.
237   Status StopTracingForThread(lldb::tid_t thread);
238 
239   // The below function as the name suggests, looks up a ProcessorTrace
240   // instance from the m_processor_trace_monitor map. In the case of
241   // process tracing where the traceid passed would map to the complete
242   // process, it is mandatory to provide a threadid to obtain a trace
243   // instance (since ProcessorTrace is tied to a thread). In the other
244   // scenario that an individual thread is being traced, just the traceid
245   // is sufficient to obtain the actual ProcessorTrace instance.
246   llvm::Expected<ProcessorTraceMonitor &>
247   LookupProcessorTraceInstance(lldb::user_id_t traceid, lldb::tid_t thread);
248 
249   // Stops tracing on individual threads being traced. Not intended
250   // to be used to stop tracing on complete process.
251   Status StopProcessorTracingOnThread(lldb::user_id_t traceid,
252                                       lldb::tid_t thread);
253 
254   // Intended to stop tracing on complete process.
255   // Should not be used for stopping trace on
256   // individual threads.
257   void StopProcessorTracingOnProcess();
258 
259   llvm::DenseMap<lldb::tid_t, ProcessorTraceMonitorUP>
260       m_processor_trace_monitor;
261 
262   // Set for tracking threads being traced under
263   // same process user id.
264   llvm::DenseSet<lldb::tid_t> m_pt_traced_thread_group;
265 
266   lldb::user_id_t m_pt_proces_trace_id = LLDB_INVALID_UID;
267   TraceOptions m_pt_process_trace_config;
268 };
269 
270 } // namespace process_linux
271 } // namespace lldb_private
272 
273 #endif // #ifndef liblldb_NativeProcessLinux_H_
274