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