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   ArchSpec GetSystemArchitecture() override;
74 
75   llvm::Optional<uint32_t> GetAddressingBits() override;
76 
77   // Check if a given Process
78   bool CanDebug(lldb::TargetSP target_sp,
79                 bool plugin_specified_by_name) override;
80 
81   CommandObject *GetPluginCommandObject() override;
82 
83   // Creating a new process, or attaching to an existing one
84   Status WillLaunch(Module *module) override;
85 
86   Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override;
87 
88   void DidLaunch() override;
89 
90   Status WillAttachToProcessWithID(lldb::pid_t pid) override;
91 
92   Status WillAttachToProcessWithName(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   Status GetWatchpointSupportInfo(uint32_t &num) 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   Status GetWatchpointSupportInfo(uint32_t &num, bool &after) 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(ConstString 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   std::string HarmonizeThreadIdsForProfileData(
230       StringExtractorGDBRemote &inputStringExtractor);
231 
232   void DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) override;
233   void DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) override;
234   void DidVForkDone() override;
235   void DidExec() override;
236 
237   llvm::Expected<bool> SaveCore(llvm::StringRef outfile) override;
238 
239 protected:
240   friend class ThreadGDBRemote;
241   friend class GDBRemoteCommunicationClient;
242   friend class GDBRemoteRegisterContext;
243 
244   bool SupportsMemoryTagging() override;
245 
246   /// Broadcaster event bits definitions.
247   enum {
248     eBroadcastBitAsyncContinue = (1 << 0),
249     eBroadcastBitAsyncThreadShouldExit = (1 << 1),
250     eBroadcastBitAsyncThreadDidExit = (1 << 2)
251   };
252 
253   GDBRemoteCommunicationClient m_gdb_comm;
254   std::atomic<lldb::pid_t> m_debugserver_pid;
255 
256   llvm::Optional<StringExtractorGDBRemote> m_last_stop_packet;
257   std::recursive_mutex m_last_stop_packet_mutex;
258 
259   GDBRemoteDynamicRegisterInfoSP m_register_info_sp;
260   Broadcaster m_async_broadcaster;
261   lldb::ListenerSP m_async_listener_sp;
262   HostThread m_async_thread;
263   std::recursive_mutex m_async_thread_state_mutex;
264   typedef std::vector<lldb::tid_t> tid_collection;
265   typedef std::vector<std::pair<lldb::tid_t, int>> tid_sig_collection;
266   typedef std::map<lldb::addr_t, lldb::addr_t> MMapMap;
267   typedef std::map<uint32_t, std::string> ExpeditedRegisterMap;
268   tid_collection m_thread_ids; // Thread IDs for all threads. This list gets
269                                // updated after stopping
270   std::vector<lldb::addr_t> m_thread_pcs;     // PC values for all the threads.
271   StructuredData::ObjectSP m_jstopinfo_sp;    // Stop info only for any threads
272                                               // that have valid stop infos
273   StructuredData::ObjectSP m_jthreadsinfo_sp; // Full stop info, expedited
274                                               // registers and memory for all
275                                               // threads if "jThreadsInfo"
276                                               // packet is supported
277   tid_collection m_continue_c_tids;           // 'c' for continue
278   tid_sig_collection m_continue_C_tids;       // 'C' for continue with signal
279   tid_collection m_continue_s_tids;           // 's' for step
280   tid_sig_collection m_continue_S_tids;       // 'S' for step with signal
281   uint64_t m_max_memory_size; // The maximum number of bytes to read/write when
282                               // reading and writing memory
283   uint64_t m_remote_stub_max_memory_size; // The maximum memory size the remote
284                                           // gdb stub can handle
285   MMapMap m_addr_to_mmap_size;
286   lldb::BreakpointSP m_thread_create_bp_sp;
287   bool m_waiting_for_attach;
288   lldb::CommandObjectSP m_command_sp;
289   int64_t m_breakpoint_pc_offset;
290   lldb::tid_t m_initial_tid; // The initial thread ID, given by stub on attach
291   bool m_use_g_packet_for_reading;
292 
293   bool m_allow_flash_writes;
294   using FlashRangeVector = lldb_private::RangeVector<lldb::addr_t, size_t>;
295   using FlashRange = FlashRangeVector::Entry;
296   FlashRangeVector m_erased_flash_ranges;
297 
298   bool m_vfork_in_progress;
299 
300   // Accessors
301   bool IsRunning(lldb::StateType state) {
302     return state == lldb::eStateRunning || IsStepping(state);
303   }
304 
305   bool IsStepping(lldb::StateType state) {
306     return state == lldb::eStateStepping;
307   }
308 
309   bool CanResume(lldb::StateType state) { return state == lldb::eStateStopped; }
310 
311   bool HasExited(lldb::StateType state) { return state == lldb::eStateExited; }
312 
313   bool ProcessIDIsValid() const;
314 
315   void Clear();
316 
317   bool DoUpdateThreadList(ThreadList &old_thread_list,
318                           ThreadList &new_thread_list) override;
319 
320   Status EstablishConnectionIfNeeded(const ProcessInfo &process_info);
321 
322   Status LaunchAndConnectToDebugserver(const ProcessInfo &process_info);
323 
324   void KillDebugserverProcess();
325 
326   void BuildDynamicRegisterInfo(bool force);
327 
328   void SetLastStopPacket(const StringExtractorGDBRemote &response);
329 
330   bool ParsePythonTargetDefinition(const FileSpec &target_definition_fspec);
331 
332   DataExtractor GetAuxvData() override;
333 
334   StructuredData::ObjectSP GetExtendedInfoForThread(lldb::tid_t tid);
335 
336   void GetMaxMemorySize();
337 
338   bool CalculateThreadStopInfo(ThreadGDBRemote *thread);
339 
340   size_t UpdateThreadPCsFromStopReplyThreadsValue(llvm::StringRef value);
341 
342   size_t UpdateThreadIDsFromStopReplyThreadsValue(llvm::StringRef value);
343 
344   bool StartAsyncThread();
345 
346   void StopAsyncThread();
347 
348   lldb::thread_result_t AsyncThread();
349 
350   static void
351   MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp,
352                             lldb::pid_t pid, int signo, int exit_status);
353 
354   lldb::StateType SetThreadStopInfo(StringExtractor &stop_packet);
355 
356   bool
357   GetThreadStopInfoFromJSON(ThreadGDBRemote *thread,
358                             const StructuredData::ObjectSP &thread_infos_sp);
359 
360   lldb::ThreadSP SetThreadStopInfo(StructuredData::Dictionary *thread_dict);
361 
362   lldb::ThreadSP
363   SetThreadStopInfo(lldb::tid_t tid,
364                     ExpeditedRegisterMap &expedited_register_map, uint8_t signo,
365                     const std::string &thread_name, const std::string &reason,
366                     const std::string &description, uint32_t exc_type,
367                     const std::vector<lldb::addr_t> &exc_data,
368                     lldb::addr_t thread_dispatch_qaddr, bool queue_vars_valid,
369                     lldb_private::LazyBool associated_with_libdispatch_queue,
370                     lldb::addr_t dispatch_queue_t, std::string &queue_name,
371                     lldb::QueueKind queue_kind, uint64_t queue_serial);
372 
373   void ClearThreadIDList();
374 
375   bool UpdateThreadIDList();
376 
377   void DidLaunchOrAttach(ArchSpec &process_arch);
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 {
447     static ModuleCacheKey getEmptyKey() { return ModuleCacheKey(); }
448 
449     static ModuleCacheKey getTombstoneKey() { return ModuleCacheKey("", "T"); }
450 
451     static unsigned getHashValue(const ModuleCacheKey &key) {
452       return llvm::hash_combine(key.first, key.second);
453     }
454 
455     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