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 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(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   llvm::Expected<TraceTypeInfo> GetSupportedTraceType() override;
179 
180   Status GetTraceConfig(lldb::user_id_t uid, TraceOptions &options) override;
181 
182   Status GetWatchpointSupportInfo(uint32_t &num, bool &after) override;
183 
184   bool StartNoticingNewThreads() override;
185 
186   bool StopNoticingNewThreads() override;
187 
188   GDBRemoteCommunicationClient &GetGDBRemote() { return m_gdb_comm; }
189 
190   Status SendEventData(const char *data) override;
191 
192   // Override DidExit so we can disconnect from the remote GDB server
193   void DidExit() override;
194 
195   void SetUserSpecifiedMaxMemoryTransferSize(uint64_t user_specified_max);
196 
197   bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch,
198                      ModuleSpec &module_spec) override;
199 
200   void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,
201                            const llvm::Triple &triple) override;
202 
203   llvm::VersionTuple GetHostOSVersion() override;
204   llvm::VersionTuple GetHostMacCatalystVersion() override;
205 
206   llvm::Error LoadModules() override;
207 
208   llvm::Expected<LoadedModuleInfoList> GetLoadedModuleList() override;
209 
210   Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded,
211                             lldb::addr_t &load_addr) override;
212 
213   void ModulesDidLoad(ModuleList &module_list) override;
214 
215   StructuredData::ObjectSP
216   GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,
217                                  lldb::addr_t image_count) override;
218 
219   Status
220   ConfigureStructuredData(ConstString type_name,
221                           const StructuredData::ObjectSP &config_sp) override;
222 
223   StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos() override;
224 
225   StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(
226       const std::vector<lldb::addr_t> &load_addresses) override;
227 
228   StructuredData::ObjectSP
229   GetLoadedDynamicLibrariesInfos_sender(StructuredData::ObjectSP args);
230 
231   StructuredData::ObjectSP GetSharedCacheInfo() override;
232 
233   std::string HarmonizeThreadIdsForProfileData(
234       StringExtractorGDBRemote &inputStringExtractor);
235 
236 protected:
237   friend class ThreadGDBRemote;
238   friend class GDBRemoteCommunicationClient;
239   friend class GDBRemoteRegisterContext;
240 
241   /// Broadcaster event bits definitions.
242   enum {
243     eBroadcastBitAsyncContinue = (1 << 0),
244     eBroadcastBitAsyncThreadShouldExit = (1 << 1),
245     eBroadcastBitAsyncThreadDidExit = (1 << 2)
246   };
247 
248   GDBRemoteCommunicationClient m_gdb_comm;
249   GDBRemoteCommunicationReplayServer m_gdb_replay_server;
250   std::atomic<lldb::pid_t> m_debugserver_pid;
251   std::vector<StringExtractorGDBRemote> m_stop_packet_stack; // The stop packet
252                                                              // stack replaces
253                                                              // the last stop
254                                                              // packet variable
255   std::recursive_mutex m_last_stop_packet_mutex;
256   GDBRemoteDynamicRegisterInfo m_register_info;
257   Broadcaster m_async_broadcaster;
258   lldb::ListenerSP m_async_listener_sp;
259   HostThread m_async_thread;
260   std::recursive_mutex m_async_thread_state_mutex;
261   typedef std::vector<lldb::tid_t> tid_collection;
262   typedef std::vector<std::pair<lldb::tid_t, int>> tid_sig_collection;
263   typedef std::map<lldb::addr_t, lldb::addr_t> MMapMap;
264   typedef std::map<uint32_t, std::string> ExpeditedRegisterMap;
265   tid_collection m_thread_ids; // Thread IDs for all threads. This list gets
266                                // updated after stopping
267   std::vector<lldb::addr_t> m_thread_pcs;     // PC values for all the threads.
268   StructuredData::ObjectSP m_jstopinfo_sp;    // Stop info only for any threads
269                                               // that have valid stop infos
270   StructuredData::ObjectSP m_jthreadsinfo_sp; // Full stop info, expedited
271                                               // registers and memory for all
272                                               // threads if "jThreadsInfo"
273                                               // packet is supported
274   tid_collection m_continue_c_tids;           // 'c' for continue
275   tid_sig_collection m_continue_C_tids;       // 'C' for continue with signal
276   tid_collection m_continue_s_tids;           // 's' for step
277   tid_sig_collection m_continue_S_tids;       // 'S' for step with signal
278   uint64_t m_max_memory_size; // The maximum number of bytes to read/write when
279                               // reading and writing memory
280   uint64_t m_remote_stub_max_memory_size; // The maximum memory size the remote
281                                           // gdb stub can handle
282   MMapMap m_addr_to_mmap_size;
283   lldb::BreakpointSP m_thread_create_bp_sp;
284   bool m_waiting_for_attach;
285   bool m_destroy_tried_resuming;
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_replay_mode;
292   bool m_allow_flash_writes;
293   using FlashRangeVector = lldb_private::RangeVector<lldb::addr_t, size_t>;
294   using FlashRange = FlashRangeVector::Entry;
295   FlashRangeVector m_erased_flash_ranges;
296 
297   // Accessors
298   bool IsRunning(lldb::StateType state) {
299     return state == lldb::eStateRunning || IsStepping(state);
300   }
301 
302   bool IsStepping(lldb::StateType state) {
303     return state == lldb::eStateStepping;
304   }
305 
306   bool CanResume(lldb::StateType state) { return state == lldb::eStateStopped; }
307 
308   bool HasExited(lldb::StateType state) { return state == lldb::eStateExited; }
309 
310   bool ProcessIDIsValid() const;
311 
312   void Clear();
313 
314   bool UpdateThreadList(ThreadList &old_thread_list,
315                         ThreadList &new_thread_list) override;
316 
317   Status ConnectToReplayServer();
318 
319   Status EstablishConnectionIfNeeded(const ProcessInfo &process_info);
320 
321   Status LaunchAndConnectToDebugserver(const ProcessInfo &process_info);
322 
323   void KillDebugserverProcess();
324 
325   void BuildDynamicRegisterInfo(bool force);
326 
327   void SetLastStopPacket(const StringExtractorGDBRemote &response);
328 
329   bool ParsePythonTargetDefinition(const FileSpec &target_definition_fspec);
330 
331   DataExtractor GetAuxvData() override;
332 
333   StructuredData::ObjectSP GetExtendedInfoForThread(lldb::tid_t tid);
334 
335   void GetMaxMemorySize();
336 
337   bool CalculateThreadStopInfo(ThreadGDBRemote *thread);
338 
339   size_t UpdateThreadPCsFromStopReplyThreadsValue(std::string &value);
340 
341   size_t UpdateThreadIDsFromStopReplyThreadsValue(std::string &value);
342 
343   bool HandleNotifyPacket(StringExtractorGDBRemote &packet);
344 
345   bool StartAsyncThread();
346 
347   void StopAsyncThread();
348 
349   static lldb::thread_result_t AsyncThread(void *arg);
350 
351   static bool
352   MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp,
353                             lldb::pid_t pid, bool exited, int signo,
354                             int exit_status);
355 
356   lldb::StateType SetThreadStopInfo(StringExtractor &stop_packet);
357 
358   bool
359   GetThreadStopInfoFromJSON(ThreadGDBRemote *thread,
360                             const StructuredData::ObjectSP &thread_infos_sp);
361 
362   lldb::ThreadSP SetThreadStopInfo(StructuredData::Dictionary *thread_dict);
363 
364   lldb::ThreadSP
365   SetThreadStopInfo(lldb::tid_t tid,
366                     ExpeditedRegisterMap &expedited_register_map, uint8_t signo,
367                     const std::string &thread_name, const std::string &reason,
368                     const std::string &description, uint32_t exc_type,
369                     const std::vector<lldb::addr_t> &exc_data,
370                     lldb::addr_t thread_dispatch_qaddr, bool queue_vars_valid,
371                     lldb_private::LazyBool associated_with_libdispatch_queue,
372                     lldb::addr_t dispatch_queue_t, std::string &queue_name,
373                     lldb::QueueKind queue_kind, uint64_t queue_serial);
374 
375   void HandleStopReplySequence();
376 
377   void ClearThreadIDList();
378 
379   bool UpdateThreadIDList();
380 
381   void DidLaunchOrAttach(ArchSpec &process_arch);
382   void MaybeLoadExecutableModule();
383 
384   Status ConnectToDebugserver(llvm::StringRef host_port);
385 
386   const char *GetDispatchQueueNameForThread(lldb::addr_t thread_dispatch_qaddr,
387                                             std::string &dispatch_queue_name);
388 
389   DynamicLoader *GetDynamicLoader() override;
390 
391   bool GetGDBServerRegisterInfoXMLAndProcess(ArchSpec &arch_to_use,
392                                              std::string xml_filename,
393                                              uint32_t &cur_reg_num,
394                                              uint32_t &reg_offset);
395 
396   // Query remote GDBServer for register information
397   bool GetGDBServerRegisterInfo(ArchSpec &arch);
398 
399   lldb::ModuleSP LoadModuleAtAddress(const FileSpec &file,
400                                      lldb::addr_t link_map,
401                                      lldb::addr_t base_addr,
402                                      bool value_is_offset);
403 
404   Status UpdateAutomaticSignalFiltering() override;
405 
406   Status FlashErase(lldb::addr_t addr, size_t size);
407 
408   Status FlashDone();
409 
410   bool HasErased(FlashRange range);
411 
412 private:
413   // For ProcessGDBRemote only
414   std::string m_partial_profile_data;
415   std::map<uint64_t, uint32_t> m_thread_id_to_used_usec_map;
416   uint64_t m_last_signals_version = 0;
417 
418   static bool NewThreadNotifyBreakpointHit(void *baton,
419                                            StoppointCallbackContext *context,
420                                            lldb::user_id_t break_id,
421                                            lldb::user_id_t break_loc_id);
422 
423   // ContinueDelegate interface
424   void HandleAsyncStdout(llvm::StringRef out) override;
425   void HandleAsyncMisc(llvm::StringRef data) override;
426   void HandleStopReply() override;
427   void HandleAsyncStructuredDataPacket(llvm::StringRef data) override;
428 
429   void SetThreadPc(const lldb::ThreadSP &thread_sp, uint64_t index);
430   using ModuleCacheKey = std::pair<std::string, std::string>;
431   // KeyInfo for the cached module spec DenseMap.
432   // The invariant is that all real keys will have the file and architecture
433   // set.
434   // The empty key has an empty file and an empty arch.
435   // The tombstone key has an invalid arch and an empty file.
436   // The comparison and hash functions take the file name and architecture
437   // triple into account.
438   struct ModuleCacheInfo {
439     static ModuleCacheKey getEmptyKey() { return ModuleCacheKey(); }
440 
441     static ModuleCacheKey getTombstoneKey() { return ModuleCacheKey("", "T"); }
442 
443     static unsigned getHashValue(const ModuleCacheKey &key) {
444       return llvm::hash_combine(key.first, key.second);
445     }
446 
447     static bool isEqual(const ModuleCacheKey &LHS, const ModuleCacheKey &RHS) {
448       return LHS == RHS;
449     }
450   };
451 
452   llvm::DenseMap<ModuleCacheKey, ModuleSpec, ModuleCacheInfo>
453       m_cached_module_specs;
454 
455   ProcessGDBRemote(const ProcessGDBRemote &) = delete;
456   const ProcessGDBRemote &operator=(const ProcessGDBRemote &) = delete;
457 };
458 
459 } // namespace process_gdb_remote
460 } // namespace lldb_private
461 
462 #endif // LLDB_SOURCE_PLUGINS_PROCESS_GDB_REMOTE_PROCESSGDBREMOTE_H
463