1 //===-- NativeProcessProtocol.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 LLDB_HOST_COMMON_NATIVEPROCESSPROTOCOL_H 10 #define LLDB_HOST_COMMON_NATIVEPROCESSPROTOCOL_H 11 12 #include "NativeBreakpointList.h" 13 #include "NativeThreadProtocol.h" 14 #include "NativeWatchpointList.h" 15 #include "lldb/Host/Host.h" 16 #include "lldb/Host/MainLoop.h" 17 #include "lldb/Utility/ArchSpec.h" 18 #include "lldb/Utility/Status.h" 19 #include "lldb/Utility/TraceGDBRemotePackets.h" 20 #include "lldb/Utility/UnimplementedError.h" 21 #include "lldb/lldb-private-forward.h" 22 #include "lldb/lldb-types.h" 23 #include "llvm/ADT/ArrayRef.h" 24 #include "llvm/ADT/DenseSet.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/Support/Error.h" 27 #include "llvm/Support/MemoryBuffer.h" 28 #include <mutex> 29 #include <unordered_map> 30 #include <vector> 31 32 namespace lldb_private { 33 LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE(); 34 35 class MemoryRegionInfo; 36 class ResumeActionList; 37 38 struct SVR4LibraryInfo { 39 std::string name; 40 lldb::addr_t link_map; 41 lldb::addr_t base_addr; 42 lldb::addr_t ld_addr; 43 lldb::addr_t next; 44 }; 45 46 // NativeProcessProtocol 47 class NativeProcessProtocol { 48 public: 49 virtual ~NativeProcessProtocol() = default; 50 51 virtual Status Resume(const ResumeActionList &resume_actions) = 0; 52 53 virtual Status Halt() = 0; 54 55 virtual Status Detach() = 0; 56 57 /// Sends a process a UNIX signal \a signal. 58 /// 59 /// \return 60 /// Returns an error object. 61 virtual Status Signal(int signo) = 0; 62 63 /// Tells a process to interrupt all operations as if by a Ctrl-C. 64 /// 65 /// The default implementation will send a local host's equivalent of 66 /// a SIGSTOP to the process via the NativeProcessProtocol::Signal() 67 /// operation. 68 /// 69 /// \return 70 /// Returns an error object. 71 virtual Status Interrupt(); 72 73 virtual Status Kill() = 0; 74 75 // Tells a process not to stop the inferior on given signals and just 76 // reinject them back. 77 virtual Status IgnoreSignals(llvm::ArrayRef<int> signals); 78 79 // Memory and memory region functions 80 81 virtual Status GetMemoryRegionInfo(lldb::addr_t load_addr, 82 MemoryRegionInfo &range_info); 83 84 virtual Status ReadMemory(lldb::addr_t addr, void *buf, size_t size, 85 size_t &bytes_read) = 0; 86 87 Status ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, 88 size_t &bytes_read); 89 90 virtual Status ReadMemoryTags(int32_t type, lldb::addr_t addr, size_t len, 91 std::vector<uint8_t> &tags); 92 93 virtual Status WriteMemoryTags(int32_t type, lldb::addr_t addr, size_t len, 94 const std::vector<uint8_t> &tags); 95 96 /// Reads a null terminated string from memory. 97 /// 98 /// Reads up to \p max_size bytes of memory until it finds a '\0'. 99 /// If a '\0' is not found then it reads max_size-1 bytes as a string and a 100 /// '\0' is added as the last character of the \p buffer. 101 /// 102 /// \param[in] addr 103 /// The address in memory to read from. 104 /// 105 /// \param[in] buffer 106 /// An allocated buffer with at least \p max_size size. 107 /// 108 /// \param[in] max_size 109 /// The maximum number of bytes to read from memory until it reads the 110 /// string. 111 /// 112 /// \param[out] total_bytes_read 113 /// The number of bytes read from memory into \p buffer. 114 /// 115 /// \return 116 /// Returns a StringRef backed up by the \p buffer passed in. 117 llvm::Expected<llvm::StringRef> 118 ReadCStringFromMemory(lldb::addr_t addr, char *buffer, size_t max_size, 119 size_t &total_bytes_read); 120 121 virtual Status WriteMemory(lldb::addr_t addr, const void *buf, size_t size, 122 size_t &bytes_written) = 0; 123 AllocateMemory(size_t size,uint32_t permissions)124 virtual llvm::Expected<lldb::addr_t> AllocateMemory(size_t size, 125 uint32_t permissions) { 126 return llvm::make_error<UnimplementedError>(); 127 } 128 DeallocateMemory(lldb::addr_t addr)129 virtual llvm::Error DeallocateMemory(lldb::addr_t addr) { 130 return llvm::make_error<UnimplementedError>(); 131 } 132 133 virtual lldb::addr_t GetSharedLibraryInfoAddress() = 0; 134 135 virtual llvm::Expected<std::vector<SVR4LibraryInfo>> GetLoadedSVR4Libraries()136 GetLoadedSVR4Libraries() { 137 return llvm::createStringError(llvm::inconvertibleErrorCode(), 138 "Not implemented"); 139 } 140 141 virtual bool IsAlive() const; 142 143 virtual size_t UpdateThreads() = 0; 144 145 virtual const ArchSpec &GetArchitecture() const = 0; 146 147 // Breakpoint functions 148 virtual Status SetBreakpoint(lldb::addr_t addr, uint32_t size, 149 bool hardware) = 0; 150 151 virtual Status RemoveBreakpoint(lldb::addr_t addr, bool hardware = false); 152 153 // Hardware Breakpoint functions 154 virtual const HardwareBreakpointMap &GetHardwareBreakpointMap() const; 155 156 virtual Status SetHardwareBreakpoint(lldb::addr_t addr, size_t size); 157 158 virtual Status RemoveHardwareBreakpoint(lldb::addr_t addr); 159 160 // Watchpoint functions 161 virtual const NativeWatchpointList::WatchpointMap &GetWatchpointMap() const; 162 163 virtual llvm::Optional<std::pair<uint32_t, uint32_t>> 164 GetHardwareDebugSupportInfo() const; 165 166 virtual Status SetWatchpoint(lldb::addr_t addr, size_t size, 167 uint32_t watch_flags, bool hardware); 168 169 virtual Status RemoveWatchpoint(lldb::addr_t addr); 170 171 // Accessors GetID()172 lldb::pid_t GetID() const { return m_pid; } 173 174 lldb::StateType GetState() const; 175 IsRunning()176 bool IsRunning() const { 177 return m_state == lldb::eStateRunning || IsStepping(); 178 } 179 IsStepping()180 bool IsStepping() const { return m_state == lldb::eStateStepping; } 181 CanResume()182 bool CanResume() const { return m_state == lldb::eStateStopped; } 183 GetByteOrder()184 lldb::ByteOrder GetByteOrder() const { 185 return GetArchitecture().GetByteOrder(); 186 } 187 GetAddressByteSize()188 uint32_t GetAddressByteSize() const { 189 return GetArchitecture().GetAddressByteSize(); 190 } 191 192 virtual llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 193 GetAuxvData() const = 0; 194 195 // Exit Status 196 virtual llvm::Optional<WaitStatus> GetExitStatus(); 197 198 virtual bool SetExitStatus(WaitStatus status, bool bNotifyStateChange); 199 200 // Access to threads 201 NativeThreadProtocol *GetThreadAtIndex(uint32_t idx); 202 203 NativeThreadProtocol *GetThreadByID(lldb::tid_t tid); 204 SetCurrentThreadID(lldb::tid_t tid)205 void SetCurrentThreadID(lldb::tid_t tid) { m_current_thread_id = tid; } 206 GetCurrentThreadID()207 lldb::tid_t GetCurrentThreadID() { return m_current_thread_id; } 208 GetCurrentThread()209 NativeThreadProtocol *GetCurrentThread() { 210 return GetThreadByID(m_current_thread_id); 211 } 212 213 // Access to inferior stdio GetTerminalFileDescriptor()214 virtual int GetTerminalFileDescriptor() { return m_terminal_fd; } 215 216 // Stop id interface 217 218 uint32_t GetStopID() const; 219 220 // Callbacks for low-level process state changes 221 class NativeDelegate { 222 public: 223 virtual ~NativeDelegate() = default; 224 225 virtual void InitializeDelegate(NativeProcessProtocol *process) = 0; 226 227 virtual void ProcessStateChanged(NativeProcessProtocol *process, 228 lldb::StateType state) = 0; 229 230 virtual void DidExec(NativeProcessProtocol *process) = 0; 231 232 virtual void 233 NewSubprocess(NativeProcessProtocol *parent_process, 234 std::unique_ptr<NativeProcessProtocol> child_process) = 0; 235 }; 236 237 virtual Status GetLoadedModuleFileSpec(const char *module_path, 238 FileSpec &file_spec) = 0; 239 240 virtual Status GetFileLoadAddress(const llvm::StringRef &file_name, 241 lldb::addr_t &load_addr) = 0; 242 243 /// Extension flag constants, returned by Factory::GetSupportedExtensions() 244 /// and passed to SetEnabledExtension() 245 enum class Extension { 246 multiprocess = (1u << 0), 247 fork = (1u << 1), 248 vfork = (1u << 2), 249 pass_signals = (1u << 3), 250 auxv = (1u << 4), 251 libraries_svr4 = (1u << 5), 252 memory_tagging = (1u << 6), 253 254 LLVM_MARK_AS_BITMASK_ENUM(memory_tagging) 255 }; 256 257 class Factory { 258 public: 259 virtual ~Factory(); 260 /// Launch a process for debugging. 261 /// 262 /// \param[in] launch_info 263 /// Information required to launch the process. 264 /// 265 /// \param[in] native_delegate 266 /// The delegate that will receive messages regarding the 267 /// inferior. Must outlive the NativeProcessProtocol 268 /// instance. 269 /// 270 /// \param[in] mainloop 271 /// The mainloop instance with which the process can register 272 /// callbacks. Must outlive the NativeProcessProtocol 273 /// instance. 274 /// 275 /// \return 276 /// A NativeProcessProtocol shared pointer if the operation succeeded or 277 /// an error object if it failed. 278 virtual llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 279 Launch(ProcessLaunchInfo &launch_info, NativeDelegate &native_delegate, 280 MainLoop &mainloop) const = 0; 281 282 /// Attach to an existing process. 283 /// 284 /// \param[in] pid 285 /// pid of the process locatable 286 /// 287 /// \param[in] native_delegate 288 /// The delegate that will receive messages regarding the 289 /// inferior. Must outlive the NativeProcessProtocol 290 /// instance. 291 /// 292 /// \param[in] mainloop 293 /// The mainloop instance with which the process can register 294 /// callbacks. Must outlive the NativeProcessProtocol 295 /// instance. 296 /// 297 /// \return 298 /// A NativeProcessProtocol shared pointer if the operation succeeded or 299 /// an error object if it failed. 300 virtual llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 301 Attach(lldb::pid_t pid, NativeDelegate &native_delegate, 302 MainLoop &mainloop) const = 0; 303 304 /// Get the bitmask of extensions supported by this process plugin. 305 /// 306 /// \return 307 /// A NativeProcessProtocol::Extension bitmask. GetSupportedExtensions()308 virtual Extension GetSupportedExtensions() const { return {}; } 309 }; 310 311 /// Start tracing a process or its threads. 312 /// 313 /// \param[in] json_params 314 /// JSON object with the information of what and how to trace. 315 /// In the case of gdb-remote, this object should conform to the 316 /// jLLDBTraceStart packet. 317 /// 318 /// This object should have a string entry called "type", which is the 319 /// tracing technology name. 320 /// 321 /// \param[in] type 322 /// Tracing technology type, as described in the \a json_params. 323 /// 324 /// \return 325 /// \a llvm::Error::success if the operation was successful, or an 326 /// \a llvm::Error otherwise. TraceStart(llvm::StringRef json_params,llvm::StringRef type)327 virtual llvm::Error TraceStart(llvm::StringRef json_params, 328 llvm::StringRef type) { 329 return llvm::createStringError(llvm::inconvertibleErrorCode(), 330 "Unsupported tracing type '%s'", 331 type.data()); 332 } 333 334 /// \copydoc Process::TraceStop(const TraceStopRequest &) TraceStop(const TraceStopRequest & request)335 virtual llvm::Error TraceStop(const TraceStopRequest &request) { 336 return llvm::createStringError(llvm::inconvertibleErrorCode(), 337 "Unsupported tracing type '%s'", 338 request.type.data()); 339 } 340 341 /// \copydoc Process::TraceGetState(llvm::StringRef type) 342 virtual llvm::Expected<llvm::json::Value> TraceGetState(llvm::StringRef type)343 TraceGetState(llvm::StringRef type) { 344 return llvm::createStringError(llvm::inconvertibleErrorCode(), 345 "Unsupported tracing type '%s'", 346 type.data()); 347 } 348 349 /// \copydoc Process::TraceGetBinaryData(const TraceGetBinaryDataRequest &) 350 virtual llvm::Expected<std::vector<uint8_t>> TraceGetBinaryData(const TraceGetBinaryDataRequest & request)351 TraceGetBinaryData(const TraceGetBinaryDataRequest &request) { 352 return llvm::createStringError( 353 llvm::inconvertibleErrorCode(), 354 "Unsupported data kind '%s' for the '%s' tracing technology", 355 request.kind.c_str(), request.type.c_str()); 356 } 357 358 /// \copydoc Process::TraceSupported() TraceSupported()359 virtual llvm::Expected<TraceSupportedResponse> TraceSupported() { 360 return llvm::make_error<UnimplementedError>(); 361 } 362 363 /// Method called in order to propagate the bitmap of protocol 364 /// extensions supported by the client. 365 /// 366 /// \param[in] flags 367 /// The bitmap of enabled extensions. SetEnabledExtensions(Extension flags)368 virtual void SetEnabledExtensions(Extension flags) { 369 m_enabled_extensions = flags; 370 } 371 372 protected: 373 struct SoftwareBreakpoint { 374 uint32_t ref_count; 375 llvm::SmallVector<uint8_t, 4> saved_opcodes; 376 llvm::ArrayRef<uint8_t> breakpoint_opcodes; 377 }; 378 379 std::unordered_map<lldb::addr_t, SoftwareBreakpoint> m_software_breakpoints; 380 lldb::pid_t m_pid; 381 382 std::vector<std::unique_ptr<NativeThreadProtocol>> m_threads; 383 lldb::tid_t m_current_thread_id = LLDB_INVALID_THREAD_ID; 384 mutable std::recursive_mutex m_threads_mutex; 385 386 lldb::StateType m_state = lldb::eStateInvalid; 387 mutable std::recursive_mutex m_state_mutex; 388 389 llvm::Optional<WaitStatus> m_exit_status; 390 391 NativeDelegate &m_delegate; 392 NativeWatchpointList m_watchpoint_list; 393 HardwareBreakpointMap m_hw_breakpoints_map; 394 int m_terminal_fd; 395 uint32_t m_stop_id = 0; 396 397 // Set of signal numbers that LLDB directly injects back to inferior without 398 // stopping it. 399 llvm::DenseSet<int> m_signals_to_ignore; 400 401 // Extensions enabled per the last SetEnabledExtensions() call. 402 Extension m_enabled_extensions; 403 404 // lldb_private::Host calls should be used to launch a process for debugging, 405 // and then the process should be attached to. When attaching to a process 406 // lldb_private::Host calls should be used to locate the process to attach 407 // to, and then this function should be called. 408 NativeProcessProtocol(lldb::pid_t pid, int terminal_fd, 409 NativeDelegate &delegate); 410 SetID(lldb::pid_t pid)411 void SetID(lldb::pid_t pid) { m_pid = pid; } 412 413 // interface for state handling 414 void SetState(lldb::StateType state, bool notify_delegates = true); 415 416 // Derived classes need not implement this. It can be used as a hook to 417 // clear internal caches that should be invalidated when stop ids change. 418 // 419 // Note this function is called with the state mutex obtained by the caller. 420 virtual void DoStopIDBumped(uint32_t newBumpId); 421 422 // interface for software breakpoints 423 424 Status SetSoftwareBreakpoint(lldb::addr_t addr, uint32_t size_hint); 425 Status RemoveSoftwareBreakpoint(lldb::addr_t addr); 426 427 virtual llvm::Expected<llvm::ArrayRef<uint8_t>> 428 GetSoftwareBreakpointTrapOpcode(size_t size_hint); 429 430 /// Return the offset of the PC relative to the software breakpoint that was hit. If an 431 /// architecture (e.g. arm) reports breakpoint hits before incrementing the PC, this offset 432 /// will be 0. If an architecture (e.g. intel) reports breakpoints hits after incrementing the 433 /// PC, this offset will be the size of the breakpoint opcode. 434 virtual size_t GetSoftwareBreakpointPCOffset(); 435 436 // Adjust the thread's PC after hitting a software breakpoint. On 437 // architectures where the PC points after the breakpoint instruction, this 438 // resets it to point to the breakpoint itself. 439 void FixupBreakpointPCAsNeeded(NativeThreadProtocol &thread); 440 441 /// Notify the delegate that an exec occurred. 442 /// 443 /// Provide a mechanism for a delegate to clear out any exec- 444 /// sensitive data. 445 void NotifyDidExec(); 446 447 NativeThreadProtocol *GetThreadByIDUnlocked(lldb::tid_t tid); 448 449 private: 450 void SynchronouslyNotifyProcessStateChanged(lldb::StateType state); 451 llvm::Expected<SoftwareBreakpoint> 452 EnableSoftwareBreakpoint(lldb::addr_t addr, uint32_t size_hint); 453 }; 454 } // namespace lldb_private 455 456 #endif // LLDB_HOST_COMMON_NATIVEPROCESSPROTOCOL_H 457