1 //===-- GDBRemoteCommunication.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_GDBREMOTECOMMUNICATION_H
10 #define LLDB_SOURCE_PLUGINS_PROCESS_GDB_REMOTE_GDBREMOTECOMMUNICATION_H
11 
12 #include "GDBRemoteCommunicationHistory.h"
13 
14 #include <condition_variable>
15 #include <mutex>
16 #include <queue>
17 #include <string>
18 #include <vector>
19 
20 #include "lldb/Core/Communication.h"
21 #include "lldb/Host/Config.h"
22 #include "lldb/Host/HostThread.h"
23 #include "lldb/Utility/Args.h"
24 #include "lldb/Utility/Listener.h"
25 #include "lldb/Utility/Predicate.h"
26 #include "lldb/Utility/StringExtractorGDBRemote.h"
27 #include "lldb/lldb-public.h"
28 
29 namespace lldb_private {
30 namespace repro {
31 class PacketRecorder;
32 }
33 namespace process_gdb_remote {
34 
35 enum GDBStoppointType {
36   eStoppointInvalid = -1,
37   eBreakpointSoftware = 0,
38   eBreakpointHardware,
39   eWatchpointWrite,
40   eWatchpointRead,
41   eWatchpointReadWrite
42 };
43 
44 enum class CompressionType {
45   None = 0,    // no compression
46   ZlibDeflate, // zlib's deflate compression scheme, requires zlib or Apple's
47                // libcompression
48   LZFSE,       // an Apple compression scheme, requires Apple's libcompression
49   LZ4, // lz compression - called "lz4 raw" in libcompression terms, compat with
50        // https://code.google.com/p/lz4/
51   LZMA, // Lempel–Ziv–Markov chain algorithm
52 };
53 
54 // Data included in the vFile:fstat packet.
55 // https://sourceware.org/gdb/onlinedocs/gdb/struct-stat.html#struct-stat
56 struct GDBRemoteFStatData {
57   llvm::support::ubig32_t gdb_st_dev;
58   llvm::support::ubig32_t gdb_st_ino;
59   llvm::support::ubig32_t gdb_st_mode;
60   llvm::support::ubig32_t gdb_st_nlink;
61   llvm::support::ubig32_t gdb_st_uid;
62   llvm::support::ubig32_t gdb_st_gid;
63   llvm::support::ubig32_t gdb_st_rdev;
64   llvm::support::ubig64_t gdb_st_size;
65   llvm::support::ubig64_t gdb_st_blksize;
66   llvm::support::ubig64_t gdb_st_blocks;
67   llvm::support::ubig32_t gdb_st_atime;
68   llvm::support::ubig32_t gdb_st_mtime;
69   llvm::support::ubig32_t gdb_st_ctime;
70 };
71 static_assert(sizeof(GDBRemoteFStatData) == 64,
72               "size of GDBRemoteFStatData is not 64");
73 
74 enum GDBErrno {
75 #define HANDLE_ERRNO(name, value) GDB_##name = value,
76 #include "Plugins/Process/gdb-remote/GDBRemoteErrno.def"
77   GDB_EUNKNOWN = 9999
78 };
79 
80 class ProcessGDBRemote;
81 
82 class GDBRemoteCommunication : public Communication {
83 public:
84   enum {
85     eBroadcastBitRunPacketSent = kLoUserBroadcastBit,
86     eBroadcastBitGdbReadThreadGotNotify =
87         kLoUserBroadcastBit << 1 // Sent when we received a notify packet.
88   };
89 
90   enum class PacketType { Invalid = 0, Standard, Notify };
91 
92   enum class PacketResult {
93     Success = 0,        // Success
94     ErrorSendFailed,    // Status sending the packet
95     ErrorSendAck,       // Didn't get an ack back after sending a packet
96     ErrorReplyFailed,   // Status getting the reply
97     ErrorReplyTimeout,  // Timed out waiting for reply
98     ErrorReplyInvalid,  // Got a reply but it wasn't valid for the packet that
99                         // was sent
100     ErrorReplyAck,      // Sending reply ack failed
101     ErrorDisconnected,  // We were disconnected
102     ErrorNoSequenceLock // We couldn't get the sequence lock for a multi-packet
103                         // request
104   };
105 
106   // Class to change the timeout for a given scope and restore it to the
107   // original value when the
108   // created ScopedTimeout object got out of scope
109   class ScopedTimeout {
110   public:
111     ScopedTimeout(GDBRemoteCommunication &gdb_comm,
112                   std::chrono::seconds timeout);
113     ~ScopedTimeout();
114 
115   private:
116     GDBRemoteCommunication &m_gdb_comm;
117     std::chrono::seconds m_saved_timeout;
118     // Don't ever reduce the timeout for a packet, only increase it. If the
119     // requested timeout if less than the current timeout, we don't set it
120     // and won't need to restore it.
121     bool m_timeout_modified;
122   };
123 
124   GDBRemoteCommunication(const char *comm_name, const char *listener_name);
125 
126   ~GDBRemoteCommunication() override;
127 
128   PacketResult GetAck();
129 
130   size_t SendAck();
131 
132   size_t SendNack();
133 
134   char CalculcateChecksum(llvm::StringRef payload);
135 
136   PacketType CheckForPacket(const uint8_t *src, size_t src_len,
137                             StringExtractorGDBRemote &packet);
138 
139   bool GetSendAcks() { return m_send_acks; }
140 
141   // Set the global packet timeout.
142   //
143   // For clients, this is the timeout that gets used when sending
144   // packets and waiting for responses. For servers, this is used when waiting
145   // for ACKs.
146   std::chrono::seconds SetPacketTimeout(std::chrono::seconds packet_timeout) {
147     const auto old_packet_timeout = m_packet_timeout;
148     m_packet_timeout = packet_timeout;
149     return old_packet_timeout;
150   }
151 
152   std::chrono::seconds GetPacketTimeout() const { return m_packet_timeout; }
153 
154   // Start a debugserver instance on the current host using the
155   // supplied connection URL.
156   Status StartDebugserverProcess(
157       const char *url,
158       Platform *platform, // If non nullptr, then check with the platform for
159                           // the GDB server binary if it can't be located
160       ProcessLaunchInfo &launch_info, uint16_t *port, const Args *inferior_args,
161       int pass_comm_fd); // Communication file descriptor to pass during
162                          // fork/exec to avoid having to connect/accept
163 
164   void DumpHistory(Stream &strm);
165 
166   void SetPacketRecorder(repro::PacketRecorder *recorder);
167 
168   static llvm::Error ConnectLocally(GDBRemoteCommunication &client,
169                                     GDBRemoteCommunication &server);
170 
171   /// Expand GDB run-length encoding.
172   static std::string ExpandRLE(std::string);
173 
174 protected:
175   std::chrono::seconds m_packet_timeout;
176   uint32_t m_echo_number;
177   LazyBool m_supports_qEcho;
178   GDBRemoteCommunicationHistory m_history;
179   bool m_send_acks;
180   bool m_is_platform; // Set to true if this class represents a platform,
181                       // false if this class represents a debug session for
182                       // a single process
183 
184   CompressionType m_compression_type;
185 
186   PacketResult SendPacketNoLock(llvm::StringRef payload);
187   PacketResult SendRawPacketNoLock(llvm::StringRef payload,
188                                    bool skip_ack = false);
189 
190   PacketResult ReadPacket(StringExtractorGDBRemote &response,
191                           Timeout<std::micro> timeout, bool sync_on_timeout);
192 
193   PacketResult ReadPacketWithOutputSupport(
194       StringExtractorGDBRemote &response, Timeout<std::micro> timeout,
195       bool sync_on_timeout,
196       llvm::function_ref<void(llvm::StringRef)> output_callback);
197 
198   // Pop a packet from the queue in a thread safe manner
199   PacketResult PopPacketFromQueue(StringExtractorGDBRemote &response,
200                                   Timeout<std::micro> timeout);
201 
202   PacketResult WaitForPacketNoLock(StringExtractorGDBRemote &response,
203                                    Timeout<std::micro> timeout,
204                                    bool sync_on_timeout);
205 
206   bool CompressionIsEnabled() {
207     return m_compression_type != CompressionType::None;
208   }
209 
210   // If compression is enabled, decompress the packet in m_bytes and update
211   // m_bytes with the uncompressed version.
212   // Returns 'true' packet was decompressed and m_bytes is the now-decompressed
213   // text.
214   // Returns 'false' if unable to decompress or if the checksum was invalid.
215   //
216   // NB: Once the packet has been decompressed, checksum cannot be computed
217   // based
218   // on m_bytes.  The checksum was for the compressed packet.
219   bool DecompressPacket();
220 
221   Status StartListenThread(const char *hostname = "127.0.0.1",
222                            uint16_t port = 0);
223 
224   bool JoinListenThread();
225 
226   static lldb::thread_result_t ListenThread(lldb::thread_arg_t arg);
227 
228   // GDB-Remote read thread
229   //  . this thread constantly tries to read from the communication
230   //    class and stores all packets received in a queue.  The usual
231   //    threads read requests simply pop packets off the queue in the
232   //    usual order.
233   //    This setup allows us to intercept and handle async packets, such
234   //    as the notify packet.
235 
236   // This method is defined as part of communication.h
237   // when the read thread gets any bytes it will pass them on to this function
238   void AppendBytesToCache(const uint8_t *bytes, size_t len, bool broadcast,
239                           lldb::ConnectionStatus status) override;
240 
241 private:
242   std::queue<StringExtractorGDBRemote> m_packet_queue; // The packet queue
243   std::mutex m_packet_queue_mutex; // Mutex for accessing queue
244   std::condition_variable
245       m_condition_queue_not_empty; // Condition variable to wait for packets
246 
247   HostThread m_listen_thread;
248   std::string m_listen_url;
249 
250 #if defined(HAVE_LIBCOMPRESSION)
251   CompressionType m_decompression_scratch_type = CompressionType::None;
252   void *m_decompression_scratch = nullptr;
253 #endif
254 
255   GDBRemoteCommunication(const GDBRemoteCommunication &) = delete;
256   const GDBRemoteCommunication &
257   operator=(const GDBRemoteCommunication &) = delete;
258 };
259 
260 } // namespace process_gdb_remote
261 } // namespace lldb_private
262 
263 namespace llvm {
264 template <>
265 struct format_provider<
266     lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketResult> {
267   static void format(const lldb_private::process_gdb_remote::
268                          GDBRemoteCommunication::PacketResult &state,
269                      raw_ostream &Stream, StringRef Style);
270 };
271 } // namespace llvm
272 
273 #endif // LLDB_SOURCE_PLUGINS_PROCESS_GDB_REMOTE_GDBREMOTECOMMUNICATION_H
274