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