1 //===-- ProcessGDBRemote.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_SOURCE_PLUGINS_PROCESS_GDB_REMOTE_PROCESSGDBREMOTE_H 10 #define LLDB_SOURCE_PLUGINS_PROCESS_GDB_REMOTE_PROCESSGDBREMOTE_H 11 12 #include <atomic> 13 #include <map> 14 #include <mutex> 15 #include <string> 16 #include <vector> 17 18 #include "lldb/Core/LoadedModuleInfoList.h" 19 #include "lldb/Core/ModuleSpec.h" 20 #include "lldb/Core/ThreadSafeValue.h" 21 #include "lldb/Host/HostThread.h" 22 #include "lldb/Target/Process.h" 23 #include "lldb/Target/Thread.h" 24 #include "lldb/Utility/ArchSpec.h" 25 #include "lldb/Utility/Broadcaster.h" 26 #include "lldb/Utility/ConstString.h" 27 #include "lldb/Utility/GDBRemote.h" 28 #include "lldb/Utility/Status.h" 29 #include "lldb/Utility/StreamString.h" 30 #include "lldb/Utility/StringExtractor.h" 31 #include "lldb/Utility/StringList.h" 32 #include "lldb/Utility/StructuredData.h" 33 #include "lldb/lldb-private-forward.h" 34 35 #include "GDBRemoteCommunicationClient.h" 36 #include "GDBRemoteCommunicationReplayServer.h" 37 #include "GDBRemoteRegisterContext.h" 38 39 #include "llvm/ADT/DenseMap.h" 40 41 namespace lldb_private { 42 namespace repro { 43 class Loader; 44 } 45 namespace process_gdb_remote { 46 47 struct RemoteRegisterInfo { 48 ConstString name; 49 ConstString alt_name; 50 ConstString set_name; 51 uint32_t byte_size = LLDB_INVALID_INDEX32; 52 uint32_t byte_offset = LLDB_INVALID_INDEX32; 53 lldb::Encoding encoding = lldb::eEncodingUint; 54 lldb::Format format = lldb::eFormatHex; 55 uint32_t regnum_dwarf = LLDB_INVALID_REGNUM; 56 uint32_t regnum_ehframe = LLDB_INVALID_REGNUM; 57 uint32_t regnum_generic = LLDB_INVALID_REGNUM; 58 uint32_t regnum_remote = LLDB_INVALID_REGNUM; 59 std::vector<uint32_t> value_regs; 60 std::vector<uint32_t> invalidate_regs; 61 }; 62 63 class ThreadGDBRemote; 64 65 class ProcessGDBRemote : public Process, 66 private GDBRemoteClientBase::ContinueDelegate { 67 public: 68 ProcessGDBRemote(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp); 69 70 ~ProcessGDBRemote() override; 71 72 static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, 73 lldb::ListenerSP listener_sp, 74 const FileSpec *crash_file_path, 75 bool can_connect); 76 77 static void Initialize(); 78 79 static void DebuggerInitialize(Debugger &debugger); 80 81 static void Terminate(); 82 83 static ConstString GetPluginNameStatic(); 84 85 static const char *GetPluginDescriptionStatic(); 86 87 static std::chrono::seconds GetPacketTimeout(); 88 89 // Check if a given Process 90 bool CanDebug(lldb::TargetSP target_sp, 91 bool plugin_specified_by_name) override; 92 93 CommandObject *GetPluginCommandObject() override; 94 95 // Creating a new process, or attaching to an existing one 96 Status WillLaunch(Module *module) override; 97 98 Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override; 99 100 void DidLaunch() override; 101 102 Status WillAttachToProcessWithID(lldb::pid_t pid) override; 103 104 Status WillAttachToProcessWithName(const char *process_name, 105 bool wait_for_launch) override; 106 107 Status DoConnectRemote(llvm::StringRef remote_url) override; 108 109 Status WillLaunchOrAttach(); 110 111 Status DoAttachToProcessWithID(lldb::pid_t pid, 112 const ProcessAttachInfo &attach_info) override; 113 114 Status 115 DoAttachToProcessWithName(const char *process_name, 116 const ProcessAttachInfo &attach_info) override; 117 118 void DidAttach(ArchSpec &process_arch) override; 119 120 // PluginInterface protocol 121 ConstString GetPluginName() override; 122 123 // Process Control 124 Status WillResume() override; 125 126 Status DoResume() override; 127 128 Status DoHalt(bool &caused_stop) override; 129 130 Status DoDetach(bool keep_stopped) override; 131 132 bool DetachRequiresHalt() override { return true; } 133 134 Status DoSignal(int signal) override; 135 136 Status DoDestroy() override; 137 138 void RefreshStateAfterStop() override; 139 140 void SetUnixSignals(const lldb::UnixSignalsSP &signals_sp); 141 142 // Process Queries 143 bool IsAlive() override; 144 145 lldb::addr_t GetImageInfoAddress() override; 146 147 void WillPublicStop() override; 148 149 // Process Memory 150 size_t DoReadMemory(lldb::addr_t addr, void *buf, size_t size, 151 Status &error) override; 152 153 Status 154 WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) override; 155 156 size_t DoWriteMemory(lldb::addr_t addr, const void *buf, size_t size, 157 Status &error) override; 158 159 lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions, 160 Status &error) override; 161 162 Status GetMemoryRegionInfo(lldb::addr_t load_addr, 163 MemoryRegionInfo ®ion_info) override; 164 165 Status DoDeallocateMemory(lldb::addr_t ptr) override; 166 167 // Process STDIO 168 size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) override; 169 170 // Process Breakpoints 171 Status EnableBreakpointSite(BreakpointSite *bp_site) override; 172 173 Status DisableBreakpointSite(BreakpointSite *bp_site) override; 174 175 // Process Watchpoints 176 Status EnableWatchpoint(Watchpoint *wp, bool notify = true) override; 177 178 Status DisableWatchpoint(Watchpoint *wp, bool notify = true) override; 179 180 Status GetWatchpointSupportInfo(uint32_t &num) override; 181 182 llvm::Expected<TraceSupportedResponse> TraceSupported() override; 183 184 llvm::Error TraceStop(const TraceStopRequest &request) override; 185 186 llvm::Error TraceStart(const llvm::json::Value &request) override; 187 188 llvm::Expected<std::string> TraceGetState(llvm::StringRef type) override; 189 190 llvm::Expected<std::vector<uint8_t>> 191 TraceGetBinaryData(const TraceGetBinaryDataRequest &request) override; 192 193 Status GetWatchpointSupportInfo(uint32_t &num, bool &after) override; 194 195 bool StartNoticingNewThreads() override; 196 197 bool StopNoticingNewThreads() override; 198 199 GDBRemoteCommunicationClient &GetGDBRemote() { return m_gdb_comm; } 200 201 Status SendEventData(const char *data) override; 202 203 // Override DidExit so we can disconnect from the remote GDB server 204 void DidExit() override; 205 206 void SetUserSpecifiedMaxMemoryTransferSize(uint64_t user_specified_max); 207 208 bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch, 209 ModuleSpec &module_spec) override; 210 211 void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs, 212 const llvm::Triple &triple) override; 213 214 llvm::VersionTuple GetHostOSVersion() override; 215 llvm::VersionTuple GetHostMacCatalystVersion() override; 216 217 llvm::Error LoadModules() override; 218 219 llvm::Expected<LoadedModuleInfoList> GetLoadedModuleList() override; 220 221 Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded, 222 lldb::addr_t &load_addr) override; 223 224 void ModulesDidLoad(ModuleList &module_list) override; 225 226 StructuredData::ObjectSP 227 GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address, 228 lldb::addr_t image_count) override; 229 230 Status 231 ConfigureStructuredData(ConstString type_name, 232 const StructuredData::ObjectSP &config_sp) override; 233 234 StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos() override; 235 236 StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos( 237 const std::vector<lldb::addr_t> &load_addresses) override; 238 239 StructuredData::ObjectSP 240 GetLoadedDynamicLibrariesInfos_sender(StructuredData::ObjectSP args); 241 242 StructuredData::ObjectSP GetSharedCacheInfo() override; 243 244 std::string HarmonizeThreadIdsForProfileData( 245 StringExtractorGDBRemote &inputStringExtractor); 246 247 void DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) override; 248 void DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) override; 249 void DidVForkDone() override; 250 void DidExec() override; 251 252 llvm::Expected<bool> SaveCore(llvm::StringRef outfile) override; 253 254 protected: 255 friend class ThreadGDBRemote; 256 friend class GDBRemoteCommunicationClient; 257 friend class GDBRemoteRegisterContext; 258 259 bool SupportsMemoryTagging() override; 260 261 /// Broadcaster event bits definitions. 262 enum { 263 eBroadcastBitAsyncContinue = (1 << 0), 264 eBroadcastBitAsyncThreadShouldExit = (1 << 1), 265 eBroadcastBitAsyncThreadDidExit = (1 << 2) 266 }; 267 268 GDBRemoteCommunicationClient m_gdb_comm; 269 GDBRemoteCommunicationReplayServer m_gdb_replay_server; 270 std::atomic<lldb::pid_t> m_debugserver_pid; 271 272 llvm::Optional<StringExtractorGDBRemote> m_last_stop_packet; 273 std::recursive_mutex m_last_stop_packet_mutex; 274 275 GDBRemoteDynamicRegisterInfoSP m_register_info_sp; 276 Broadcaster m_async_broadcaster; 277 lldb::ListenerSP m_async_listener_sp; 278 HostThread m_async_thread; 279 std::recursive_mutex m_async_thread_state_mutex; 280 typedef std::vector<lldb::tid_t> tid_collection; 281 typedef std::vector<std::pair<lldb::tid_t, int>> tid_sig_collection; 282 typedef std::map<lldb::addr_t, lldb::addr_t> MMapMap; 283 typedef std::map<uint32_t, std::string> ExpeditedRegisterMap; 284 tid_collection m_thread_ids; // Thread IDs for all threads. This list gets 285 // updated after stopping 286 std::vector<lldb::addr_t> m_thread_pcs; // PC values for all the threads. 287 StructuredData::ObjectSP m_jstopinfo_sp; // Stop info only for any threads 288 // that have valid stop infos 289 StructuredData::ObjectSP m_jthreadsinfo_sp; // Full stop info, expedited 290 // registers and memory for all 291 // threads if "jThreadsInfo" 292 // packet is supported 293 tid_collection m_continue_c_tids; // 'c' for continue 294 tid_sig_collection m_continue_C_tids; // 'C' for continue with signal 295 tid_collection m_continue_s_tids; // 's' for step 296 tid_sig_collection m_continue_S_tids; // 'S' for step with signal 297 uint64_t m_max_memory_size; // The maximum number of bytes to read/write when 298 // reading and writing memory 299 uint64_t m_remote_stub_max_memory_size; // The maximum memory size the remote 300 // gdb stub can handle 301 MMapMap m_addr_to_mmap_size; 302 lldb::BreakpointSP m_thread_create_bp_sp; 303 bool m_waiting_for_attach; 304 bool m_destroy_tried_resuming; 305 lldb::CommandObjectSP m_command_sp; 306 int64_t m_breakpoint_pc_offset; 307 lldb::tid_t m_initial_tid; // The initial thread ID, given by stub on attach 308 bool m_use_g_packet_for_reading; 309 310 bool m_replay_mode; 311 bool m_allow_flash_writes; 312 using FlashRangeVector = lldb_private::RangeVector<lldb::addr_t, size_t>; 313 using FlashRange = FlashRangeVector::Entry; 314 FlashRangeVector m_erased_flash_ranges; 315 316 bool m_vfork_in_progress; 317 318 // Accessors 319 bool IsRunning(lldb::StateType state) { 320 return state == lldb::eStateRunning || IsStepping(state); 321 } 322 323 bool IsStepping(lldb::StateType state) { 324 return state == lldb::eStateStepping; 325 } 326 327 bool CanResume(lldb::StateType state) { return state == lldb::eStateStopped; } 328 329 bool HasExited(lldb::StateType state) { return state == lldb::eStateExited; } 330 331 bool ProcessIDIsValid() const; 332 333 void Clear(); 334 335 bool DoUpdateThreadList(ThreadList &old_thread_list, 336 ThreadList &new_thread_list) override; 337 338 Status ConnectToReplayServer(); 339 340 Status EstablishConnectionIfNeeded(const ProcessInfo &process_info); 341 342 Status LaunchAndConnectToDebugserver(const ProcessInfo &process_info); 343 344 void KillDebugserverProcess(); 345 346 void BuildDynamicRegisterInfo(bool force); 347 348 void SetLastStopPacket(const StringExtractorGDBRemote &response); 349 350 bool ParsePythonTargetDefinition(const FileSpec &target_definition_fspec); 351 352 DataExtractor GetAuxvData() override; 353 354 StructuredData::ObjectSP GetExtendedInfoForThread(lldb::tid_t tid); 355 356 void GetMaxMemorySize(); 357 358 bool CalculateThreadStopInfo(ThreadGDBRemote *thread); 359 360 size_t UpdateThreadPCsFromStopReplyThreadsValue(llvm::StringRef value); 361 362 size_t UpdateThreadIDsFromStopReplyThreadsValue(llvm::StringRef value); 363 364 bool HandleNotifyPacket(StringExtractorGDBRemote &packet); 365 366 bool StartAsyncThread(); 367 368 void StopAsyncThread(); 369 370 static lldb::thread_result_t AsyncThread(void *arg); 371 372 static bool 373 MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp, 374 lldb::pid_t pid, bool exited, int signo, 375 int exit_status); 376 377 lldb::StateType SetThreadStopInfo(StringExtractor &stop_packet); 378 379 bool 380 GetThreadStopInfoFromJSON(ThreadGDBRemote *thread, 381 const StructuredData::ObjectSP &thread_infos_sp); 382 383 lldb::ThreadSP SetThreadStopInfo(StructuredData::Dictionary *thread_dict); 384 385 lldb::ThreadSP 386 SetThreadStopInfo(lldb::tid_t tid, 387 ExpeditedRegisterMap &expedited_register_map, uint8_t signo, 388 const std::string &thread_name, const std::string &reason, 389 const std::string &description, uint32_t exc_type, 390 const std::vector<lldb::addr_t> &exc_data, 391 lldb::addr_t thread_dispatch_qaddr, bool queue_vars_valid, 392 lldb_private::LazyBool associated_with_libdispatch_queue, 393 lldb::addr_t dispatch_queue_t, std::string &queue_name, 394 lldb::QueueKind queue_kind, uint64_t queue_serial); 395 396 void HandleStopReplySequence(); 397 398 void ClearThreadIDList(); 399 400 bool UpdateThreadIDList(); 401 402 void DidLaunchOrAttach(ArchSpec &process_arch); 403 void MaybeLoadExecutableModule(); 404 405 Status ConnectToDebugserver(llvm::StringRef host_port); 406 407 const char *GetDispatchQueueNameForThread(lldb::addr_t thread_dispatch_qaddr, 408 std::string &dispatch_queue_name); 409 410 DynamicLoader *GetDynamicLoader() override; 411 412 bool GetGDBServerRegisterInfoXMLAndProcess( 413 ArchSpec &arch_to_use, std::string xml_filename, 414 std::vector<RemoteRegisterInfo> ®isters); 415 416 // Convert RemoteRegisterInfos into RegisterInfos and add to the dynamic 417 // register list. 418 void AddRemoteRegisters(std::vector<RemoteRegisterInfo> ®isters, 419 const ArchSpec &arch_to_use); 420 // Query remote GDBServer for register information 421 bool GetGDBServerRegisterInfo(ArchSpec &arch); 422 423 lldb::ModuleSP LoadModuleAtAddress(const FileSpec &file, 424 lldb::addr_t link_map, 425 lldb::addr_t base_addr, 426 bool value_is_offset); 427 428 Status UpdateAutomaticSignalFiltering() override; 429 430 Status FlashErase(lldb::addr_t addr, size_t size); 431 432 Status FlashDone(); 433 434 bool HasErased(FlashRange range); 435 436 llvm::Expected<std::vector<uint8_t>> 437 DoReadMemoryTags(lldb::addr_t addr, size_t len, int32_t type) override; 438 439 Status DoWriteMemoryTags(lldb::addr_t addr, size_t len, int32_t type, 440 const std::vector<uint8_t> &tags) override; 441 442 private: 443 // For ProcessGDBRemote only 444 std::string m_partial_profile_data; 445 std::map<uint64_t, uint32_t> m_thread_id_to_used_usec_map; 446 uint64_t m_last_signals_version = 0; 447 448 static bool NewThreadNotifyBreakpointHit(void *baton, 449 StoppointCallbackContext *context, 450 lldb::user_id_t break_id, 451 lldb::user_id_t break_loc_id); 452 453 // ContinueDelegate interface 454 void HandleAsyncStdout(llvm::StringRef out) override; 455 void HandleAsyncMisc(llvm::StringRef data) override; 456 void HandleStopReply() override; 457 void HandleAsyncStructuredDataPacket(llvm::StringRef data) override; 458 459 void SetThreadPc(const lldb::ThreadSP &thread_sp, uint64_t index); 460 using ModuleCacheKey = std::pair<std::string, std::string>; 461 // KeyInfo for the cached module spec DenseMap. 462 // The invariant is that all real keys will have the file and architecture 463 // set. 464 // The empty key has an empty file and an empty arch. 465 // The tombstone key has an invalid arch and an empty file. 466 // The comparison and hash functions take the file name and architecture 467 // triple into account. 468 struct ModuleCacheInfo { 469 static ModuleCacheKey getEmptyKey() { return ModuleCacheKey(); } 470 471 static ModuleCacheKey getTombstoneKey() { return ModuleCacheKey("", "T"); } 472 473 static unsigned getHashValue(const ModuleCacheKey &key) { 474 return llvm::hash_combine(key.first, key.second); 475 } 476 477 static bool isEqual(const ModuleCacheKey &LHS, const ModuleCacheKey &RHS) { 478 return LHS == RHS; 479 } 480 }; 481 482 llvm::DenseMap<ModuleCacheKey, ModuleSpec, ModuleCacheInfo> 483 m_cached_module_specs; 484 485 ProcessGDBRemote(const ProcessGDBRemote &) = delete; 486 const ProcessGDBRemote &operator=(const ProcessGDBRemote &) = delete; 487 488 // fork helpers 489 void DidForkSwitchSoftwareBreakpoints(bool enable); 490 void DidForkSwitchHardwareTraps(bool enable); 491 }; 492 493 } // namespace process_gdb_remote 494 } // namespace lldb_private 495 496 #endif // LLDB_SOURCE_PLUGINS_PROCESS_GDB_REMOTE_PROCESSGDBREMOTE_H 497