1 //===-- ProcessGDBRemote.h --------------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #ifndef liblldb_ProcessGDBRemote_h_ 11 #define liblldb_ProcessGDBRemote_h_ 12 13 #include <atomic> 14 #include <map> 15 #include <mutex> 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/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/Status.h" 29 #include "lldb/Utility/StreamGDBRemote.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 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 //------------------------------------------------------------------ 72 // Check if a given Process 73 //------------------------------------------------------------------ 74 bool CanDebug(lldb::TargetSP target_sp, 75 bool plugin_specified_by_name) override; 76 77 CommandObject *GetPluginCommandObject() override; 78 79 //------------------------------------------------------------------ 80 // Creating a new process, or attaching to an existing one 81 //------------------------------------------------------------------ 82 Status WillLaunch(Module *module) override; 83 84 Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override; 85 86 void DidLaunch() override; 87 88 Status WillAttachToProcessWithID(lldb::pid_t pid) override; 89 90 Status WillAttachToProcessWithName(const char *process_name, 91 bool wait_for_launch) override; 92 93 Status DoConnectRemote(Stream *strm, llvm::StringRef remote_url) override; 94 95 Status WillLaunchOrAttach(); 96 97 Status DoAttachToProcessWithID(lldb::pid_t pid, 98 const ProcessAttachInfo &attach_info) override; 99 100 Status 101 DoAttachToProcessWithName(const char *process_name, 102 const ProcessAttachInfo &attach_info) override; 103 104 void DidAttach(ArchSpec &process_arch) override; 105 106 //------------------------------------------------------------------ 107 // PluginInterface protocol 108 //------------------------------------------------------------------ 109 ConstString GetPluginName() override; 110 111 uint32_t GetPluginVersion() override; 112 113 //------------------------------------------------------------------ 114 // Process Control 115 //------------------------------------------------------------------ 116 Status WillResume() override; 117 118 Status DoResume() override; 119 120 Status DoHalt(bool &caused_stop) override; 121 122 Status DoDetach(bool keep_stopped) override; 123 DetachRequiresHalt()124 bool DetachRequiresHalt() override { return true; } 125 126 Status DoSignal(int signal) override; 127 128 Status DoDestroy() override; 129 130 void RefreshStateAfterStop() override; 131 132 void SetUnixSignals(const lldb::UnixSignalsSP &signals_sp); 133 134 //------------------------------------------------------------------ 135 // Process Queries 136 //------------------------------------------------------------------ 137 bool IsAlive() override; 138 139 lldb::addr_t GetImageInfoAddress() override; 140 141 void WillPublicStop() override; 142 143 //------------------------------------------------------------------ 144 // Process Memory 145 //------------------------------------------------------------------ 146 size_t DoReadMemory(lldb::addr_t addr, void *buf, size_t size, 147 Status &error) override; 148 149 Status 150 WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) override; 151 152 size_t DoWriteMemory(lldb::addr_t addr, const void *buf, size_t size, 153 Status &error) override; 154 155 lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions, 156 Status &error) override; 157 158 Status GetMemoryRegionInfo(lldb::addr_t load_addr, 159 MemoryRegionInfo ®ion_info) override; 160 161 Status DoDeallocateMemory(lldb::addr_t ptr) override; 162 163 //------------------------------------------------------------------ 164 // Process STDIO 165 //------------------------------------------------------------------ 166 size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) override; 167 168 //---------------------------------------------------------------------- 169 // Process Breakpoints 170 //---------------------------------------------------------------------- 171 Status EnableBreakpointSite(BreakpointSite *bp_site) override; 172 173 Status DisableBreakpointSite(BreakpointSite *bp_site) override; 174 175 //---------------------------------------------------------------------- 176 // Process Watchpoints 177 //---------------------------------------------------------------------- 178 Status EnableWatchpoint(Watchpoint *wp, bool notify = true) override; 179 180 Status DisableWatchpoint(Watchpoint *wp, bool notify = true) override; 181 182 Status GetWatchpointSupportInfo(uint32_t &num) override; 183 184 lldb::user_id_t StartTrace(const TraceOptions &options, 185 Status &error) override; 186 187 Status StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) override; 188 189 Status GetData(lldb::user_id_t uid, lldb::tid_t thread_id, 190 llvm::MutableArrayRef<uint8_t> &buffer, 191 size_t offset = 0) override; 192 193 Status GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id, 194 llvm::MutableArrayRef<uint8_t> &buffer, 195 size_t offset = 0) override; 196 197 Status GetTraceConfig(lldb::user_id_t uid, TraceOptions &options) override; 198 199 Status GetWatchpointSupportInfo(uint32_t &num, bool &after) override; 200 201 bool StartNoticingNewThreads() override; 202 203 bool StopNoticingNewThreads() override; 204 GetGDBRemote()205 GDBRemoteCommunicationClient &GetGDBRemote() { return m_gdb_comm; } 206 207 Status SendEventData(const char *data) override; 208 209 //---------------------------------------------------------------------- 210 // Override DidExit so we can disconnect from the remote GDB server 211 //---------------------------------------------------------------------- 212 void DidExit() override; 213 214 void SetUserSpecifiedMaxMemoryTransferSize(uint64_t user_specified_max); 215 216 bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch, 217 ModuleSpec &module_spec) override; 218 219 void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs, 220 const llvm::Triple &triple) override; 221 222 llvm::VersionTuple GetHostOSVersion() override; 223 224 size_t LoadModules(LoadedModuleInfoList &module_list) override; 225 226 size_t LoadModules() override; 227 228 Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded, 229 lldb::addr_t &load_addr) override; 230 231 void ModulesDidLoad(ModuleList &module_list) override; 232 233 StructuredData::ObjectSP 234 GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address, 235 lldb::addr_t image_count) override; 236 237 Status 238 ConfigureStructuredData(const ConstString &type_name, 239 const StructuredData::ObjectSP &config_sp) override; 240 241 StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos() override; 242 243 StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos( 244 const std::vector<lldb::addr_t> &load_addresses) override; 245 246 StructuredData::ObjectSP 247 GetLoadedDynamicLibrariesInfos_sender(StructuredData::ObjectSP args); 248 249 StructuredData::ObjectSP GetSharedCacheInfo() override; 250 251 std::string HarmonizeThreadIdsForProfileData( 252 StringExtractorGDBRemote &inputStringExtractor); 253 254 protected: 255 friend class ThreadGDBRemote; 256 friend class GDBRemoteCommunicationClient; 257 friend class GDBRemoteRegisterContext; 258 259 //------------------------------------------------------------------ 260 /// Broadcaster event bits definitions. 261 //------------------------------------------------------------------ 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 std::vector<StringExtractorGDBRemote> m_stop_packet_stack; // The stop packet 272 // stack replaces 273 // the last stop 274 // packet variable 275 std::recursive_mutex m_last_stop_packet_mutex; 276 GDBRemoteDynamicRegisterInfo m_register_info; 277 Broadcaster m_async_broadcaster; 278 lldb::ListenerSP m_async_listener_sp; 279 HostThread m_async_thread; 280 std::recursive_mutex m_async_thread_state_mutex; 281 typedef std::vector<lldb::tid_t> tid_collection; 282 typedef std::vector<std::pair<lldb::tid_t, int>> tid_sig_collection; 283 typedef std::map<lldb::addr_t, lldb::addr_t> MMapMap; 284 typedef std::map<uint32_t, std::string> ExpeditedRegisterMap; 285 tid_collection m_thread_ids; // Thread IDs for all threads. This list gets 286 // updated after stopping 287 std::vector<lldb::addr_t> m_thread_pcs; // PC values for all the threads. 288 StructuredData::ObjectSP m_jstopinfo_sp; // Stop info only for any threads 289 // that have valid stop infos 290 StructuredData::ObjectSP m_jthreadsinfo_sp; // Full stop info, expedited 291 // registers and memory for all 292 // threads if "jThreadsInfo" 293 // packet is supported 294 tid_collection m_continue_c_tids; // 'c' for continue 295 tid_sig_collection m_continue_C_tids; // 'C' for continue with signal 296 tid_collection m_continue_s_tids; // 's' for step 297 tid_sig_collection m_continue_S_tids; // 'S' for step with signal 298 uint64_t m_max_memory_size; // The maximum number of bytes to read/write when 299 // reading and writing memory 300 uint64_t m_remote_stub_max_memory_size; // The maximum memory size the remote 301 // gdb stub can handle 302 MMapMap m_addr_to_mmap_size; 303 lldb::BreakpointSP m_thread_create_bp_sp; 304 bool m_waiting_for_attach; 305 bool m_destroy_tried_resuming; 306 lldb::CommandObjectSP m_command_sp; 307 int64_t m_breakpoint_pc_offset; 308 lldb::tid_t m_initial_tid; // The initial thread ID, given by stub on attach 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 //---------------------------------------------------------------------- 317 // Accessors 318 //---------------------------------------------------------------------- IsRunning(lldb::StateType state)319 bool IsRunning(lldb::StateType state) { 320 return state == lldb::eStateRunning || IsStepping(state); 321 } 322 IsStepping(lldb::StateType state)323 bool IsStepping(lldb::StateType state) { 324 return state == lldb::eStateStepping; 325 } 326 CanResume(lldb::StateType state)327 bool CanResume(lldb::StateType state) { return state == lldb::eStateStopped; } 328 HasExited(lldb::StateType state)329 bool HasExited(lldb::StateType state) { return state == lldb::eStateExited; } 330 331 bool ProcessIDIsValid() const; 332 333 void Clear(); 334 335 bool UpdateThreadList(ThreadList &old_thread_list, 336 ThreadList &new_thread_list) override; 337 338 Status ConnectToReplayServer(repro::Loader *loader); 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 const lldb::DataBufferSP 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(std::string &value); 361 362 size_t UpdateThreadIDsFromStopReplyThreadsValue(std::string &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 404 Status ConnectToDebugserver(llvm::StringRef host_port); 405 406 const char *GetDispatchQueueNameForThread(lldb::addr_t thread_dispatch_qaddr, 407 std::string &dispatch_queue_name); 408 409 DynamicLoader *GetDynamicLoader() override; 410 411 // Query remote GDBServer for register information 412 bool GetGDBServerRegisterInfo(ArchSpec &arch); 413 414 // Query remote GDBServer for a detailed loaded library list 415 Status GetLoadedModuleList(LoadedModuleInfoList &); 416 417 lldb::ModuleSP LoadModuleAtAddress(const FileSpec &file, 418 lldb::addr_t link_map, 419 lldb::addr_t base_addr, 420 bool value_is_offset); 421 422 Status UpdateAutomaticSignalFiltering() override; 423 424 Status FlashErase(lldb::addr_t addr, size_t size); 425 426 Status FlashDone(); 427 428 bool HasErased(FlashRange range); 429 430 private: 431 //------------------------------------------------------------------ 432 // For ProcessGDBRemote only 433 //------------------------------------------------------------------ 434 std::string m_partial_profile_data; 435 std::map<uint64_t, uint32_t> m_thread_id_to_used_usec_map; 436 uint64_t m_last_signals_version = 0; 437 438 static bool NewThreadNotifyBreakpointHit(void *baton, 439 StoppointCallbackContext *context, 440 lldb::user_id_t break_id, 441 lldb::user_id_t break_loc_id); 442 443 //------------------------------------------------------------------ 444 // ContinueDelegate interface 445 //------------------------------------------------------------------ 446 void HandleAsyncStdout(llvm::StringRef out) override; 447 void HandleAsyncMisc(llvm::StringRef data) override; 448 void HandleStopReply() override; 449 void HandleAsyncStructuredDataPacket(llvm::StringRef data) override; 450 451 void SetThreadPc(const lldb::ThreadSP &thread_sp, uint64_t index); 452 using ModuleCacheKey = std::pair<std::string, std::string>; 453 // KeyInfo for the cached module spec DenseMap. 454 // The invariant is that all real keys will have the file and architecture 455 // set. 456 // The empty key has an empty file and an empty arch. 457 // The tombstone key has an invalid arch and an empty file. 458 // The comparison and hash functions take the file name and architecture 459 // triple into account. 460 struct ModuleCacheInfo { getEmptyKeyModuleCacheInfo461 static ModuleCacheKey getEmptyKey() { return ModuleCacheKey(); } 462 getTombstoneKeyModuleCacheInfo463 static ModuleCacheKey getTombstoneKey() { return ModuleCacheKey("", "T"); } 464 getHashValueModuleCacheInfo465 static unsigned getHashValue(const ModuleCacheKey &key) { 466 return llvm::hash_combine(key.first, key.second); 467 } 468 isEqualModuleCacheInfo469 static bool isEqual(const ModuleCacheKey &LHS, const ModuleCacheKey &RHS) { 470 return LHS == RHS; 471 } 472 }; 473 474 llvm::DenseMap<ModuleCacheKey, ModuleSpec, ModuleCacheInfo> 475 m_cached_module_specs; 476 477 DISALLOW_COPY_AND_ASSIGN(ProcessGDBRemote); 478 }; 479 480 } // namespace process_gdb_remote 481 } // namespace lldb_private 482 483 #endif // liblldb_ProcessGDBRemote_h_ 484