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