xref: /freebsd-src/contrib/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h (revision 9dba64be9536c28e4800e06512b7f29b43ade345)
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 liblldb_ProcessGDBRemote_h_
10 #define liblldb_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 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 
60   static void Initialize();
61 
62   static void DebuggerInitialize(Debugger &debugger);
63 
64   static void Terminate();
65 
66   static ConstString GetPluginNameStatic();
67 
68   static const char *GetPluginDescriptionStatic();
69 
70   // Check if a given Process
71   bool CanDebug(lldb::TargetSP target_sp,
72                 bool plugin_specified_by_name) override;
73 
74   CommandObject *GetPluginCommandObject() override;
75 
76   // Creating a new process, or attaching to an existing one
77   Status WillLaunch(Module *module) override;
78 
79   Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override;
80 
81   void DidLaunch() override;
82 
83   Status WillAttachToProcessWithID(lldb::pid_t pid) override;
84 
85   Status WillAttachToProcessWithName(const char *process_name,
86                                      bool wait_for_launch) override;
87 
88   Status DoConnectRemote(Stream *strm, llvm::StringRef remote_url) override;
89 
90   Status WillLaunchOrAttach();
91 
92   Status DoAttachToProcessWithID(lldb::pid_t pid,
93                                  const ProcessAttachInfo &attach_info) override;
94 
95   Status
96   DoAttachToProcessWithName(const char *process_name,
97                             const ProcessAttachInfo &attach_info) override;
98 
99   void DidAttach(ArchSpec &process_arch) override;
100 
101   // PluginInterface protocol
102   ConstString GetPluginName() override;
103 
104   uint32_t GetPluginVersion() override;
105 
106   // Process Control
107   Status WillResume() override;
108 
109   Status DoResume() override;
110 
111   Status DoHalt(bool &caused_stop) override;
112 
113   Status DoDetach(bool keep_stopped) override;
114 
115   bool DetachRequiresHalt() override { return true; }
116 
117   Status DoSignal(int signal) override;
118 
119   Status DoDestroy() override;
120 
121   void RefreshStateAfterStop() override;
122 
123   void SetUnixSignals(const lldb::UnixSignalsSP &signals_sp);
124 
125   // Process Queries
126   bool IsAlive() override;
127 
128   lldb::addr_t GetImageInfoAddress() override;
129 
130   void WillPublicStop() override;
131 
132   // Process Memory
133   size_t DoReadMemory(lldb::addr_t addr, void *buf, size_t size,
134                       Status &error) override;
135 
136   Status
137   WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) override;
138 
139   size_t DoWriteMemory(lldb::addr_t addr, const void *buf, size_t size,
140                        Status &error) override;
141 
142   lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions,
143                                 Status &error) override;
144 
145   Status GetMemoryRegionInfo(lldb::addr_t load_addr,
146                              MemoryRegionInfo &region_info) 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   lldb::user_id_t StartTrace(const TraceOptions &options,
166                              Status &error) override;
167 
168   Status StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) override;
169 
170   Status GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
171                  llvm::MutableArrayRef<uint8_t> &buffer,
172                  size_t offset = 0) override;
173 
174   Status GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
175                      llvm::MutableArrayRef<uint8_t> &buffer,
176                      size_t offset = 0) override;
177 
178   Status GetTraceConfig(lldb::user_id_t uid, TraceOptions &options) 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 protected:
235   friend class ThreadGDBRemote;
236   friend class GDBRemoteCommunicationClient;
237   friend class GDBRemoteRegisterContext;
238 
239   /// Broadcaster event bits definitions.
240   enum {
241     eBroadcastBitAsyncContinue = (1 << 0),
242     eBroadcastBitAsyncThreadShouldExit = (1 << 1),
243     eBroadcastBitAsyncThreadDidExit = (1 << 2)
244   };
245 
246   GDBRemoteCommunicationClient m_gdb_comm;
247   GDBRemoteCommunicationReplayServer m_gdb_replay_server;
248   std::atomic<lldb::pid_t> m_debugserver_pid;
249   std::vector<StringExtractorGDBRemote> m_stop_packet_stack; // The stop packet
250                                                              // stack replaces
251                                                              // the last stop
252                                                              // packet variable
253   std::recursive_mutex m_last_stop_packet_mutex;
254   GDBRemoteDynamicRegisterInfo m_register_info;
255   Broadcaster m_async_broadcaster;
256   lldb::ListenerSP m_async_listener_sp;
257   HostThread m_async_thread;
258   std::recursive_mutex m_async_thread_state_mutex;
259   typedef std::vector<lldb::tid_t> tid_collection;
260   typedef std::vector<std::pair<lldb::tid_t, int>> tid_sig_collection;
261   typedef std::map<lldb::addr_t, lldb::addr_t> MMapMap;
262   typedef std::map<uint32_t, std::string> ExpeditedRegisterMap;
263   tid_collection m_thread_ids; // Thread IDs for all threads. This list gets
264                                // updated after stopping
265   std::vector<lldb::addr_t> m_thread_pcs;     // PC values for all the threads.
266   StructuredData::ObjectSP m_jstopinfo_sp;    // Stop info only for any threads
267                                               // that have valid stop infos
268   StructuredData::ObjectSP m_jthreadsinfo_sp; // Full stop info, expedited
269                                               // registers and memory for all
270                                               // threads if "jThreadsInfo"
271                                               // packet is supported
272   tid_collection m_continue_c_tids;           // 'c' for continue
273   tid_sig_collection m_continue_C_tids;       // 'C' for continue with signal
274   tid_collection m_continue_s_tids;           // 's' for step
275   tid_sig_collection m_continue_S_tids;       // 'S' for step with signal
276   uint64_t m_max_memory_size; // The maximum number of bytes to read/write when
277                               // reading and writing memory
278   uint64_t m_remote_stub_max_memory_size; // The maximum memory size the remote
279                                           // gdb stub can handle
280   MMapMap m_addr_to_mmap_size;
281   lldb::BreakpointSP m_thread_create_bp_sp;
282   bool m_waiting_for_attach;
283   bool m_destroy_tried_resuming;
284   lldb::CommandObjectSP m_command_sp;
285   int64_t m_breakpoint_pc_offset;
286   lldb::tid_t m_initial_tid; // The initial thread ID, given by stub on attach
287 
288   bool m_replay_mode;
289   bool m_allow_flash_writes;
290   using FlashRangeVector = lldb_private::RangeVector<lldb::addr_t, size_t>;
291   using FlashRange = FlashRangeVector::Entry;
292   FlashRangeVector m_erased_flash_ranges;
293 
294   // Accessors
295   bool IsRunning(lldb::StateType state) {
296     return state == lldb::eStateRunning || IsStepping(state);
297   }
298 
299   bool IsStepping(lldb::StateType state) {
300     return state == lldb::eStateStepping;
301   }
302 
303   bool CanResume(lldb::StateType state) { return state == lldb::eStateStopped; }
304 
305   bool HasExited(lldb::StateType state) { return state == lldb::eStateExited; }
306 
307   bool ProcessIDIsValid() const;
308 
309   void Clear();
310 
311   bool UpdateThreadList(ThreadList &old_thread_list,
312                         ThreadList &new_thread_list) override;
313 
314   Status ConnectToReplayServer(repro::Loader *loader);
315 
316   Status EstablishConnectionIfNeeded(const ProcessInfo &process_info);
317 
318   Status LaunchAndConnectToDebugserver(const ProcessInfo &process_info);
319 
320   void KillDebugserverProcess();
321 
322   void BuildDynamicRegisterInfo(bool force);
323 
324   void SetLastStopPacket(const StringExtractorGDBRemote &response);
325 
326   bool ParsePythonTargetDefinition(const FileSpec &target_definition_fspec);
327 
328   DataExtractor GetAuxvData() override;
329 
330   StructuredData::ObjectSP GetExtendedInfoForThread(lldb::tid_t tid);
331 
332   void GetMaxMemorySize();
333 
334   bool CalculateThreadStopInfo(ThreadGDBRemote *thread);
335 
336   size_t UpdateThreadPCsFromStopReplyThreadsValue(std::string &value);
337 
338   size_t UpdateThreadIDsFromStopReplyThreadsValue(std::string &value);
339 
340   bool HandleNotifyPacket(StringExtractorGDBRemote &packet);
341 
342   bool StartAsyncThread();
343 
344   void StopAsyncThread();
345 
346   static lldb::thread_result_t AsyncThread(void *arg);
347 
348   static bool
349   MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp,
350                             lldb::pid_t pid, bool exited, int signo,
351                             int exit_status);
352 
353   lldb::StateType SetThreadStopInfo(StringExtractor &stop_packet);
354 
355   bool
356   GetThreadStopInfoFromJSON(ThreadGDBRemote *thread,
357                             const StructuredData::ObjectSP &thread_infos_sp);
358 
359   lldb::ThreadSP SetThreadStopInfo(StructuredData::Dictionary *thread_dict);
360 
361   lldb::ThreadSP
362   SetThreadStopInfo(lldb::tid_t tid,
363                     ExpeditedRegisterMap &expedited_register_map, uint8_t signo,
364                     const std::string &thread_name, const std::string &reason,
365                     const std::string &description, uint32_t exc_type,
366                     const std::vector<lldb::addr_t> &exc_data,
367                     lldb::addr_t thread_dispatch_qaddr, bool queue_vars_valid,
368                     lldb_private::LazyBool associated_with_libdispatch_queue,
369                     lldb::addr_t dispatch_queue_t, std::string &queue_name,
370                     lldb::QueueKind queue_kind, uint64_t queue_serial);
371 
372   void HandleStopReplySequence();
373 
374   void ClearThreadIDList();
375 
376   bool UpdateThreadIDList();
377 
378   void DidLaunchOrAttach(ArchSpec &process_arch);
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(ArchSpec &arch_to_use,
388                                              std::string xml_filename,
389                                              uint32_t &cur_reg_num,
390                                              uint32_t &reg_offset);
391 
392   // Query remote GDBServer for register information
393   bool GetGDBServerRegisterInfo(ArchSpec &arch);
394 
395   lldb::ModuleSP LoadModuleAtAddress(const FileSpec &file,
396                                      lldb::addr_t link_map,
397                                      lldb::addr_t base_addr,
398                                      bool value_is_offset);
399 
400   Status UpdateAutomaticSignalFiltering() override;
401 
402   Status FlashErase(lldb::addr_t addr, size_t size);
403 
404   Status FlashDone();
405 
406   bool HasErased(FlashRange range);
407 
408 private:
409   // For ProcessGDBRemote only
410   std::string m_partial_profile_data;
411   std::map<uint64_t, uint32_t> m_thread_id_to_used_usec_map;
412   uint64_t m_last_signals_version = 0;
413 
414   static bool NewThreadNotifyBreakpointHit(void *baton,
415                                            StoppointCallbackContext *context,
416                                            lldb::user_id_t break_id,
417                                            lldb::user_id_t break_loc_id);
418 
419   // ContinueDelegate interface
420   void HandleAsyncStdout(llvm::StringRef out) override;
421   void HandleAsyncMisc(llvm::StringRef data) override;
422   void HandleStopReply() override;
423   void HandleAsyncStructuredDataPacket(llvm::StringRef data) override;
424 
425   void SetThreadPc(const lldb::ThreadSP &thread_sp, uint64_t index);
426   using ModuleCacheKey = std::pair<std::string, std::string>;
427   // KeyInfo for the cached module spec DenseMap.
428   // The invariant is that all real keys will have the file and architecture
429   // set.
430   // The empty key has an empty file and an empty arch.
431   // The tombstone key has an invalid arch and an empty file.
432   // The comparison and hash functions take the file name and architecture
433   // triple into account.
434   struct ModuleCacheInfo {
435     static ModuleCacheKey getEmptyKey() { return ModuleCacheKey(); }
436 
437     static ModuleCacheKey getTombstoneKey() { return ModuleCacheKey("", "T"); }
438 
439     static unsigned getHashValue(const ModuleCacheKey &key) {
440       return llvm::hash_combine(key.first, key.second);
441     }
442 
443     static bool isEqual(const ModuleCacheKey &LHS, const ModuleCacheKey &RHS) {
444       return LHS == RHS;
445     }
446   };
447 
448   llvm::DenseMap<ModuleCacheKey, ModuleSpec, ModuleCacheInfo>
449       m_cached_module_specs;
450 
451   DISALLOW_COPY_AND_ASSIGN(ProcessGDBRemote);
452 };
453 
454 } // namespace process_gdb_remote
455 } // namespace lldb_private
456 
457 #endif // liblldb_ProcessGDBRemote_h_
458