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