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 
273   llvm::Optional<StringExtractorGDBRemote> m_last_stop_packet;
274   std::recursive_mutex m_last_stop_packet_mutex;
275 
276   GDBRemoteDynamicRegisterInfoSP m_register_info_sp;
277   Broadcaster m_async_broadcaster;
278   lldb::ListenerSP m_async_listener_sp;
279   HostThread m_async_thread;
280   std::recursive_mutex m_async_thread_state_mutex;
281   typedef std::vector<lldb::tid_t> tid_collection;
282   typedef std::vector<std::pair<lldb::tid_t, int>> tid_sig_collection;
283   typedef std::map<lldb::addr_t, lldb::addr_t> MMapMap;
284   typedef std::map<uint32_t, std::string> ExpeditedRegisterMap;
285   tid_collection m_thread_ids; // Thread IDs for all threads. This list gets
286                                // updated after stopping
287   std::vector<lldb::addr_t> m_thread_pcs;     // PC values for all the threads.
288   StructuredData::ObjectSP m_jstopinfo_sp;    // Stop info only for any threads
289                                               // that have valid stop infos
290   StructuredData::ObjectSP m_jthreadsinfo_sp; // Full stop info, expedited
291                                               // registers and memory for all
292                                               // threads if "jThreadsInfo"
293                                               // packet is supported
294   tid_collection m_continue_c_tids;           // 'c' for continue
295   tid_sig_collection m_continue_C_tids;       // 'C' for continue with signal
296   tid_collection m_continue_s_tids;           // 's' for step
297   tid_sig_collection m_continue_S_tids;       // 'S' for step with signal
298   uint64_t m_max_memory_size; // The maximum number of bytes to read/write when
299                               // reading and writing memory
300   uint64_t m_remote_stub_max_memory_size; // The maximum memory size the remote
301                                           // gdb stub can handle
302   MMapMap m_addr_to_mmap_size;
303   lldb::BreakpointSP m_thread_create_bp_sp;
304   bool m_waiting_for_attach;
305   bool m_destroy_tried_resuming;
306   lldb::CommandObjectSP m_command_sp;
307   int64_t m_breakpoint_pc_offset;
308   lldb::tid_t m_initial_tid; // The initial thread ID, given by stub on attach
309   bool m_use_g_packet_for_reading;
310 
311   bool m_replay_mode;
312   bool m_allow_flash_writes;
313   using FlashRangeVector = lldb_private::RangeVector<lldb::addr_t, size_t>;
314   using FlashRange = FlashRangeVector::Entry;
315   FlashRangeVector m_erased_flash_ranges;
316 
317   bool m_vfork_in_progress;
318 
319   // Accessors
320   bool IsRunning(lldb::StateType state) {
321     return state == lldb::eStateRunning || IsStepping(state);
322   }
323 
324   bool IsStepping(lldb::StateType state) {
325     return state == lldb::eStateStepping;
326   }
327 
328   bool CanResume(lldb::StateType state) { return state == lldb::eStateStopped; }
329 
330   bool HasExited(lldb::StateType state) { return state == lldb::eStateExited; }
331 
332   bool ProcessIDIsValid() const;
333 
334   void Clear();
335 
336   bool DoUpdateThreadList(ThreadList &old_thread_list,
337                           ThreadList &new_thread_list) override;
338 
339   Status ConnectToReplayServer();
340 
341   Status EstablishConnectionIfNeeded(const ProcessInfo &process_info);
342 
343   Status LaunchAndConnectToDebugserver(const ProcessInfo &process_info);
344 
345   void KillDebugserverProcess();
346 
347   void BuildDynamicRegisterInfo(bool force);
348 
349   void SetLastStopPacket(const StringExtractorGDBRemote &response);
350 
351   bool ParsePythonTargetDefinition(const FileSpec &target_definition_fspec);
352 
353   DataExtractor GetAuxvData() override;
354 
355   StructuredData::ObjectSP GetExtendedInfoForThread(lldb::tid_t tid);
356 
357   void GetMaxMemorySize();
358 
359   bool CalculateThreadStopInfo(ThreadGDBRemote *thread);
360 
361   size_t UpdateThreadPCsFromStopReplyThreadsValue(llvm::StringRef value);
362 
363   size_t UpdateThreadIDsFromStopReplyThreadsValue(llvm::StringRef value);
364 
365   bool HandleNotifyPacket(StringExtractorGDBRemote &packet);
366 
367   bool StartAsyncThread();
368 
369   void StopAsyncThread();
370 
371   static lldb::thread_result_t AsyncThread(void *arg);
372 
373   static bool
374   MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp,
375                             lldb::pid_t pid, bool exited, int signo,
376                             int exit_status);
377 
378   lldb::StateType SetThreadStopInfo(StringExtractor &stop_packet);
379 
380   bool
381   GetThreadStopInfoFromJSON(ThreadGDBRemote *thread,
382                             const StructuredData::ObjectSP &thread_infos_sp);
383 
384   lldb::ThreadSP SetThreadStopInfo(StructuredData::Dictionary *thread_dict);
385 
386   lldb::ThreadSP
387   SetThreadStopInfo(lldb::tid_t tid,
388                     ExpeditedRegisterMap &expedited_register_map, uint8_t signo,
389                     const std::string &thread_name, const std::string &reason,
390                     const std::string &description, uint32_t exc_type,
391                     const std::vector<lldb::addr_t> &exc_data,
392                     lldb::addr_t thread_dispatch_qaddr, bool queue_vars_valid,
393                     lldb_private::LazyBool associated_with_libdispatch_queue,
394                     lldb::addr_t dispatch_queue_t, std::string &queue_name,
395                     lldb::QueueKind queue_kind, uint64_t queue_serial);
396 
397   void HandleStopReplySequence();
398 
399   void ClearThreadIDList();
400 
401   bool UpdateThreadIDList();
402 
403   void DidLaunchOrAttach(ArchSpec &process_arch);
404   void MaybeLoadExecutableModule();
405 
406   Status ConnectToDebugserver(llvm::StringRef host_port);
407 
408   const char *GetDispatchQueueNameForThread(lldb::addr_t thread_dispatch_qaddr,
409                                             std::string &dispatch_queue_name);
410 
411   DynamicLoader *GetDynamicLoader() override;
412 
413   bool GetGDBServerRegisterInfoXMLAndProcess(
414     ArchSpec &arch_to_use, std::string xml_filename,
415     std::vector<RemoteRegisterInfo> &registers);
416 
417   // Convert RemoteRegisterInfos into RegisterInfos and add to the dynamic
418   // register list.
419   void AddRemoteRegisters(std::vector<RemoteRegisterInfo> &registers,
420                           const ArchSpec &arch_to_use);
421   // Query remote GDBServer for register information
422   bool GetGDBServerRegisterInfo(ArchSpec &arch);
423 
424   lldb::ModuleSP LoadModuleAtAddress(const FileSpec &file,
425                                      lldb::addr_t link_map,
426                                      lldb::addr_t base_addr,
427                                      bool value_is_offset);
428 
429   Status UpdateAutomaticSignalFiltering() override;
430 
431   Status FlashErase(lldb::addr_t addr, size_t size);
432 
433   Status FlashDone();
434 
435   bool HasErased(FlashRange range);
436 
437   llvm::Expected<std::vector<uint8_t>>
438   DoReadMemoryTags(lldb::addr_t addr, size_t len, int32_t type) override;
439 
440   Status DoWriteMemoryTags(lldb::addr_t addr, size_t len, int32_t type,
441                            const std::vector<uint8_t> &tags) override;
442 
443 private:
444   // For ProcessGDBRemote only
445   std::string m_partial_profile_data;
446   std::map<uint64_t, uint32_t> m_thread_id_to_used_usec_map;
447   uint64_t m_last_signals_version = 0;
448 
449   static bool NewThreadNotifyBreakpointHit(void *baton,
450                                            StoppointCallbackContext *context,
451                                            lldb::user_id_t break_id,
452                                            lldb::user_id_t break_loc_id);
453 
454   // ContinueDelegate interface
455   void HandleAsyncStdout(llvm::StringRef out) override;
456   void HandleAsyncMisc(llvm::StringRef data) override;
457   void HandleStopReply() override;
458   void HandleAsyncStructuredDataPacket(llvm::StringRef data) override;
459 
460   void SetThreadPc(const lldb::ThreadSP &thread_sp, uint64_t index);
461   using ModuleCacheKey = std::pair<std::string, std::string>;
462   // KeyInfo for the cached module spec DenseMap.
463   // The invariant is that all real keys will have the file and architecture
464   // set.
465   // The empty key has an empty file and an empty arch.
466   // The tombstone key has an invalid arch and an empty file.
467   // The comparison and hash functions take the file name and architecture
468   // triple into account.
469   struct ModuleCacheInfo {
470     static ModuleCacheKey getEmptyKey() { return ModuleCacheKey(); }
471 
472     static ModuleCacheKey getTombstoneKey() { return ModuleCacheKey("", "T"); }
473 
474     static unsigned getHashValue(const ModuleCacheKey &key) {
475       return llvm::hash_combine(key.first, key.second);
476     }
477 
478     static bool isEqual(const ModuleCacheKey &LHS, const ModuleCacheKey &RHS) {
479       return LHS == RHS;
480     }
481   };
482 
483   llvm::DenseMap<ModuleCacheKey, ModuleSpec, ModuleCacheInfo>
484       m_cached_module_specs;
485 
486   ProcessGDBRemote(const ProcessGDBRemote &) = delete;
487   const ProcessGDBRemote &operator=(const ProcessGDBRemote &) = delete;
488 
489   // fork helpers
490   void DidForkSwitchSoftwareBreakpoints(bool enable);
491   void DidForkSwitchHardwareTraps(bool enable);
492 };
493 
494 } // namespace process_gdb_remote
495 } // namespace lldb_private
496 
497 #endif // LLDB_SOURCE_PLUGINS_PROCESS_GDB_REMOTE_PROCESSGDBREMOTE_H
498