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