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