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