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