1 //===-- ProcessGDBRemote.h --------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #ifndef liblldb_ProcessGDBRemote_h_
11 #define liblldb_ProcessGDBRemote_h_
12 
13 // C Includes
14 // C++ Includes
15 #include <atomic>
16 #include <map>
17 #include <mutex>
18 #include <string>
19 #include <vector>
20 
21 #include "lldb/Core/Broadcaster.h"
22 #include "lldb/Core/LoadedModuleInfoList.h"
23 #include "lldb/Core/ModuleSpec.h"
24 #include "lldb/Core/ThreadSafeValue.h"
25 #include "lldb/Host/HostThread.h"
26 #include "lldb/Target/Process.h"
27 #include "lldb/Target/Thread.h"
28 #include "lldb/Utility/ArchSpec.h"
29 #include "lldb/Utility/ConstString.h"
30 #include "lldb/Utility/Status.h"
31 #include "lldb/Utility/StreamGDBRemote.h"
32 #include "lldb/Utility/StreamString.h"
33 #include "lldb/Utility/StringExtractor.h"
34 #include "lldb/Utility/StringList.h"
35 #include "lldb/Utility/StructuredData.h"
36 #include "lldb/lldb-private-forward.h"
37 
38 #include "GDBRemoteCommunicationClient.h"
39 #include "GDBRemoteRegisterContext.h"
40 
41 #include "llvm/ADT/DenseMap.h"
42 
43 namespace lldb_private {
44 namespace process_gdb_remote {
45 
46 class ThreadGDBRemote;
47 
48 class ProcessGDBRemote : public Process,
49                          private GDBRemoteClientBase::ContinueDelegate {
50 public:
51   ProcessGDBRemote(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp);
52 
53   ~ProcessGDBRemote() override;
54 
55   static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp,
56                                         lldb::ListenerSP listener_sp,
57                                         const FileSpec *crash_file_path);
58 
59   static void Initialize();
60 
61   static void DebuggerInitialize(Debugger &debugger);
62 
63   static void Terminate();
64 
65   static ConstString GetPluginNameStatic();
66 
67   static const char *GetPluginDescriptionStatic();
68 
69   //------------------------------------------------------------------
70   // Check if a given Process
71   //------------------------------------------------------------------
72   bool CanDebug(lldb::TargetSP target_sp,
73                 bool plugin_specified_by_name) override;
74 
75   CommandObject *GetPluginCommandObject() override;
76 
77   //------------------------------------------------------------------
78   // Creating a new process, or attaching to an existing one
79   //------------------------------------------------------------------
80   Status WillLaunch(Module *module) override;
81 
82   Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override;
83 
84   void DidLaunch() override;
85 
86   Status WillAttachToProcessWithID(lldb::pid_t pid) override;
87 
88   Status WillAttachToProcessWithName(const char *process_name,
89                                      bool wait_for_launch) override;
90 
91   Status DoConnectRemote(Stream *strm, llvm::StringRef remote_url) override;
92 
93   Status WillLaunchOrAttach();
94 
95   Status DoAttachToProcessWithID(lldb::pid_t pid,
96                                  const ProcessAttachInfo &attach_info) override;
97 
98   Status
99   DoAttachToProcessWithName(const char *process_name,
100                             const ProcessAttachInfo &attach_info) override;
101 
102   void DidAttach(ArchSpec &process_arch) override;
103 
104   //------------------------------------------------------------------
105   // PluginInterface protocol
106   //------------------------------------------------------------------
107   ConstString GetPluginName() override;
108 
109   uint32_t GetPluginVersion() override;
110 
111   //------------------------------------------------------------------
112   // Process Control
113   //------------------------------------------------------------------
114   Status WillResume() override;
115 
116   Status DoResume() override;
117 
118   Status DoHalt(bool &caused_stop) override;
119 
120   Status DoDetach(bool keep_stopped) override;
121 
122   bool DetachRequiresHalt() override { return true; }
123 
124   Status DoSignal(int signal) override;
125 
126   Status DoDestroy() override;
127 
128   void RefreshStateAfterStop() override;
129 
130   void SetUnixSignals(const lldb::UnixSignalsSP &signals_sp);
131 
132   //------------------------------------------------------------------
133   // Process Queries
134   //------------------------------------------------------------------
135   bool IsAlive() override;
136 
137   lldb::addr_t GetImageInfoAddress() override;
138 
139   void WillPublicStop() override;
140 
141   //------------------------------------------------------------------
142   // Process Memory
143   //------------------------------------------------------------------
144   size_t DoReadMemory(lldb::addr_t addr, void *buf, size_t size,
145                       Status &error) override;
146 
147   Status
148   WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) override;
149 
150   size_t DoWriteMemory(lldb::addr_t addr, const void *buf, size_t size,
151                        Status &error) override;
152 
153   lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions,
154                                 Status &error) override;
155 
156   Status GetMemoryRegionInfo(lldb::addr_t load_addr,
157                              MemoryRegionInfo &region_info) override;
158 
159   Status DoDeallocateMemory(lldb::addr_t ptr) override;
160 
161   //------------------------------------------------------------------
162   // Process STDIO
163   //------------------------------------------------------------------
164   size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) override;
165 
166   //----------------------------------------------------------------------
167   // Process Breakpoints
168   //----------------------------------------------------------------------
169   Status EnableBreakpointSite(BreakpointSite *bp_site) override;
170 
171   Status DisableBreakpointSite(BreakpointSite *bp_site) override;
172 
173   //----------------------------------------------------------------------
174   // Process Watchpoints
175   //----------------------------------------------------------------------
176   Status EnableWatchpoint(Watchpoint *wp, bool notify = true) override;
177 
178   Status DisableWatchpoint(Watchpoint *wp, bool notify = true) override;
179 
180   Status GetWatchpointSupportInfo(uint32_t &num) override;
181 
182   lldb::user_id_t StartTrace(const TraceOptions &options,
183                              Status &error) override;
184 
185   Status StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) override;
186 
187   Status GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
188                  llvm::MutableArrayRef<uint8_t> &buffer,
189                  size_t offset = 0) override;
190 
191   Status GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
192                      llvm::MutableArrayRef<uint8_t> &buffer,
193                      size_t offset = 0) override;
194 
195   Status GetTraceConfig(lldb::user_id_t uid, TraceOptions &options) override;
196 
197   Status GetWatchpointSupportInfo(uint32_t &num, bool &after) override;
198 
199   bool StartNoticingNewThreads() override;
200 
201   bool StopNoticingNewThreads() override;
202 
203   GDBRemoteCommunicationClient &GetGDBRemote() { return m_gdb_comm; }
204 
205   Status SendEventData(const char *data) override;
206 
207   //----------------------------------------------------------------------
208   // Override DidExit so we can disconnect from the remote GDB server
209   //----------------------------------------------------------------------
210   void DidExit() override;
211 
212   void SetUserSpecifiedMaxMemoryTransferSize(uint64_t user_specified_max);
213 
214   bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch,
215                      ModuleSpec &module_spec) override;
216 
217   void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,
218                            const llvm::Triple &triple) override;
219 
220   bool GetHostOSVersion(uint32_t &major, uint32_t &minor,
221                         uint32_t &update) override;
222 
223   size_t LoadModules(LoadedModuleInfoList &module_list) override;
224 
225   size_t LoadModules() override;
226 
227   Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded,
228                             lldb::addr_t &load_addr) override;
229 
230   void ModulesDidLoad(ModuleList &module_list) override;
231 
232   StructuredData::ObjectSP
233   GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,
234                                  lldb::addr_t image_count) override;
235 
236   Status
237   ConfigureStructuredData(const ConstString &type_name,
238                           const StructuredData::ObjectSP &config_sp) override;
239 
240   StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos() override;
241 
242   StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(
243       const std::vector<lldb::addr_t> &load_addresses) override;
244 
245   StructuredData::ObjectSP
246   GetLoadedDynamicLibrariesInfos_sender(StructuredData::ObjectSP args);
247 
248   StructuredData::ObjectSP GetSharedCacheInfo() override;
249 
250   std::string HarmonizeThreadIdsForProfileData(
251       StringExtractorGDBRemote &inputStringExtractor);
252 
253 protected:
254   friend class ThreadGDBRemote;
255   friend class GDBRemoteCommunicationClient;
256   friend class GDBRemoteRegisterContext;
257 
258   //------------------------------------------------------------------
259   /// Broadcaster event bits definitions.
260   //------------------------------------------------------------------
261   enum {
262     eBroadcastBitAsyncContinue = (1 << 0),
263     eBroadcastBitAsyncThreadShouldExit = (1 << 1),
264     eBroadcastBitAsyncThreadDidExit = (1 << 2)
265   };
266 
267   GDBRemoteCommunicationClient m_gdb_comm;
268   std::atomic<lldb::pid_t> m_debugserver_pid;
269   std::vector<StringExtractorGDBRemote> m_stop_packet_stack; // The stop packet
270                                                              // stack replaces
271                                                              // the last stop
272                                                              // packet variable
273   std::recursive_mutex m_last_stop_packet_mutex;
274   GDBRemoteDynamicRegisterInfo m_register_info;
275   Broadcaster m_async_broadcaster;
276   lldb::ListenerSP m_async_listener_sp;
277   HostThread m_async_thread;
278   std::recursive_mutex m_async_thread_state_mutex;
279   typedef std::vector<lldb::tid_t> tid_collection;
280   typedef std::vector<std::pair<lldb::tid_t, int>> tid_sig_collection;
281   typedef std::map<lldb::addr_t, lldb::addr_t> MMapMap;
282   typedef std::map<uint32_t, std::string> ExpeditedRegisterMap;
283   tid_collection m_thread_ids; // Thread IDs for all threads. This list gets
284                                // updated after stopping
285   std::vector<lldb::addr_t> m_thread_pcs;     // PC values for all the threads.
286   StructuredData::ObjectSP m_jstopinfo_sp;    // Stop info only for any threads
287                                               // that have valid stop infos
288   StructuredData::ObjectSP m_jthreadsinfo_sp; // Full stop info, expedited
289                                               // registers and memory for all
290                                               // threads if "jThreadsInfo"
291                                               // packet is supported
292   tid_collection m_continue_c_tids;           // 'c' for continue
293   tid_sig_collection m_continue_C_tids;       // 'C' for continue with signal
294   tid_collection m_continue_s_tids;           // 's' for step
295   tid_sig_collection m_continue_S_tids;       // 'S' for step with signal
296   uint64_t m_max_memory_size; // The maximum number of bytes to read/write when
297                               // reading and writing memory
298   uint64_t m_remote_stub_max_memory_size; // The maximum memory size the remote
299                                           // gdb stub can handle
300   MMapMap m_addr_to_mmap_size;
301   lldb::BreakpointSP m_thread_create_bp_sp;
302   bool m_waiting_for_attach;
303   bool m_destroy_tried_resuming;
304   lldb::CommandObjectSP m_command_sp;
305   int64_t m_breakpoint_pc_offset;
306   lldb::tid_t m_initial_tid; // The initial thread ID, given by stub on attach
307 
308   bool m_allow_flash_writes;
309   using FlashRangeVector = lldb_private::RangeVector<lldb::addr_t, size_t>;
310   using FlashRange = FlashRangeVector::Entry;
311   FlashRangeVector m_erased_flash_ranges;
312 
313   //----------------------------------------------------------------------
314   // Accessors
315   //----------------------------------------------------------------------
316   bool IsRunning(lldb::StateType state) {
317     return state == lldb::eStateRunning || IsStepping(state);
318   }
319 
320   bool IsStepping(lldb::StateType state) {
321     return state == lldb::eStateStepping;
322   }
323 
324   bool CanResume(lldb::StateType state) { return state == lldb::eStateStopped; }
325 
326   bool HasExited(lldb::StateType state) { return state == lldb::eStateExited; }
327 
328   bool ProcessIDIsValid() const;
329 
330   void Clear();
331 
332   bool UpdateThreadList(ThreadList &old_thread_list,
333                         ThreadList &new_thread_list) override;
334 
335   Status EstablishConnectionIfNeeded(const ProcessInfo &process_info);
336 
337   Status LaunchAndConnectToDebugserver(const ProcessInfo &process_info);
338 
339   void KillDebugserverProcess();
340 
341   void BuildDynamicRegisterInfo(bool force);
342 
343   void SetLastStopPacket(const StringExtractorGDBRemote &response);
344 
345   bool ParsePythonTargetDefinition(const FileSpec &target_definition_fspec);
346 
347   const lldb::DataBufferSP GetAuxvData() override;
348 
349   StructuredData::ObjectSP GetExtendedInfoForThread(lldb::tid_t tid);
350 
351   void GetMaxMemorySize();
352 
353   bool CalculateThreadStopInfo(ThreadGDBRemote *thread);
354 
355   size_t UpdateThreadPCsFromStopReplyThreadsValue(std::string &value);
356 
357   size_t UpdateThreadIDsFromStopReplyThreadsValue(std::string &value);
358 
359   bool HandleNotifyPacket(StringExtractorGDBRemote &packet);
360 
361   bool StartAsyncThread();
362 
363   void StopAsyncThread();
364 
365   static lldb::thread_result_t AsyncThread(void *arg);
366 
367   static bool
368   MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp,
369                             lldb::pid_t pid, bool exited, int signo,
370                             int exit_status);
371 
372   lldb::StateType SetThreadStopInfo(StringExtractor &stop_packet);
373 
374   bool
375   GetThreadStopInfoFromJSON(ThreadGDBRemote *thread,
376                             const StructuredData::ObjectSP &thread_infos_sp);
377 
378   lldb::ThreadSP SetThreadStopInfo(StructuredData::Dictionary *thread_dict);
379 
380   lldb::ThreadSP
381   SetThreadStopInfo(lldb::tid_t tid,
382                     ExpeditedRegisterMap &expedited_register_map, uint8_t signo,
383                     const std::string &thread_name, const std::string &reason,
384                     const std::string &description, uint32_t exc_type,
385                     const std::vector<lldb::addr_t> &exc_data,
386                     lldb::addr_t thread_dispatch_qaddr, bool queue_vars_valid,
387                     lldb_private::LazyBool associated_with_libdispatch_queue,
388                     lldb::addr_t dispatch_queue_t, std::string &queue_name,
389                     lldb::QueueKind queue_kind, uint64_t queue_serial);
390 
391   void HandleStopReplySequence();
392 
393   void ClearThreadIDList();
394 
395   bool UpdateThreadIDList();
396 
397   void DidLaunchOrAttach(ArchSpec &process_arch);
398 
399   Status ConnectToDebugserver(llvm::StringRef host_port);
400 
401   const char *GetDispatchQueueNameForThread(lldb::addr_t thread_dispatch_qaddr,
402                                             std::string &dispatch_queue_name);
403 
404   DynamicLoader *GetDynamicLoader() override;
405 
406   // Query remote GDBServer for register information
407   bool GetGDBServerRegisterInfo(ArchSpec &arch);
408 
409   // Query remote GDBServer for a detailed loaded library list
410   Status GetLoadedModuleList(LoadedModuleInfoList &);
411 
412   lldb::ModuleSP LoadModuleAtAddress(const FileSpec &file,
413                                      lldb::addr_t link_map,
414                                      lldb::addr_t base_addr,
415                                      bool value_is_offset);
416 
417   Status UpdateAutomaticSignalFiltering() override;
418 
419   Status FlashErase(lldb::addr_t addr, size_t size);
420 
421   Status FlashDone();
422 
423   bool HasErased(FlashRange range);
424 
425 private:
426   //------------------------------------------------------------------
427   // For ProcessGDBRemote only
428   //------------------------------------------------------------------
429   std::string m_partial_profile_data;
430   std::map<uint64_t, uint32_t> m_thread_id_to_used_usec_map;
431   uint64_t m_last_signals_version = 0;
432 
433   static bool NewThreadNotifyBreakpointHit(void *baton,
434                                            StoppointCallbackContext *context,
435                                            lldb::user_id_t break_id,
436                                            lldb::user_id_t break_loc_id);
437 
438   //------------------------------------------------------------------
439   // ContinueDelegate interface
440   //------------------------------------------------------------------
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   DISALLOW_COPY_AND_ASSIGN(ProcessGDBRemote);
473 };
474 
475 } // namespace process_gdb_remote
476 } // namespace lldb_private
477 
478 #endif // liblldb_ProcessGDBRemote_h_
479