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 // 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<std::unique_ptr<NativeProcessProtocol>>
46     Launch(ProcessLaunchInfo &launch_info, NativeDelegate &native_delegate,
47            MainLoop &mainloop) const override;
48 
49     llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
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   const ArchSpec &GetArchitecture() const override { return m_arch; }
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   NativeThreadLinux *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                      llvm::ArrayRef<::pid_t> tids);
165 
166   // Returns a list of process threads that we have attached to.
167   static llvm::Expected<std::vector<::pid_t>> Attach(::pid_t pid);
168 
169   static Status SetDefaultPtraceOpts(const lldb::pid_t);
170 
171   void MonitorCallback(lldb::pid_t pid, bool exited, WaitStatus status);
172 
173   void WaitForNewThread(::pid_t tid);
174 
175   void MonitorSIGTRAP(const siginfo_t &info, NativeThreadLinux &thread);
176 
177   void MonitorTrace(NativeThreadLinux &thread);
178 
179   void MonitorBreakpoint(NativeThreadLinux &thread);
180 
181   void MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index);
182 
183   void MonitorSignal(const siginfo_t &info, NativeThreadLinux &thread,
184                      bool exited);
185 
186   Status SetupSoftwareSingleStepping(NativeThreadLinux &thread);
187 
188 #if 0
189         static ::ProcessMessage::CrashReason
190         GetCrashReasonForSIGSEGV(const siginfo_t *info);
191 
192         static ::ProcessMessage::CrashReason
193         GetCrashReasonForSIGILL(const siginfo_t *info);
194 
195         static ::ProcessMessage::CrashReason
196         GetCrashReasonForSIGFPE(const siginfo_t *info);
197 
198         static ::ProcessMessage::CrashReason
199         GetCrashReasonForSIGBUS(const siginfo_t *info);
200 #endif
201 
202   bool HasThreadNoLock(lldb::tid_t thread_id);
203 
204   bool StopTrackingThread(lldb::tid_t thread_id);
205 
206   NativeThreadLinux &AddThread(lldb::tid_t thread_id);
207 
208   Status GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size);
209 
210   Status FixupBreakpointPCAsNeeded(NativeThreadLinux &thread);
211 
212   /// Writes a siginfo_t structure corresponding to the given thread ID to the
213   /// memory region pointed to by @p siginfo.
214   Status GetSignalInfo(lldb::tid_t tid, void *siginfo);
215 
216   /// Writes the raw event message code (vis-a-vis PTRACE_GETEVENTMSG)
217   /// corresponding to the given thread ID to the memory pointed to by @p
218   /// message.
219   Status GetEventMessage(lldb::tid_t tid, unsigned long *message);
220 
221   void NotifyThreadDeath(lldb::tid_t tid);
222 
223   Status Detach(lldb::tid_t tid);
224 
225   // This method is requests a stop on all threads which are still running. It
226   // sets up a
227   // deferred delegate notification, which will fire once threads report as
228   // stopped. The
229   // triggerring_tid will be set as the current thread (main stop reason).
230   void StopRunningThreads(lldb::tid_t triggering_tid);
231 
232   // Notify the delegate if all threads have stopped.
233   void SignalIfAllThreadsStopped();
234 
235   // Resume the given thread, optionally passing it the given signal. The type
236   // of resume
237   // operation (continue, single-step) depends on the state parameter.
238   Status ResumeThread(NativeThreadLinux &thread, lldb::StateType state,
239                       int signo);
240 
241   void ThreadWasCreated(NativeThreadLinux &thread);
242 
243   void SigchldHandler();
244 
245   Status PopulateMemoryRegionCache();
246 
247   lldb::user_id_t StartTraceGroup(const TraceOptions &config,
248                                          Status &error);
249 
250   // This function is intended to be used to stop tracing
251   // on a thread that exited.
252   Status StopTracingForThread(lldb::tid_t thread);
253 
254   // The below function as the name suggests, looks up a ProcessorTrace
255   // instance from the m_processor_trace_monitor map. In the case of
256   // process tracing where the traceid passed would map to the complete
257   // process, it is mandatory to provide a threadid to obtain a trace
258   // instance (since ProcessorTrace is tied to a thread). In the other
259   // scenario that an individual thread is being traced, just the traceid
260   // is sufficient to obtain the actual ProcessorTrace instance.
261   llvm::Expected<ProcessorTraceMonitor &>
262   LookupProcessorTraceInstance(lldb::user_id_t traceid, lldb::tid_t thread);
263 
264   // Stops tracing on individual threads being traced. Not intended
265   // to be used to stop tracing on complete process.
266   Status StopProcessorTracingOnThread(lldb::user_id_t traceid,
267                                       lldb::tid_t thread);
268 
269   // Intended to stop tracing on complete process.
270   // Should not be used for stopping trace on
271   // individual threads.
272   void StopProcessorTracingOnProcess();
273 
274   llvm::DenseMap<lldb::tid_t, ProcessorTraceMonitorUP>
275       m_processor_trace_monitor;
276 
277   // Set for tracking threads being traced under
278   // same process user id.
279   llvm::DenseSet<lldb::tid_t> m_pt_traced_thread_group;
280 
281   lldb::user_id_t m_pt_proces_trace_id = LLDB_INVALID_UID;
282   TraceOptions m_pt_process_trace_config;
283 };
284 
285 } // namespace process_linux
286 } // namespace lldb_private
287 
288 #endif // #ifndef liblldb_NativeProcessLinux_H_
289