LLDB  mainline
GDBRemoteCommunicationClient.h
Go to the documentation of this file.
1 //===-- GDBRemoteCommunicationClient.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_GDBREMOTECOMMUNICATIONCLIENT_H
10 #define LLDB_SOURCE_PLUGINS_PROCESS_GDB_REMOTE_GDBREMOTECOMMUNICATIONCLIENT_H
11 
12 #include "GDBRemoteClientBase.h"
13 
14 #include <chrono>
15 #include <map>
16 #include <mutex>
17 #include <string>
18 #include <vector>
19 
20 #include "lldb/Host/File.h"
21 #include "lldb/Utility/ArchSpec.h"
22 #include "lldb/Utility/GDBRemote.h"
25 #if defined(_WIN32)
27 #endif
28 
29 #include "llvm/ADT/Optional.h"
30 #include "llvm/Support/VersionTuple.h"
31 
32 namespace lldb_private {
33 namespace process_gdb_remote {
34 
35 /// The offsets used by the target when relocating the executable. Decoded from
36 /// qOffsets packet response.
37 struct QOffsets {
38  /// If true, the offsets field describes segments. Otherwise, it describes
39  /// sections.
40  bool segments;
41 
42  /// The individual offsets. Section offsets have two or three members.
43  /// Segment offsets have either one of two.
44  std::vector<uint64_t> offsets;
45 };
46 inline bool operator==(const QOffsets &a, const QOffsets &b) {
47  return a.segments == b.segments && a.offsets == b.offsets;
48 }
49 llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const QOffsets &offsets);
50 
52 public:
54 
55  ~GDBRemoteCommunicationClient() override;
56 
57  // After connecting, send the handshake to the server to make sure
58  // we are communicating with it.
59  bool HandshakeWithServer(Status *error_ptr);
60 
61  // For packets which specify a range of output to be returned,
62  // return all of the output via a series of request packets of the form
63  // <prefix>0,<size>
64  // <prefix><size>,<size>
65  // <prefix><size>*2,<size>
66  // <prefix><size>*3,<size>
67  // ...
68  // until a "$l..." packet is received, indicating the end.
69  // (size is in hex; this format is used by a standard gdbserver to
70  // return the given portion of the output specified by <prefix>;
71  // for example, "qXfer:libraries-svr4:read::fff,1000" means
72  // "return a chunk of the xml description file for shared
73  // library load addresses, where the chunk starts at offset 0xfff
74  // and continues for 0x1000 bytes").
75  // Concatenate the resulting server response packets together and
76  // return in response_string. If any packet fails, the return value
77  // indicates that failure and the returned string value is undefined.
79  SendPacketsAndConcatenateResponses(const char *send_payload_prefix,
80  std::string &response_string);
81 
82  bool GetThreadSuffixSupported();
83 
84  // This packet is usually sent first and the boolean return value
85  // indicates if the packet was send and any response was received
86  // even in the response is UNIMPLEMENTED. If the packet failed to
87  // get a response, then false is returned. This quickly tells us
88  // if we were able to connect and communicate with the remote GDB
89  // server
90  bool QueryNoAckModeSupported();
91 
92  void GetListThreadsInStopReplySupported();
93 
94  lldb::pid_t GetCurrentProcessID(bool allow_lazy = true);
95 
96  bool GetLaunchSuccess(std::string &error_str);
97 
98  bool LaunchGDBServer(const char *remote_accept_hostname, lldb::pid_t &pid,
99  uint16_t &port, std::string &socket_name);
100 
101  size_t QueryGDBServer(
102  std::vector<std::pair<uint16_t, std::string>> &connection_urls);
103 
104  bool KillSpawnedProcess(lldb::pid_t pid);
105 
106  /// Sends a GDB remote protocol 'A' packet that delivers program
107  /// arguments to the remote server.
108  ///
109  /// \param[in] launch_info
110  /// A NULL terminated array of const C strings to use as the
111  /// arguments.
112  ///
113  /// \return
114  /// Zero if the response was "OK", a positive value if the
115  /// the response was "Exx" where xx are two hex digits, or
116  /// -1 if the call is unsupported or any other unexpected
117  /// response was received.
118  int SendArgumentsPacket(const ProcessLaunchInfo &launch_info);
119 
120  /// Sends a "QEnvironment:NAME=VALUE" packet that will build up the
121  /// environment that will get used when launching an application
122  /// in conjunction with the 'A' packet. This function can be called
123  /// multiple times in a row in order to pass on the desired
124  /// environment that the inferior should be launched with.
125  ///
126  /// \param[in] name_equal_value
127  /// A NULL terminated C string that contains a single environment
128  /// in the format "NAME=VALUE".
129  ///
130  /// \return
131  /// Zero if the response was "OK", a positive value if the
132  /// the response was "Exx" where xx are two hex digits, or
133  /// -1 if the call is unsupported or any other unexpected
134  /// response was received.
135  int SendEnvironmentPacket(char const *name_equal_value);
136  int SendEnvironment(const Environment &env);
137 
138  int SendLaunchArchPacket(const char *arch);
139 
140  int SendLaunchEventDataPacket(const char *data,
141  bool *was_supported = nullptr);
142 
143  /// Sends a "vAttach:PID" where PID is in hex.
144  ///
145  /// \param[in] pid
146  /// A process ID for the remote gdb server to attach to.
147  ///
148  /// \param[out] response
149  /// The response received from the gdb server. If the return
150  /// value is zero, \a response will contain a stop reply
151  /// packet.
152  ///
153  /// \return
154  /// Zero if the attach was successful, or an error indicating
155  /// an error code.
156  int SendAttach(lldb::pid_t pid, StringExtractorGDBRemote &response);
157 
158  /// Sends a GDB remote protocol 'I' packet that delivers stdin
159  /// data to the remote process.
160  ///
161  /// \param[in] data
162  /// A pointer to stdin data.
163  ///
164  /// \param[in] data_len
165  /// The number of bytes available at \a data.
166  ///
167  /// \return
168  /// Zero if the attach was successful, or an error indicating
169  /// an error code.
170  int SendStdinNotification(const char *data, size_t data_len);
171 
172  /// Sets the path to use for stdin/out/err for a process
173  /// that will be launched with the 'A' packet.
174  ///
175  /// \param[in] file_spec
176  /// The path to use for stdin/out/err
177  ///
178  /// \return
179  /// Zero if the for success, or an error code for failure.
180  int SetSTDIN(const FileSpec &file_spec);
181  int SetSTDOUT(const FileSpec &file_spec);
182  int SetSTDERR(const FileSpec &file_spec);
183 
184  /// Sets the disable ASLR flag to \a enable for a process that will
185  /// be launched with the 'A' packet.
186  ///
187  /// \param[in] enable
188  /// A boolean value indicating whether to disable ASLR or not.
189  ///
190  /// \return
191  /// Zero if the for success, or an error code for failure.
192  int SetDisableASLR(bool enable);
193 
194  /// Sets the DetachOnError flag to \a enable for the process controlled by the
195  /// stub.
196  ///
197  /// \param[in] enable
198  /// A boolean value indicating whether to detach on error or not.
199  ///
200  /// \return
201  /// Zero if the for success, or an error code for failure.
202  int SetDetachOnError(bool enable);
203 
204  /// Sets the working directory to \a path for a process that will
205  /// be launched with the 'A' packet for non platform based
206  /// connections. If this packet is sent to a GDB server that
207  /// implements the platform, it will change the current working
208  /// directory for the platform process.
209  ///
210  /// \param[in] working_dir
211  /// The path to a directory to use when launching our process
212  ///
213  /// \return
214  /// Zero if the for success, or an error code for failure.
215  int SetWorkingDir(const FileSpec &working_dir);
216 
217  /// Gets the current working directory of a remote platform GDB
218  /// server.
219  ///
220  /// \param[out] working_dir
221  /// The current working directory on the remote platform.
222  ///
223  /// \return
224  /// Boolean for success
225  bool GetWorkingDir(FileSpec &working_dir);
226 
227  lldb::addr_t AllocateMemory(size_t size, uint32_t permissions);
228 
229  bool DeallocateMemory(lldb::addr_t addr);
230 
231  Status Detach(bool keep_stopped);
232 
234 
235  Status GetWatchpointSupportInfo(uint32_t &num);
236 
237  Status GetWatchpointSupportInfo(uint32_t &num, bool &after,
238  const ArchSpec &arch);
239 
240  Status GetWatchpointsTriggerAfterInstruction(bool &after,
241  const ArchSpec &arch);
242 
243  const ArchSpec &GetHostArchitecture();
244 
245  std::chrono::seconds GetHostDefaultPacketTimeout();
246 
247  const ArchSpec &GetProcessArchitecture();
248 
249  void GetRemoteQSupported();
250 
251  bool GetVContSupported(char flavor);
252 
253  bool GetpPacketSupported(lldb::tid_t tid);
254 
255  bool GetxPacketSupported();
256 
257  bool GetVAttachOrWaitSupported();
258 
259  bool GetSyncThreadStateSupported();
260 
261  void ResetDiscoverableSettings(bool did_exec);
262 
263  bool GetHostInfo(bool force = false);
264 
265  bool GetDefaultThreadId(lldb::tid_t &tid);
266 
267  llvm::VersionTuple GetOSVersion();
268 
269  llvm::VersionTuple GetMacCatalystVersion();
270 
271  bool GetOSBuildString(std::string &s);
272 
273  bool GetOSKernelDescription(std::string &s);
274 
275  ArchSpec GetSystemArchitecture();
276 
277  bool GetHostname(std::string &s);
278 
279  lldb::addr_t GetShlibInfoAddr();
280 
281  bool GetSupportsThreadSuffix();
282 
283  bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info);
284 
285  uint32_t FindProcesses(const ProcessInstanceInfoMatch &process_match_info,
286  ProcessInstanceInfoList &process_infos);
287 
288  bool GetUserName(uint32_t uid, std::string &name);
289 
290  bool GetGroupName(uint32_t gid, std::string &name);
291 
292  bool HasFullVContSupport() { return GetVContSupported('A'); }
293 
294  bool HasAnyVContSupport() { return GetVContSupported('a'); }
295 
296  bool GetStopReply(StringExtractorGDBRemote &response);
297 
298  bool GetThreadStopInfo(lldb::tid_t tid, StringExtractorGDBRemote &response);
299 
301  switch (type) {
302  case eBreakpointSoftware:
303  return m_supports_z0;
304  case eBreakpointHardware:
305  return m_supports_z1;
306  case eWatchpointWrite:
307  return m_supports_z2;
308  case eWatchpointRead:
309  return m_supports_z3;
311  return m_supports_z4;
312  default:
313  return false;
314  }
315  }
316 
317  uint8_t SendGDBStoppointTypePacket(
318  GDBStoppointType type, // Type of breakpoint or watchpoint
319  bool insert, // Insert or remove?
320  lldb::addr_t addr, // Address of breakpoint or watchpoint
321  uint32_t length); // Byte Size of breakpoint or watchpoint
322 
323  bool SetNonStopMode(const bool enable);
324 
325  void TestPacketSpeed(const uint32_t num_packets, uint32_t max_send,
326  uint32_t max_recv, uint64_t recv_amount, bool json,
327  Stream &strm);
328 
329  // This packet is for testing the speed of the interface only. Both
330  // the client and server need to support it, but this allows us to
331  // measure the packet speed without any other work being done on the
332  // other end and avoids any of that work affecting the packet send
333  // and response times.
334  bool SendSpeedTestPacket(uint32_t send_size, uint32_t recv_size);
335 
336  bool SetCurrentThread(uint64_t tid);
337 
338  bool SetCurrentThreadForRun(uint64_t tid);
339 
340  bool GetQXferAuxvReadSupported();
341 
342  void EnableErrorStringInPacket();
343 
344  bool GetQXferLibrariesReadSupported();
345 
346  bool GetQXferLibrariesSVR4ReadSupported();
347 
348  uint64_t GetRemoteMaxPacketSize();
349 
350  bool GetEchoSupported();
351 
352  bool GetQPassSignalsSupported();
353 
354  bool GetAugmentedLibrariesSVR4ReadSupported();
355 
356  bool GetQXferFeaturesReadSupported();
357 
358  bool GetQXferMemoryMapReadSupported();
359 
361  {
362  // Uncomment this to have lldb pretend the debug server doesn't respond to
363  // alloc/dealloc memory packets.
364  // m_supports_alloc_dealloc_memory = lldb_private::eLazyBoolNo;
365  return m_supports_alloc_dealloc_memory;
366  }
367 
368  size_t GetCurrentThreadIDs(std::vector<lldb::tid_t> &thread_ids,
369  bool &sequence_mutex_unavailable);
370 
371  lldb::user_id_t OpenFile(const FileSpec &file_spec, File::OpenOptions flags,
372  mode_t mode, Status &error);
373 
374  bool CloseFile(lldb::user_id_t fd, Status &error);
375 
376  lldb::user_id_t GetFileSize(const FileSpec &file_spec);
377 
378  Status GetFilePermissions(const FileSpec &file_spec,
379  uint32_t &file_permissions);
380 
381  Status SetFilePermissions(const FileSpec &file_spec,
382  uint32_t file_permissions);
383 
384  uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst,
385  uint64_t dst_len, Status &error);
386 
387  uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src,
388  uint64_t src_len, Status &error);
389 
390  Status CreateSymlink(const FileSpec &src, const FileSpec &dst);
391 
392  Status Unlink(const FileSpec &file_spec);
393 
394  Status MakeDirectory(const FileSpec &file_spec, uint32_t mode);
395 
396  bool GetFileExists(const FileSpec &file_spec);
397 
398  Status RunShellCommand(
399  const char *command, // Shouldn't be nullptr
400  const FileSpec &working_dir, // Pass empty FileSpec to use the current
401  // working directory
402  int *status_ptr, // Pass nullptr if you don't want the process exit status
403  int *signo_ptr, // Pass nullptr if you don't want the signal that caused
404  // the process to exit
405  std::string
406  *command_output, // Pass nullptr if you don't want the command output
407  const Timeout<std::micro> &timeout);
408 
409  bool CalculateMD5(const FileSpec &file_spec, uint64_t &high, uint64_t &low);
410 
411  lldb::DataBufferSP ReadRegister(
412  lldb::tid_t tid,
413  uint32_t
414  reg_num); // Must be the eRegisterKindProcessPlugin register number
415 
416  lldb::DataBufferSP ReadAllRegisters(lldb::tid_t tid);
417 
418  bool
419  WriteRegister(lldb::tid_t tid,
420  uint32_t reg_num, // eRegisterKindProcessPlugin register number
421  llvm::ArrayRef<uint8_t> data);
422 
423  bool WriteAllRegisters(lldb::tid_t tid, llvm::ArrayRef<uint8_t> data);
424 
425  bool SaveRegisterState(lldb::tid_t tid, uint32_t &save_id);
426 
427  bool RestoreRegisterState(lldb::tid_t tid, uint32_t save_id);
428 
429  bool SyncThreadState(lldb::tid_t tid);
430 
431  const char *GetGDBServerProgramName();
432 
433  uint32_t GetGDBServerProgramVersion();
434 
435  bool AvoidGPackets(ProcessGDBRemote *process);
436 
437  StructuredData::ObjectSP GetThreadsInfo();
438 
439  bool GetThreadExtendedInfoSupported();
440 
441  bool GetLoadedDynamicLibrariesInfosSupported();
442 
443  bool GetSharedCacheInfoSupported();
444 
445  /// Use qOffsets to query the offset used when relocating the target
446  /// executable. If successful, the returned structure will contain at least
447  /// one value in the offsets field.
448  llvm::Optional<QOffsets> GetQOffsets();
449 
450  bool GetModuleInfo(const FileSpec &module_file_spec,
451  const ArchSpec &arch_spec, ModuleSpec &module_spec);
452 
453  llvm::Optional<std::vector<ModuleSpec>>
454  GetModulesInfo(llvm::ArrayRef<FileSpec> module_file_specs,
455  const llvm::Triple &triple);
456 
457  bool ReadExtFeature(const lldb_private::ConstString object,
458  const lldb_private::ConstString annex, std::string &out,
459  lldb_private::Status &err);
460 
461  void ServeSymbolLookups(lldb_private::Process *process);
462 
463  // Sends QPassSignals packet to the server with given signals to ignore.
464  Status SendSignalsToIgnore(llvm::ArrayRef<int32_t> signals);
465 
466  /// Return the feature set supported by the gdb-remote server.
467  ///
468  /// This method returns the remote side's response to the qSupported
469  /// packet. The response is the complete string payload returned
470  /// to the client.
471  ///
472  /// \return
473  /// The string returned by the server to the qSupported query.
474  const std::string &GetServerSupportedFeatures() const {
475  return m_qSupported_response;
476  }
477 
478  /// Return the array of async JSON packet types supported by the remote.
479  ///
480  /// This method returns the remote side's array of supported JSON
481  /// packet types as a list of type names. Each of the results are
482  /// expected to have an Enable{type_name} command to enable and configure
483  /// the related feature. Each type_name for an enabled feature will
484  /// possibly send async-style packets that contain a payload of a
485  /// binhex-encoded JSON dictionary. The dictionary will have a
486  /// string field named 'type', that contains the type_name of the
487  /// supported packet type.
488  ///
489  /// There is a Plugin category called structured-data plugins.
490  /// A plugin indicates whether it knows how to handle a type_name.
491  /// If so, it can be used to process the async JSON packet.
492  ///
493  /// \return
494  /// The string returned by the server to the qSupported query.
495  lldb_private::StructuredData::Array *GetSupportedStructuredDataPlugins();
496 
497  /// Configure a StructuredData feature on the remote end.
498  ///
499  /// \see \b Process::ConfigureStructuredData(...) for details.
500  Status
501  ConfigureRemoteStructuredData(ConstString type_name,
502  const StructuredData::ObjectSP &config_sp);
503 
504  lldb::user_id_t SendStartTracePacket(const TraceOptions &options,
505  Status &error);
506 
507  Status SendStopTracePacket(lldb::user_id_t uid, lldb::tid_t thread_id);
508 
509  Status SendGetDataPacket(lldb::user_id_t uid, lldb::tid_t thread_id,
510  llvm::MutableArrayRef<uint8_t> &buffer,
511  size_t offset = 0);
512 
513  Status SendGetMetaDataPacket(lldb::user_id_t uid, lldb::tid_t thread_id,
514  llvm::MutableArrayRef<uint8_t> &buffer,
515  size_t offset = 0);
516 
517  Status SendGetTraceConfigPacket(lldb::user_id_t uid, TraceOptions &options);
518 
519 protected:
555 
556  bool m_supports_qProcessInfoPID : 1, m_supports_qfProcessInfo : 1,
557  m_supports_qUserName : 1, m_supports_qGroupName : 1,
558  m_supports_qThreadStopInfo : 1, m_supports_z0 : 1, m_supports_z1 : 1,
559  m_supports_z2 : 1, m_supports_z3 : 1, m_supports_z4 : 1,
560  m_supports_QEnvironment : 1, m_supports_QEnvironmentHexEncoded : 1,
561  m_supports_qSymbol : 1, m_qSymbol_requests_done : 1,
562  m_supports_qModuleInfo : 1, m_supports_jThreadsInfo : 1,
563  m_supports_jModulesInfo : 1;
564 
566  lldb::tid_t m_curr_tid; // Current gdb remote protocol thread index for all
567  // other operations
568  lldb::tid_t m_curr_tid_run; // Current gdb remote protocol thread index for
569  // continue, step, etc
570 
572 
575  llvm::VersionTuple m_os_version;
576  llvm::VersionTuple m_maccatalyst_version;
577  std::string m_os_build;
578  std::string m_os_kernel;
579  std::string m_hostname;
580  std::string m_gdb_server_name; // from reply to qGDBServerVersion, empty if
581  // qGDBServerVersion is not supported
582  uint32_t m_gdb_server_version; // from reply to qGDBServerVersion, zero if
583  // qGDBServerVersion is not supported
584  std::chrono::seconds m_default_packet_timeout;
585  uint64_t m_max_packet_size; // as returned by qSupported
586  std::string m_qSupported_response; // the complete response to qSupported
587 
590 
591  std::vector<MemoryRegionInfo> m_qXfer_memory_map;
593 
594  bool GetCurrentProcessInfo(bool allow_lazy_pid = true);
595 
596  bool GetGDBServerVersion();
597 
598  // Given the list of compression types that the remote debug stub can support,
599  // possibly enable compression if we find an encoding we can handle.
600  void MaybeEnableCompression(std::vector<std::string> supported_compressions);
601 
602  bool DecodeProcessInfoResponse(StringExtractorGDBRemote &response,
603  ProcessInstanceInfo &process_info);
604 
605  void OnRunPacketSent(bool first) override;
606 
607  PacketResult SendThreadSpecificPacketAndWaitForResponse(
608  lldb::tid_t tid, StreamString &&payload,
609  StringExtractorGDBRemote &response, bool send_async);
610 
611  Status SendGetTraceDataPacket(StreamGDBRemote &packet, lldb::user_id_t uid,
612  lldb::tid_t thread_id,
613  llvm::MutableArrayRef<uint8_t> &buffer,
614  size_t offset);
615 
616  Status LoadQXferMemoryMap();
617 
618  Status GetQXferMemoryMapRegionInfo(lldb::addr_t addr,
619  MemoryRegionInfo &region);
620 
621  LazyBool GetThreadPacketSupported(lldb::tid_t tid, llvm::StringRef packetStr);
622 
623 private:
626  operator=(const GDBRemoteCommunicationClient &) = delete;
627 };
628 
629 } // namespace process_gdb_remote
630 } // namespace lldb_private
631 
632 #endif // LLDB_SOURCE_PLUGINS_PROCESS_GDB_REMOTE_GDBREMOTECOMMUNICATIONCLIENT_H
bool operator==(const QOffsets &a, const QOffsets &b)
A class that represents a running process on the host machine.
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
Definition: Host.h:30
A file utility class.
Definition: FileSpec.h:56
An architecture specification class.
Definition: ArchSpec.h:33
std::vector< uint64_t > offsets
The individual offsets.
const std::string & GetServerSupportedFeatures() const
Return the feature set supported by the gdb-remote server.
The offsets used by the target when relocating the executable.
static MemoryRegionInfo GetMemoryRegionInfo(const MemoryRegionInfos &regions, lldb::addr_t load_addr)
uint64_t user_id_t
Definition: lldb-types.h:84
static llvm::raw_ostream & error(Stream &strm)
uint64_t tid_t
Definition: lldb-types.h:86
A plug-in interface definition class for debugging a process.
Definition: Process.h:362
bool segments
If true, the offsets field describes segments.
uint64_t addr_t
Definition: lldb-types.h:83
A uniqued constant string class.
Definition: ConstString.h:40
uint64_t pid_t
Definition: lldb-types.h:85
std::shared_ptr< Object > ObjectSP
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const QOffsets &offsets)
An error handling class.
Definition: Status.h:44