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