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