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