1 //===-- ProcessGDBRemote.h --------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef liblldb_ProcessGDBRemote_h_
10 #define liblldb_ProcessGDBRemote_h_
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/Status.h"
28 #include "lldb/Utility/StreamGDBRemote.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"
35 #include "GDBRemoteCommunicationClient.h"
36 #include "GDBRemoteCommunicationReplayServer.h"
37 #include "GDBRemoteRegisterContext.h"
39 #include "llvm/ADT/DenseMap.h"
41 namespace lldb_private {
45 namespace process_gdb_remote {
47 class ThreadGDBRemote;
49 class ProcessGDBRemote : public Process,
50 private GDBRemoteClientBase::ContinueDelegate {
52 ProcessGDBRemote(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp);
54 ~ProcessGDBRemote() override;
56 static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp,
57 lldb::ListenerSP listener_sp,
58 const FileSpec *crash_file_path);
60 static void Initialize();
62 static void DebuggerInitialize(Debugger &debugger);
64 static void Terminate();
66 static ConstString GetPluginNameStatic();
68 static const char *GetPluginDescriptionStatic();
70 // Check if a given Process
71 bool CanDebug(lldb::TargetSP target_sp,
72 bool plugin_specified_by_name) override;
74 CommandObject *GetPluginCommandObject() override;
76 // Creating a new process, or attaching to an existing one
77 Status WillLaunch(Module *module) override;
79 Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override;
81 void DidLaunch() override;
83 Status WillAttachToProcessWithID(lldb::pid_t pid) override;
85 Status WillAttachToProcessWithName(const char *process_name,
86 bool wait_for_launch) override;
88 Status DoConnectRemote(Stream *strm, llvm::StringRef remote_url) override;
90 Status WillLaunchOrAttach();
92 Status DoAttachToProcessWithID(lldb::pid_t pid,
93 const ProcessAttachInfo &attach_info) override;
96 DoAttachToProcessWithName(const char *process_name,
97 const ProcessAttachInfo &attach_info) override;
99 void DidAttach(ArchSpec &process_arch) override;
101 // PluginInterface protocol
102 ConstString GetPluginName() override;
104 uint32_t GetPluginVersion() override;
107 Status WillResume() override;
109 Status DoResume() override;
111 Status DoHalt(bool &caused_stop) override;
113 Status DoDetach(bool keep_stopped) override;
115 bool DetachRequiresHalt() override { return true; }
117 Status DoSignal(int signal) override;
119 Status DoDestroy() override;
121 void RefreshStateAfterStop() override;
123 void SetUnixSignals(const lldb::UnixSignalsSP &signals_sp);
126 bool IsAlive() override;
128 lldb::addr_t GetImageInfoAddress() override;
130 void WillPublicStop() override;
133 size_t DoReadMemory(lldb::addr_t addr, void *buf, size_t size,
134 Status &error) override;
137 WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) override;
139 size_t DoWriteMemory(lldb::addr_t addr, const void *buf, size_t size,
140 Status &error) override;
142 lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions,
143 Status &error) override;
145 Status GetMemoryRegionInfo(lldb::addr_t load_addr,
146 MemoryRegionInfo ®ion_info) override;
148 Status DoDeallocateMemory(lldb::addr_t ptr) override;
151 size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) override;
153 // Process Breakpoints
154 Status EnableBreakpointSite(BreakpointSite *bp_site) override;
156 Status DisableBreakpointSite(BreakpointSite *bp_site) override;
158 // Process Watchpoints
159 Status EnableWatchpoint(Watchpoint *wp, bool notify = true) override;
161 Status DisableWatchpoint(Watchpoint *wp, bool notify = true) override;
163 Status GetWatchpointSupportInfo(uint32_t &num) override;
165 lldb::user_id_t StartTrace(const TraceOptions &options,
166 Status &error) override;
168 Status StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) override;
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;
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;
178 Status GetTraceConfig(lldb::user_id_t uid, TraceOptions &options) override;
180 Status GetWatchpointSupportInfo(uint32_t &num, bool &after) override;
182 bool StartNoticingNewThreads() override;
184 bool StopNoticingNewThreads() override;
186 GDBRemoteCommunicationClient &GetGDBRemote() { return m_gdb_comm; }
188 Status SendEventData(const char *data) override;
190 // Override DidExit so we can disconnect from the remote GDB server
191 void DidExit() override;
193 void SetUserSpecifiedMaxMemoryTransferSize(uint64_t user_specified_max);
195 bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch,
196 ModuleSpec &module_spec) override;
198 void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,
199 const llvm::Triple &triple) override;
201 llvm::VersionTuple GetHostOSVersion() override;
203 size_t LoadModules(LoadedModuleInfoList &module_list) override;
205 size_t LoadModules() override;
207 Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded,
208 lldb::addr_t &load_addr) override;
210 void ModulesDidLoad(ModuleList &module_list) override;
212 StructuredData::ObjectSP
213 GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,
214 lldb::addr_t image_count) override;
217 ConfigureStructuredData(ConstString type_name,
218 const StructuredData::ObjectSP &config_sp) override;
220 StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos() override;
222 StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(
223 const std::vector<lldb::addr_t> &load_addresses) override;
225 StructuredData::ObjectSP
226 GetLoadedDynamicLibrariesInfos_sender(StructuredData::ObjectSP args);
228 StructuredData::ObjectSP GetSharedCacheInfo() override;
230 std::string HarmonizeThreadIdsForProfileData(
231 StringExtractorGDBRemote &inputStringExtractor);
234 friend class ThreadGDBRemote;
235 friend class GDBRemoteCommunicationClient;
236 friend class GDBRemoteRegisterContext;
238 /// Broadcaster event bits definitions.
240 eBroadcastBitAsyncContinue = (1 << 0),
241 eBroadcastBitAsyncThreadShouldExit = (1 << 1),
242 eBroadcastBitAsyncThreadDidExit = (1 << 2)
245 GDBRemoteCommunicationClient m_gdb_comm;
246 GDBRemoteCommunicationReplayServer m_gdb_replay_server;
247 std::atomic<lldb::pid_t> m_debugserver_pid;
248 std::vector<StringExtractorGDBRemote> m_stop_packet_stack; // The stop packet
252 std::recursive_mutex m_last_stop_packet_mutex;
253 GDBRemoteDynamicRegisterInfo m_register_info;
254 Broadcaster m_async_broadcaster;
255 lldb::ListenerSP m_async_listener_sp;
256 HostThread m_async_thread;
257 std::recursive_mutex m_async_thread_state_mutex;
258 typedef std::vector<lldb::tid_t> tid_collection;
259 typedef std::vector<std::pair<lldb::tid_t, int>> tid_sig_collection;
260 typedef std::map<lldb::addr_t, lldb::addr_t> MMapMap;
261 typedef std::map<uint32_t, std::string> ExpeditedRegisterMap;
262 tid_collection m_thread_ids; // Thread IDs for all threads. This list gets
263 // updated after stopping
264 std::vector<lldb::addr_t> m_thread_pcs; // PC values for all the threads.
265 StructuredData::ObjectSP m_jstopinfo_sp; // Stop info only for any threads
266 // that have valid stop infos
267 StructuredData::ObjectSP m_jthreadsinfo_sp; // Full stop info, expedited
268 // registers and memory for all
269 // threads if "jThreadsInfo"
270 // packet is supported
271 tid_collection m_continue_c_tids; // 'c' for continue
272 tid_sig_collection m_continue_C_tids; // 'C' for continue with signal
273 tid_collection m_continue_s_tids; // 's' for step
274 tid_sig_collection m_continue_S_tids; // 'S' for step with signal
275 uint64_t m_max_memory_size; // The maximum number of bytes to read/write when
276 // reading and writing memory
277 uint64_t m_remote_stub_max_memory_size; // The maximum memory size the remote
278 // gdb stub can handle
279 MMapMap m_addr_to_mmap_size;
280 lldb::BreakpointSP m_thread_create_bp_sp;
281 bool m_waiting_for_attach;
282 bool m_destroy_tried_resuming;
283 lldb::CommandObjectSP m_command_sp;
284 int64_t m_breakpoint_pc_offset;
285 lldb::tid_t m_initial_tid; // The initial thread ID, given by stub on attach
288 bool m_allow_flash_writes;
289 using FlashRangeVector = lldb_private::RangeVector<lldb::addr_t, size_t>;
290 using FlashRange = FlashRangeVector::Entry;
291 FlashRangeVector m_erased_flash_ranges;
294 bool IsRunning(lldb::StateType state) {
295 return state == lldb::eStateRunning || IsStepping(state);
298 bool IsStepping(lldb::StateType state) {
299 return state == lldb::eStateStepping;
302 bool CanResume(lldb::StateType state) { return state == lldb::eStateStopped; }
304 bool HasExited(lldb::StateType state) { return state == lldb::eStateExited; }
306 bool ProcessIDIsValid() const;
310 bool UpdateThreadList(ThreadList &old_thread_list,
311 ThreadList &new_thread_list) override;
313 Status ConnectToReplayServer(repro::Loader *loader);
315 Status EstablishConnectionIfNeeded(const ProcessInfo &process_info);
317 Status LaunchAndConnectToDebugserver(const ProcessInfo &process_info);
319 void KillDebugserverProcess();
321 void BuildDynamicRegisterInfo(bool force);
323 void SetLastStopPacket(const StringExtractorGDBRemote &response);
325 bool ParsePythonTargetDefinition(const FileSpec &target_definition_fspec);
327 DataExtractor GetAuxvData() override;
329 StructuredData::ObjectSP GetExtendedInfoForThread(lldb::tid_t tid);
331 void GetMaxMemorySize();
333 bool CalculateThreadStopInfo(ThreadGDBRemote *thread);
335 size_t UpdateThreadPCsFromStopReplyThreadsValue(std::string &value);
337 size_t UpdateThreadIDsFromStopReplyThreadsValue(std::string &value);
339 bool HandleNotifyPacket(StringExtractorGDBRemote &packet);
341 bool StartAsyncThread();
343 void StopAsyncThread();
345 static lldb::thread_result_t AsyncThread(void *arg);
348 MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp,
349 lldb::pid_t pid, bool exited, int signo,
352 lldb::StateType SetThreadStopInfo(StringExtractor &stop_packet);
355 GetThreadStopInfoFromJSON(ThreadGDBRemote *thread,
356 const StructuredData::ObjectSP &thread_infos_sp);
358 lldb::ThreadSP SetThreadStopInfo(StructuredData::Dictionary *thread_dict);
361 SetThreadStopInfo(lldb::tid_t tid,
362 ExpeditedRegisterMap &expedited_register_map, uint8_t signo,
363 const std::string &thread_name, const std::string &reason,
364 const std::string &description, uint32_t exc_type,
365 const std::vector<lldb::addr_t> &exc_data,
366 lldb::addr_t thread_dispatch_qaddr, bool queue_vars_valid,
367 lldb_private::LazyBool associated_with_libdispatch_queue,
368 lldb::addr_t dispatch_queue_t, std::string &queue_name,
369 lldb::QueueKind queue_kind, uint64_t queue_serial);
371 void HandleStopReplySequence();
373 void ClearThreadIDList();
375 bool UpdateThreadIDList();
377 void DidLaunchOrAttach(ArchSpec &process_arch);
379 Status ConnectToDebugserver(llvm::StringRef host_port);
381 const char *GetDispatchQueueNameForThread(lldb::addr_t thread_dispatch_qaddr,
382 std::string &dispatch_queue_name);
384 DynamicLoader *GetDynamicLoader() override;
386 bool GetGDBServerRegisterInfoXMLAndProcess(ArchSpec &arch_to_use,
387 std::string xml_filename,
388 uint32_t &cur_reg_num,
389 uint32_t ®_offset);
391 // Query remote GDBServer for register information
392 bool GetGDBServerRegisterInfo(ArchSpec &arch);
394 // Query remote GDBServer for a detailed loaded library list
395 Status GetLoadedModuleList(LoadedModuleInfoList &);
397 lldb::ModuleSP LoadModuleAtAddress(const FileSpec &file,
398 lldb::addr_t link_map,
399 lldb::addr_t base_addr,
400 bool value_is_offset);
402 Status UpdateAutomaticSignalFiltering() override;
404 Status FlashErase(lldb::addr_t addr, size_t size);
408 bool HasErased(FlashRange range);
411 // For ProcessGDBRemote only
412 std::string m_partial_profile_data;
413 std::map<uint64_t, uint32_t> m_thread_id_to_used_usec_map;
414 uint64_t m_last_signals_version = 0;
416 static bool NewThreadNotifyBreakpointHit(void *baton,
417 StoppointCallbackContext *context,
418 lldb::user_id_t break_id,
419 lldb::user_id_t break_loc_id);
421 // ContinueDelegate interface
422 void HandleAsyncStdout(llvm::StringRef out) override;
423 void HandleAsyncMisc(llvm::StringRef data) override;
424 void HandleStopReply() override;
425 void HandleAsyncStructuredDataPacket(llvm::StringRef data) override;
427 void SetThreadPc(const lldb::ThreadSP &thread_sp, uint64_t index);
428 using ModuleCacheKey = std::pair<std::string, std::string>;
429 // KeyInfo for the cached module spec DenseMap.
430 // The invariant is that all real keys will have the file and architecture
432 // The empty key has an empty file and an empty arch.
433 // The tombstone key has an invalid arch and an empty file.
434 // The comparison and hash functions take the file name and architecture
435 // triple into account.
436 struct ModuleCacheInfo {
437 static ModuleCacheKey getEmptyKey() { return ModuleCacheKey(); }
439 static ModuleCacheKey getTombstoneKey() { return ModuleCacheKey("", "T"); }
441 static unsigned getHashValue(const ModuleCacheKey &key) {
442 return llvm::hash_combine(key.first, key.second);
445 static bool isEqual(const ModuleCacheKey &LHS, const ModuleCacheKey &RHS) {
450 llvm::DenseMap<ModuleCacheKey, ModuleSpec, ModuleCacheInfo>
451 m_cached_module_specs;
453 DISALLOW_COPY_AND_ASSIGN(ProcessGDBRemote);
456 } // namespace process_gdb_remote
457 } // namespace lldb_private
459 #endif // liblldb_ProcessGDBRemote_h_