GDBRemoteCommunicationClient.h revision 344779
1//===-- GDBRemoteCommunicationClient.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_GDBRemoteCommunicationClient_h_
11#define liblldb_GDBRemoteCommunicationClient_h_
12
13#include "GDBRemoteClientBase.h"
14
15#include <chrono>
16#include <map>
17#include <mutex>
18#include <string>
19#include <vector>
20
21#include "lldb/Target/Process.h"
22#include "lldb/Utility/ArchSpec.h"
23#include "lldb/Utility/StreamGDBRemote.h"
24#include "lldb/Utility/StructuredData.h"
25
26#include "llvm/ADT/Optional.h"
27
28namespace lldb_private {
29namespace process_gdb_remote {
30
31class GDBRemoteCommunicationClient : public GDBRemoteClientBase {
32public:
33  GDBRemoteCommunicationClient();
34
35  ~GDBRemoteCommunicationClient() override;
36
37  //------------------------------------------------------------------
38  // After connecting, send the handshake to the server to make sure
39  // we are communicating with it.
40  //------------------------------------------------------------------
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.
60  PacketResult
61  SendPacketsAndConcatenateResponses(const char *send_payload_prefix,
62                                     std::string &response_string);
63
64  bool GetThreadSuffixSupported();
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
72  bool QueryNoAckModeSupported();
73
74  void GetListThreadsInStopReplySupported();
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
86  bool KillSpawnedProcess(lldb::pid_t pid);
87
88  //------------------------------------------------------------------
89  /// Sends a GDB remote protocol 'A' packet that delivers program
90  /// arguments to the remote server.
91  ///
92  /// @param[in] argv
93  ///     A NULL terminated array of const C strings to use as the
94  ///     arguments.
95  ///
96  /// @return
97  ///     Zero if the response was "OK", a positive value if the
98  ///     the response was "Exx" where xx are two hex digits, or
99  ///     -1 if the call is unsupported or any other unexpected
100  ///     response was received.
101  //------------------------------------------------------------------
102  int SendArgumentsPacket(const ProcessLaunchInfo &launch_info);
103
104  //------------------------------------------------------------------
105  /// Sends a "QEnvironment:NAME=VALUE" packet that will build up the
106  /// environment that will get used when launching an application
107  /// in conjunction with the 'A' packet. This function can be called
108  /// multiple times in a row in order to pass on the desired
109  /// environment that the inferior should be launched with.
110  ///
111  /// @param[in] name_equal_value
112  ///     A NULL terminated C string that contains a single environment
113  ///     in the format "NAME=VALUE".
114  ///
115  /// @return
116  ///     Zero if the response was "OK", a positive value if the
117  ///     the response was "Exx" where xx are two hex digits, or
118  ///     -1 if the call is unsupported or any other unexpected
119  ///     response was received.
120  //------------------------------------------------------------------
121  int SendEnvironmentPacket(char const *name_equal_value);
122  int SendEnvironment(const Environment &env);
123
124  int SendLaunchArchPacket(const char *arch);
125
126  int SendLaunchEventDataPacket(const char *data,
127                                bool *was_supported = nullptr);
128
129  //------------------------------------------------------------------
130  /// Sends a "vAttach:PID" where PID is in hex.
131  ///
132  /// @param[in] pid
133  ///     A process ID for the remote gdb server to attach to.
134  ///
135  /// @param[out] response
136  ///     The response received from the gdb server. If the return
137  ///     value is zero, \a response will contain a stop reply
138  ///     packet.
139  ///
140  /// @return
141  ///     Zero if the attach was successful, or an error indicating
142  ///     an error code.
143  //------------------------------------------------------------------
144  int SendAttach(lldb::pid_t pid, StringExtractorGDBRemote &response);
145
146  //------------------------------------------------------------------
147  /// Sends a GDB remote protocol 'I' packet that delivers stdin
148  /// data to the remote process.
149  ///
150  /// @param[in] data
151  ///     A pointer to stdin data.
152  ///
153  /// @param[in] data_len
154  ///     The number of bytes available at \a data.
155  ///
156  /// @return
157  ///     Zero if the attach was successful, or an error indicating
158  ///     an error code.
159  //------------------------------------------------------------------
160  int SendStdinNotification(const char *data, size_t data_len);
161
162  //------------------------------------------------------------------
163  /// Sets the path to use for stdin/out/err for a process
164  /// that will be launched with the 'A' packet.
165  ///
166  /// @param[in] path
167  ///     The path to use for stdin/out/err
168  ///
169  /// @return
170  ///     Zero if the for success, or an error code for failure.
171  //------------------------------------------------------------------
172  int SetSTDIN(const FileSpec &file_spec);
173  int SetSTDOUT(const FileSpec &file_spec);
174  int SetSTDERR(const FileSpec &file_spec);
175
176  //------------------------------------------------------------------
177  /// Sets the disable ASLR flag to \a enable for a process that will
178  /// be launched with the 'A' packet.
179  ///
180  /// @param[in] enable
181  ///     A boolean value indicating whether to disable ASLR or not.
182  ///
183  /// @return
184  ///     Zero if the for success, or an error code for failure.
185  //------------------------------------------------------------------
186  int SetDisableASLR(bool enable);
187
188  //------------------------------------------------------------------
189  /// Sets the DetachOnError flag to \a enable for the process controlled by the
190  /// stub.
191  ///
192  /// @param[in] enable
193  ///     A boolean value indicating whether to detach on error or not.
194  ///
195  /// @return
196  ///     Zero if the for success, or an error code for failure.
197  //------------------------------------------------------------------
198  int SetDetachOnError(bool enable);
199
200  //------------------------------------------------------------------
201  /// Sets the working directory to \a path for a process that will
202  /// be launched with the 'A' packet for non platform based
203  /// connections. If this packet is sent to a GDB server that
204  /// implements the platform, it will change the current working
205  /// directory for the platform process.
206  ///
207  /// @param[in] working_dir
208  ///     The path to a directory to use when launching our process
209  ///
210  /// @return
211  ///     Zero if the for success, or an error code for failure.
212  //------------------------------------------------------------------
213  int SetWorkingDir(const FileSpec &working_dir);
214
215  //------------------------------------------------------------------
216  /// Gets the current working directory of a remote platform GDB
217  /// server.
218  ///
219  /// @param[out] working_dir
220  ///     The current working directory on the remote platform.
221  ///
222  /// @return
223  ///     Boolean for success
224  //------------------------------------------------------------------
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
233  Status GetMemoryRegionInfo(lldb::addr_t addr, MemoryRegionInfo &range_info);
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  bool GetOSBuildString(std::string &s);
270
271  bool GetOSKernelDescription(std::string &s);
272
273  ArchSpec GetSystemArchitecture();
274
275  bool GetHostname(std::string &s);
276
277  lldb::addr_t GetShlibInfoAddr();
278
279  bool GetSupportsThreadSuffix();
280
281  bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info);
282
283  uint32_t FindProcesses(const ProcessInstanceInfoMatch &process_match_info,
284                         ProcessInstanceInfoList &process_infos);
285
286  bool GetUserName(uint32_t uid, std::string &name);
287
288  bool GetGroupName(uint32_t gid, std::string &name);
289
290  bool HasFullVContSupport() { return GetVContSupported('A'); }
291
292  bool HasAnyVContSupport() { return GetVContSupported('a'); }
293
294  bool GetStopReply(StringExtractorGDBRemote &response);
295
296  bool GetThreadStopInfo(lldb::tid_t tid, StringExtractorGDBRemote &response);
297
298  bool SupportsGDBStoppointPacket(GDBStoppointType type) {
299    switch (type) {
300    case eBreakpointSoftware:
301      return m_supports_z0;
302    case eBreakpointHardware:
303      return m_supports_z1;
304    case eWatchpointWrite:
305      return m_supports_z2;
306    case eWatchpointRead:
307      return m_supports_z3;
308    case eWatchpointReadWrite:
309      return m_supports_z4;
310    default:
311      return false;
312    }
313  }
314
315  uint8_t SendGDBStoppointTypePacket(
316      GDBStoppointType type, // Type of breakpoint or watchpoint
317      bool insert,           // Insert or remove?
318      lldb::addr_t addr,     // Address of breakpoint or watchpoint
319      uint32_t length);      // Byte Size of breakpoint or watchpoint
320
321  bool SetNonStopMode(const bool enable);
322
323  void TestPacketSpeed(const uint32_t num_packets, uint32_t max_send,
324                       uint32_t max_recv, uint64_t recv_amount, bool json,
325                       Stream &strm);
326
327  // This packet is for testing the speed of the interface only. Both
328  // the client and server need to support it, but this allows us to
329  // measure the packet speed without any other work being done on the
330  // other end and avoids any of that work affecting the packet send
331  // and response times.
332  bool SendSpeedTestPacket(uint32_t send_size, uint32_t recv_size);
333
334  bool SetCurrentThread(uint64_t tid);
335
336  bool SetCurrentThreadForRun(uint64_t tid);
337
338  bool GetQXferAuxvReadSupported();
339
340  void EnableErrorStringInPacket();
341
342  bool GetQXferLibrariesReadSupported();
343
344  bool GetQXferLibrariesSVR4ReadSupported();
345
346  uint64_t GetRemoteMaxPacketSize();
347
348  bool GetEchoSupported();
349
350  bool GetQPassSignalsSupported();
351
352  bool GetAugmentedLibrariesSVR4ReadSupported();
353
354  bool GetQXferFeaturesReadSupported();
355
356  bool GetQXferMemoryMapReadSupported();
357
358  LazyBool SupportsAllocDeallocMemory() // const
359  {
360    // Uncomment this to have lldb pretend the debug server doesn't respond to
361    // alloc/dealloc memory packets.
362    // m_supports_alloc_dealloc_memory = lldb_private::eLazyBoolNo;
363    return m_supports_alloc_dealloc_memory;
364  }
365
366  size_t GetCurrentThreadIDs(std::vector<lldb::tid_t> &thread_ids,
367                             bool &sequence_mutex_unavailable);
368
369  lldb::user_id_t OpenFile(const FileSpec &file_spec, uint32_t flags,
370                           mode_t mode, Status &error);
371
372  bool CloseFile(lldb::user_id_t fd, Status &error);
373
374  lldb::user_id_t GetFileSize(const FileSpec &file_spec);
375
376  Status GetFilePermissions(const FileSpec &file_spec,
377                            uint32_t &file_permissions);
378
379  Status SetFilePermissions(const FileSpec &file_spec,
380                            uint32_t file_permissions);
381
382  uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst,
383                    uint64_t dst_len, Status &error);
384
385  uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src,
386                     uint64_t src_len, Status &error);
387
388  Status CreateSymlink(const FileSpec &src, const FileSpec &dst);
389
390  Status Unlink(const FileSpec &file_spec);
391
392  Status MakeDirectory(const FileSpec &file_spec, uint32_t mode);
393
394  bool GetFileExists(const FileSpec &file_spec);
395
396  Status RunShellCommand(
397      const char *command,         // Shouldn't be nullptr
398      const FileSpec &working_dir, // Pass empty FileSpec to use the current
399                                   // working directory
400      int *status_ptr, // Pass nullptr if you don't want the process exit status
401      int *signo_ptr,  // Pass nullptr if you don't want the signal that caused
402                       // the process to exit
403      std::string
404          *command_output, // Pass nullptr if you don't want the command output
405      const Timeout<std::micro> &timeout);
406
407  bool CalculateMD5(const FileSpec &file_spec, uint64_t &high, uint64_t &low);
408
409  lldb::DataBufferSP ReadRegister(
410      lldb::tid_t tid,
411      uint32_t
412          reg_num); // Must be the eRegisterKindProcessPlugin register number
413
414  lldb::DataBufferSP ReadAllRegisters(lldb::tid_t tid);
415
416  bool
417  WriteRegister(lldb::tid_t tid,
418                uint32_t reg_num, // eRegisterKindProcessPlugin register number
419                llvm::ArrayRef<uint8_t> data);
420
421  bool WriteAllRegisters(lldb::tid_t tid, llvm::ArrayRef<uint8_t> data);
422
423  bool SaveRegisterState(lldb::tid_t tid, uint32_t &save_id);
424
425  bool RestoreRegisterState(lldb::tid_t tid, uint32_t save_id);
426
427  bool SyncThreadState(lldb::tid_t tid);
428
429  const char *GetGDBServerProgramName();
430
431  uint32_t GetGDBServerProgramVersion();
432
433  bool AvoidGPackets(ProcessGDBRemote *process);
434
435  StructuredData::ObjectSP GetThreadsInfo();
436
437  bool GetThreadExtendedInfoSupported();
438
439  bool GetLoadedDynamicLibrariesInfosSupported();
440
441  bool GetSharedCacheInfoSupported();
442
443  bool GetModuleInfo(const FileSpec &module_file_spec,
444                     const ArchSpec &arch_spec, ModuleSpec &module_spec);
445
446  llvm::Optional<std::vector<ModuleSpec>>
447  GetModulesInfo(llvm::ArrayRef<FileSpec> module_file_specs,
448                 const llvm::Triple &triple);
449
450  bool ReadExtFeature(const lldb_private::ConstString object,
451                      const lldb_private::ConstString annex, std::string &out,
452                      lldb_private::Status &err);
453
454  void ServeSymbolLookups(lldb_private::Process *process);
455
456  // Sends QPassSignals packet to the server with given signals to ignore.
457  Status SendSignalsToIgnore(llvm::ArrayRef<int32_t> signals);
458
459  //------------------------------------------------------------------
460  /// Return the feature set supported by the gdb-remote server.
461  ///
462  /// This method returns the remote side's response to the qSupported
463  /// packet.  The response is the complete string payload returned
464  /// to the client.
465  ///
466  /// @return
467  ///     The string returned by the server to the qSupported query.
468  //------------------------------------------------------------------
469  const std::string &GetServerSupportedFeatures() const {
470    return m_qSupported_response;
471  }
472
473  //------------------------------------------------------------------
474  /// Return the array of async JSON packet types supported by the remote.
475  ///
476  /// This method returns the remote side's array of supported JSON
477  /// packet types as a list of type names.  Each of the results are
478  /// expected to have an Enable{type_name} command to enable and configure
479  /// the related feature.  Each type_name for an enabled feature will
480  /// possibly send async-style packets that contain a payload of a
481  /// binhex-encoded JSON dictionary.  The dictionary will have a
482  /// string field named 'type', that contains the type_name of the
483  /// supported packet type.
484  ///
485  /// There is a Plugin category called structured-data plugins.
486  /// A plugin indicates whether it knows how to handle a type_name.
487  /// If so, it can be used to process the async JSON packet.
488  ///
489  /// @return
490  ///     The string returned by the server to the qSupported query.
491  //------------------------------------------------------------------
492  lldb_private::StructuredData::Array *GetSupportedStructuredDataPlugins();
493
494  //------------------------------------------------------------------
495  /// Configure a StructuredData feature on the remote end.
496  ///
497  /// @see \b Process::ConfigureStructuredData(...) for details.
498  //------------------------------------------------------------------
499  Status
500  ConfigureRemoteStructuredData(const ConstString &type_name,
501                                const StructuredData::ObjectSP &config_sp);
502
503  lldb::user_id_t SendStartTracePacket(const TraceOptions &options,
504                                       Status &error);
505
506  Status SendStopTracePacket(lldb::user_id_t uid, lldb::tid_t thread_id);
507
508  Status SendGetDataPacket(lldb::user_id_t uid, lldb::tid_t thread_id,
509                           llvm::MutableArrayRef<uint8_t> &buffer,
510                           size_t offset = 0);
511
512  Status SendGetMetaDataPacket(lldb::user_id_t uid, lldb::tid_t thread_id,
513                               llvm::MutableArrayRef<uint8_t> &buffer,
514                               size_t offset = 0);
515
516  Status SendGetTraceConfigPacket(lldb::user_id_t uid, TraceOptions &options);
517
518protected:
519  LazyBool m_supports_not_sending_acks;
520  LazyBool m_supports_thread_suffix;
521  LazyBool m_supports_threads_in_stop_reply;
522  LazyBool m_supports_vCont_all;
523  LazyBool m_supports_vCont_any;
524  LazyBool m_supports_vCont_c;
525  LazyBool m_supports_vCont_C;
526  LazyBool m_supports_vCont_s;
527  LazyBool m_supports_vCont_S;
528  LazyBool m_qHostInfo_is_valid;
529  LazyBool m_curr_pid_is_valid;
530  LazyBool m_qProcessInfo_is_valid;
531  LazyBool m_qGDBServerVersion_is_valid;
532  LazyBool m_supports_alloc_dealloc_memory;
533  LazyBool m_supports_memory_region_info;
534  LazyBool m_supports_watchpoint_support_info;
535  LazyBool m_supports_detach_stay_stopped;
536  LazyBool m_watchpoints_trigger_after_instruction;
537  LazyBool m_attach_or_wait_reply;
538  LazyBool m_prepare_for_reg_writing_reply;
539  LazyBool m_supports_p;
540  LazyBool m_supports_x;
541  LazyBool m_avoid_g_packets;
542  LazyBool m_supports_QSaveRegisterState;
543  LazyBool m_supports_qXfer_auxv_read;
544  LazyBool m_supports_qXfer_libraries_read;
545  LazyBool m_supports_qXfer_libraries_svr4_read;
546  LazyBool m_supports_qXfer_features_read;
547  LazyBool m_supports_qXfer_memory_map_read;
548  LazyBool m_supports_augmented_libraries_svr4_read;
549  LazyBool m_supports_jThreadExtendedInfo;
550  LazyBool m_supports_jLoadedDynamicLibrariesInfos;
551  LazyBool m_supports_jGetSharedCacheInfo;
552  LazyBool m_supports_QPassSignals;
553  LazyBool m_supports_error_string_reply;
554
555  bool m_supports_qProcessInfoPID : 1, m_supports_qfProcessInfo : 1,
556      m_supports_qUserName : 1, m_supports_qGroupName : 1,
557      m_supports_qThreadStopInfo : 1, m_supports_z0 : 1, m_supports_z1 : 1,
558      m_supports_z2 : 1, m_supports_z3 : 1, m_supports_z4 : 1,
559      m_supports_QEnvironment : 1, m_supports_QEnvironmentHexEncoded : 1,
560      m_supports_qSymbol : 1, m_qSymbol_requests_done : 1,
561      m_supports_qModuleInfo : 1, m_supports_jThreadsInfo : 1,
562      m_supports_jModulesInfo : 1;
563
564  lldb::pid_t m_curr_pid;
565  lldb::tid_t m_curr_tid; // Current gdb remote protocol thread index for all
566                          // other operations
567  lldb::tid_t m_curr_tid_run; // Current gdb remote protocol thread index for
568                              // continue, step, etc
569
570  uint32_t m_num_supported_hardware_watchpoints;
571
572  ArchSpec m_host_arch;
573  ArchSpec m_process_arch;
574  llvm::VersionTuple m_os_version;
575  std::string m_os_build;
576  std::string m_os_kernel;
577  std::string m_hostname;
578  std::string m_gdb_server_name; // from reply to qGDBServerVersion, empty if
579                                 // qGDBServerVersion is not supported
580  uint32_t m_gdb_server_version; // from reply to qGDBServerVersion, zero if
581                                 // qGDBServerVersion is not supported
582  std::chrono::seconds m_default_packet_timeout;
583  uint64_t m_max_packet_size;        // as returned by qSupported
584  std::string m_qSupported_response; // the complete response to qSupported
585
586  bool m_supported_async_json_packets_is_valid;
587  lldb_private::StructuredData::ObjectSP m_supported_async_json_packets_sp;
588
589  std::vector<MemoryRegionInfo> m_qXfer_memory_map;
590  bool m_qXfer_memory_map_loaded;
591
592  bool GetCurrentProcessInfo(bool allow_lazy_pid = true);
593
594  bool GetGDBServerVersion();
595
596  // Given the list of compression types that the remote debug stub can support,
597  // possibly enable compression if we find an encoding we can handle.
598  void MaybeEnableCompression(std::vector<std::string> supported_compressions);
599
600  bool DecodeProcessInfoResponse(StringExtractorGDBRemote &response,
601                                 ProcessInstanceInfo &process_info);
602
603  void OnRunPacketSent(bool first) override;
604
605  PacketResult SendThreadSpecificPacketAndWaitForResponse(
606      lldb::tid_t tid, StreamString &&payload,
607      StringExtractorGDBRemote &response, bool send_async);
608
609  Status SendGetTraceDataPacket(StreamGDBRemote &packet, lldb::user_id_t uid,
610                                lldb::tid_t thread_id,
611                                llvm::MutableArrayRef<uint8_t> &buffer,
612                                size_t offset);
613
614  Status LoadQXferMemoryMap();
615
616  Status GetQXferMemoryMapRegionInfo(lldb::addr_t addr,
617                                     MemoryRegionInfo &region);
618
619private:
620  DISALLOW_COPY_AND_ASSIGN(GDBRemoteCommunicationClient);
621};
622
623} // namespace process_gdb_remote
624} // namespace lldb_private
625
626#endif // liblldb_GDBRemoteCommunicationClient_h_
627