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