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