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 "IntelPTManager.h"
24 #include "NativeThreadLinux.h"
25 #include "Plugins/Process/POSIX/NativeProcessELF.h"
26 #include "Plugins/Process/Utility/NativeProcessSoftwareSingleStep.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 NativeProcessELF,
41                            private NativeProcessSoftwareSingleStep {
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     Extension GetSupportedExtensions() const override;
54   };
55 
56   // NativeProcessProtocol Interface
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 WriteMemory(lldb::addr_t addr, const void *buf, size_t size,
76                      size_t &bytes_written) override;
77 
78   llvm::Expected<lldb::addr_t> AllocateMemory(size_t size,
79                                               uint32_t permissions) override;
80 
81   llvm::Error DeallocateMemory(lldb::addr_t addr) 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   NativeThreadLinux *GetCurrentThread();
102 
103   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
104   GetAuxvData() const override {
105     return getProcFile(GetID(), "auxv");
106   }
107 
108   /// Tracing
109   /// These methods implement the jLLDBTrace packets
110   /// \{
111   llvm::Error TraceStart(llvm::StringRef json_request,
112                          llvm::StringRef type) override;
113 
114   llvm::Error TraceStop(const TraceStopRequest &request) override;
115 
116   llvm::Expected<llvm::json::Value>
117   TraceGetState(llvm::StringRef type) override;
118 
119   llvm::Expected<std::vector<uint8_t>>
120   TraceGetBinaryData(const TraceGetBinaryDataRequest &request) override;
121 
122   llvm::Expected<TraceSupportedResponse> TraceSupported() override;
123   /// }
124 
125   // Interface used by NativeRegisterContext-derived classes.
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   llvm::Expected<uint64_t> Syscall(llvm::ArrayRef<uint64_t> args);
137 
138 private:
139   MainLoop::SignalHandleUP m_sigchld_handle;
140   ArchSpec m_arch;
141   MainLoop& m_main_loop;
142 
143   LazyBool m_supports_mem_region = eLazyBoolCalculate;
144   std::vector<std::pair<MemoryRegionInfo, FileSpec>> m_mem_region_cache;
145 
146   lldb::tid_t m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
147 
148   /// Inferior memory (allocated by us) and its size.
149   llvm::DenseMap<lldb::addr_t, lldb::addr_t> m_allocated_memory;
150 
151   // Private Instance Methods
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 WaitForCloneNotification(::pid_t pid);
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   bool HasThreadNoLock(lldb::tid_t thread_id);
177 
178   bool StopTrackingThread(lldb::tid_t thread_id);
179 
180   /// Create a new thread.
181   ///
182   /// If process tracing is enabled and the thread can't be traced, then the
183   /// thread is left stopped with a \a eStopReasonProcessorTrace status, and
184   /// then the process is stopped.
185   ///
186   /// \param[in] resume
187   ///     If a tracing error didn't happen, then resume the thread after
188   ///     creation if \b true, or leave it stopped with SIGSTOP if \b false.
189   NativeThreadLinux &AddThread(lldb::tid_t thread_id, bool resume);
190 
191   /// Start tracing a new thread if process tracing is enabled.
192   ///
193   /// Trace mechanisms should modify this method to provide automatic tracing
194   /// for new threads.
195   Status NotifyTracersOfNewThread(lldb::tid_t tid);
196 
197   /// Stop tracing threads upon a destroy event.
198   ///
199   /// Trace mechanisms should modify this method to provide automatic trace
200   /// stopping for threads being destroyed.
201   Status NotifyTracersOfThreadDestroyed(lldb::tid_t tid);
202 
203   /// Writes a siginfo_t structure corresponding to the given thread ID to the
204   /// memory region pointed to by \p siginfo.
205   Status GetSignalInfo(lldb::tid_t tid, void *siginfo);
206 
207   /// Writes the raw event message code (vis-a-vis PTRACE_GETEVENTMSG)
208   /// corresponding to the given thread ID to the memory pointed to by @p
209   /// message.
210   Status GetEventMessage(lldb::tid_t tid, unsigned long *message);
211 
212   void NotifyThreadDeath(lldb::tid_t tid);
213 
214   Status Detach(lldb::tid_t tid);
215 
216   // This method is requests a stop on all threads which are still running. It
217   // sets up a
218   // deferred delegate notification, which will fire once threads report as
219   // stopped. The
220   // triggerring_tid will be set as the current thread (main stop reason).
221   void StopRunningThreads(lldb::tid_t triggering_tid);
222 
223   // Notify the delegate if all threads have stopped.
224   void SignalIfAllThreadsStopped();
225 
226   // Resume the given thread, optionally passing it the given signal. The type
227   // of resume
228   // operation (continue, single-step) depends on the state parameter.
229   Status ResumeThread(NativeThreadLinux &thread, lldb::StateType state,
230                       int signo);
231 
232   void ThreadWasCreated(NativeThreadLinux &thread);
233 
234   void SigchldHandler();
235 
236   Status PopulateMemoryRegionCache();
237 
238   /// Manages Intel PT process and thread traces.
239   IntelPTManager m_intel_pt_manager;
240 
241   struct CloneInfo {
242     int event;
243     lldb::tid_t parent_tid;
244   };
245 
246   // Map of child processes that have been signaled once, and we are
247   // waiting for the second signal.
248   llvm::DenseMap<lldb::pid_t, llvm::Optional<CloneInfo>> m_pending_pid_map;
249 
250   // Handle a clone()-like event.  If received by parent, clone_info contains
251   // additional info.  Returns true if the event is handled, or false if it
252   // is pending second notification.
253   bool MonitorClone(lldb::pid_t child_pid,
254                     llvm::Optional<CloneInfo> clone_info);
255 };
256 
257 } // namespace process_linux
258 } // namespace lldb_private
259 
260 #endif // #ifndef liblldb_NativeProcessLinux_H_
261