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