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 <optional>
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/DynamicRegisterInfo.h"
24 #include "lldb/Target/Process.h"
25 #include "lldb/Target/Thread.h"
26 #include "lldb/Utility/ArchSpec.h"
27 #include "lldb/Utility/Broadcaster.h"
28 #include "lldb/Utility/ConstString.h"
29 #include "lldb/Utility/GDBRemote.h"
30 #include "lldb/Utility/Status.h"
31 #include "lldb/Utility/StreamString.h"
32 #include "lldb/Utility/StringExtractor.h"
33 #include "lldb/Utility/StringList.h"
34 #include "lldb/Utility/StructuredData.h"
35 #include "lldb/lldb-private-forward.h"
36 
37 #include "GDBRemoteCommunicationClient.h"
38 #include "GDBRemoteRegisterContext.h"
39 
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/StringMap.h"
42 
43 namespace lldb_private {
44 namespace repro {
45 class Loader;
46 }
47 namespace process_gdb_remote {
48 
49 class ThreadGDBRemote;
50 
51 class ProcessGDBRemote : public Process,
52                          private GDBRemoteClientBase::ContinueDelegate {
53 public:
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 llvm::StringRef GetPluginNameStatic() { return "gdb-remote"; }
68 
69   static llvm::StringRef GetPluginDescriptionStatic();
70 
71   static std::chrono::seconds GetPacketTimeout();
72 
73   ArchSpec GetSystemArchitecture() override;
74 
75   // Check if a given Process
76   bool CanDebug(lldb::TargetSP target_sp,
77                 bool plugin_specified_by_name) override;
78 
79   CommandObject *GetPluginCommandObject() override;
80 
81   void DumpPluginHistory(Stream &s) override;
82 
83   // Creating a new process, or attaching to an existing one
84   Status DoWillLaunch(Module *module) override;
85 
86   Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override;
87 
88   void DidLaunch() override;
89 
90   Status DoWillAttachToProcessWithID(lldb::pid_t pid) override;
91 
92   Status DoWillAttachToProcessWithName(const char *process_name,
93                                        bool wait_for_launch) override;
94 
95   Status DoConnectRemote(llvm::StringRef remote_url) override;
96 
97   Status WillLaunchOrAttach();
98 
99   Status DoAttachToProcessWithID(lldb::pid_t pid,
100                                  const ProcessAttachInfo &attach_info) override;
101 
102   Status
103   DoAttachToProcessWithName(const char *process_name,
104                             const ProcessAttachInfo &attach_info) override;
105 
106   void DidAttach(ArchSpec &process_arch) override;
107 
108   // PluginInterface protocol
109   llvm::StringRef GetPluginName() override { return GetPluginNameStatic(); }
110 
111   // Process Control
112   Status WillResume() override;
113 
114   Status DoResume() override;
115 
116   Status DoHalt(bool &caused_stop) override;
117 
118   Status DoDetach(bool keep_stopped) override;
119 
120   bool DetachRequiresHalt() override { return true; }
121 
122   Status DoSignal(int signal) override;
123 
124   Status DoDestroy() override;
125 
126   void RefreshStateAfterStop() override;
127 
128   void SetUnixSignals(const lldb::UnixSignalsSP &signals_sp);
129 
130   // Process Queries
131   bool IsAlive() override;
132 
133   lldb::addr_t GetImageInfoAddress() override;
134 
135   void WillPublicStop() override;
136 
137   // Process Memory
138   size_t DoReadMemory(lldb::addr_t addr, void *buf, size_t size,
139                       Status &error) override;
140 
141   Status
142   WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) override;
143 
144   size_t DoWriteMemory(lldb::addr_t addr, const void *buf, size_t size,
145                        Status &error) override;
146 
147   lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions,
148                                 Status &error) override;
149 
150   Status DoDeallocateMemory(lldb::addr_t ptr) override;
151 
152   // Process STDIO
153   size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) override;
154 
155   // Process Breakpoints
156   Status EnableBreakpointSite(BreakpointSite *bp_site) override;
157 
158   Status DisableBreakpointSite(BreakpointSite *bp_site) override;
159 
160   // Process Watchpoints
161   Status EnableWatchpoint(Watchpoint *wp, bool notify = true) override;
162 
163   Status DisableWatchpoint(Watchpoint *wp, bool notify = true) override;
164 
165   std::optional<uint32_t> GetWatchpointSlotCount() override;
166 
167   llvm::Expected<TraceSupportedResponse> TraceSupported() override;
168 
169   llvm::Error TraceStop(const TraceStopRequest &request) override;
170 
171   llvm::Error TraceStart(const llvm::json::Value &request) override;
172 
173   llvm::Expected<std::string> TraceGetState(llvm::StringRef type) override;
174 
175   llvm::Expected<std::vector<uint8_t>>
176   TraceGetBinaryData(const TraceGetBinaryDataRequest &request) override;
177 
178   std::optional<bool> DoGetWatchpointReportedAfter() override;
179 
180   bool StartNoticingNewThreads() override;
181 
182   bool StopNoticingNewThreads() override;
183 
184   GDBRemoteCommunicationClient &GetGDBRemote() { return m_gdb_comm; }
185 
186   Status SendEventData(const char *data) override;
187 
188   // Override DidExit so we can disconnect from the remote GDB server
189   void DidExit() override;
190 
191   void SetUserSpecifiedMaxMemoryTransferSize(uint64_t user_specified_max);
192 
193   bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch,
194                      ModuleSpec &module_spec) override;
195 
196   void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,
197                            const llvm::Triple &triple) override;
198 
199   llvm::VersionTuple GetHostOSVersion() override;
200   llvm::VersionTuple GetHostMacCatalystVersion() override;
201 
202   llvm::Error LoadModules() override;
203 
204   llvm::Expected<LoadedModuleInfoList> GetLoadedModuleList() override;
205 
206   Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded,
207                             lldb::addr_t &load_addr) override;
208 
209   void ModulesDidLoad(ModuleList &module_list) override;
210 
211   StructuredData::ObjectSP
212   GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,
213                                  lldb::addr_t image_count) override;
214 
215   Status
216   ConfigureStructuredData(llvm::StringRef type_name,
217                           const StructuredData::ObjectSP &config_sp) override;
218 
219   StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos() override;
220 
221   StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(
222       const std::vector<lldb::addr_t> &load_addresses) override;
223 
224   StructuredData::ObjectSP
225   GetLoadedDynamicLibrariesInfos_sender(StructuredData::ObjectSP args);
226 
227   StructuredData::ObjectSP GetSharedCacheInfo() override;
228 
229   StructuredData::ObjectSP GetDynamicLoaderProcessState() override;
230 
231   std::string HarmonizeThreadIdsForProfileData(
232       StringExtractorGDBRemote &inputStringExtractor);
233 
234   void DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) override;
235   void DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) override;
236   void DidVForkDone() override;
237   void DidExec() override;
238 
239   llvm::Expected<bool> SaveCore(llvm::StringRef outfile) override;
240 
241 protected:
242   friend class ThreadGDBRemote;
243   friend class GDBRemoteCommunicationClient;
244   friend class GDBRemoteRegisterContext;
245 
246   ProcessGDBRemote(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp);
247 
248   bool SupportsMemoryTagging() override;
249 
250   /// Broadcaster event bits definitions.
251   enum {
252     eBroadcastBitAsyncContinue = (1 << 0),
253     eBroadcastBitAsyncThreadShouldExit = (1 << 1),
254     eBroadcastBitAsyncThreadDidExit = (1 << 2)
255   };
256 
257   GDBRemoteCommunicationClient m_gdb_comm;
258   std::atomic<lldb::pid_t> m_debugserver_pid;
259 
260   std::optional<StringExtractorGDBRemote> m_last_stop_packet;
261   std::recursive_mutex m_last_stop_packet_mutex;
262 
263   GDBRemoteDynamicRegisterInfoSP m_register_info_sp;
264   Broadcaster m_async_broadcaster;
265   lldb::ListenerSP m_async_listener_sp;
266   HostThread m_async_thread;
267   std::recursive_mutex m_async_thread_state_mutex;
268   typedef std::vector<lldb::tid_t> tid_collection;
269   typedef std::vector<std::pair<lldb::tid_t, int>> tid_sig_collection;
270   typedef std::map<lldb::addr_t, lldb::addr_t> MMapMap;
271   typedef std::map<uint32_t, std::string> ExpeditedRegisterMap;
272   tid_collection m_thread_ids; // Thread IDs for all threads. This list gets
273                                // updated after stopping
274   std::vector<lldb::addr_t> m_thread_pcs;     // PC values for all the threads.
275   StructuredData::ObjectSP m_jstopinfo_sp;    // Stop info only for any threads
276                                               // that have valid stop infos
277   StructuredData::ObjectSP m_jthreadsinfo_sp; // Full stop info, expedited
278                                               // registers and memory for all
279                                               // threads if "jThreadsInfo"
280                                               // packet is supported
281   tid_collection m_continue_c_tids;           // 'c' for continue
282   tid_sig_collection m_continue_C_tids;       // 'C' for continue with signal
283   tid_collection m_continue_s_tids;           // 's' for step
284   tid_sig_collection m_continue_S_tids;       // 'S' for step with signal
285   uint64_t m_max_memory_size; // The maximum number of bytes to read/write when
286                               // reading and writing memory
287   uint64_t m_remote_stub_max_memory_size; // The maximum memory size the remote
288                                           // gdb stub can handle
289   MMapMap m_addr_to_mmap_size;
290   lldb::BreakpointSP m_thread_create_bp_sp;
291   bool m_waiting_for_attach;
292   lldb::CommandObjectSP m_command_sp;
293   int64_t m_breakpoint_pc_offset;
294   lldb::tid_t m_initial_tid; // The initial thread ID, given by stub on attach
295   bool m_use_g_packet_for_reading;
296 
297   bool m_allow_flash_writes;
298   using FlashRangeVector = lldb_private::RangeVector<lldb::addr_t, size_t>;
299   using FlashRange = FlashRangeVector::Entry;
300   FlashRangeVector m_erased_flash_ranges;
301 
302   bool m_vfork_in_progress;
303 
304   // Accessors
305   bool IsRunning(lldb::StateType state) {
306     return state == lldb::eStateRunning || IsStepping(state);
307   }
308 
309   bool IsStepping(lldb::StateType state) {
310     return state == lldb::eStateStepping;
311   }
312 
313   bool CanResume(lldb::StateType state) { return state == lldb::eStateStopped; }
314 
315   bool HasExited(lldb::StateType state) { return state == lldb::eStateExited; }
316 
317   void Clear();
318 
319   bool DoUpdateThreadList(ThreadList &old_thread_list,
320                           ThreadList &new_thread_list) override;
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 StartAsyncThread();
347 
348   void StopAsyncThread();
349 
350   lldb::thread_result_t AsyncThread();
351 
352   static void
353   MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp,
354                             lldb::pid_t pid, int signo, int exit_status);
355 
356   lldb::StateType SetThreadStopInfo(StringExtractor &stop_packet);
357 
358   bool
359   GetThreadStopInfoFromJSON(ThreadGDBRemote *thread,
360                             const StructuredData::ObjectSP &thread_infos_sp);
361 
362   lldb::ThreadSP SetThreadStopInfo(StructuredData::Dictionary *thread_dict);
363 
364   lldb::ThreadSP
365   SetThreadStopInfo(lldb::tid_t tid,
366                     ExpeditedRegisterMap &expedited_register_map, uint8_t signo,
367                     const std::string &thread_name, const std::string &reason,
368                     const std::string &description, uint32_t exc_type,
369                     const std::vector<lldb::addr_t> &exc_data,
370                     lldb::addr_t thread_dispatch_qaddr, bool queue_vars_valid,
371                     lldb_private::LazyBool associated_with_libdispatch_queue,
372                     lldb::addr_t dispatch_queue_t, std::string &queue_name,
373                     lldb::QueueKind queue_kind, uint64_t queue_serial);
374 
375   void ClearThreadIDList();
376 
377   bool UpdateThreadIDList();
378 
379   void DidLaunchOrAttach(ArchSpec &process_arch);
380   void LoadStubBinaries();
381   void MaybeLoadExecutableModule();
382 
383   Status ConnectToDebugserver(llvm::StringRef host_port);
384 
385   const char *GetDispatchQueueNameForThread(lldb::addr_t thread_dispatch_qaddr,
386                                             std::string &dispatch_queue_name);
387 
388   DynamicLoader *GetDynamicLoader() override;
389 
390   bool GetGDBServerRegisterInfoXMLAndProcess(
391     ArchSpec &arch_to_use, std::string xml_filename,
392     std::vector<DynamicRegisterInfo::Register> &registers);
393 
394   // Convert DynamicRegisterInfo::Registers into RegisterInfos and add
395   // to the dynamic register list.
396   void AddRemoteRegisters(std::vector<DynamicRegisterInfo::Register> &registers,
397                           const ArchSpec &arch_to_use);
398   // Query remote GDBServer for register information
399   bool GetGDBServerRegisterInfo(ArchSpec &arch);
400 
401   lldb::ModuleSP LoadModuleAtAddress(const FileSpec &file,
402                                      lldb::addr_t link_map,
403                                      lldb::addr_t base_addr,
404                                      bool value_is_offset);
405 
406   Status UpdateAutomaticSignalFiltering() override;
407 
408   Status FlashErase(lldb::addr_t addr, size_t size);
409 
410   Status FlashDone();
411 
412   bool HasErased(FlashRange range);
413 
414   llvm::Expected<std::vector<uint8_t>>
415   DoReadMemoryTags(lldb::addr_t addr, size_t len, int32_t type) override;
416 
417   Status DoWriteMemoryTags(lldb::addr_t addr, size_t len, int32_t type,
418                            const std::vector<uint8_t> &tags) override;
419 
420   Status DoGetMemoryRegionInfo(lldb::addr_t load_addr,
421                                MemoryRegionInfo &region_info) 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   void DidForkSwitchHardwareTraps(bool enable);
472 
473   // Lists of register fields generated from the remote's target XML.
474   // Pointers to these RegisterFlags will be set in the register info passed
475   // back to the upper levels of lldb. Doing so is safe because this class will
476   // live at least as long as the debug session. We therefore do not store the
477   // data directly in the map because the map may reallocate it's storage as new
478   // entries are added. Which would invalidate any pointers set in the register
479   // info up to that point.
480   llvm::StringMap<std::unique_ptr<RegisterFlags>> m_registers_flags_types;
481 };
482 
483 } // namespace process_gdb_remote
484 } // namespace lldb_private
485 
486 #endif // LLDB_SOURCE_PLUGINS_PROCESS_GDB_REMOTE_PROCESSGDBREMOTE_H
487