1 //===-- GDBRemoteCommunication.cpp ----------------------------------------===//
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 #include "GDBRemoteCommunication.h"
10 
11 #include <climits>
12 #include <cstring>
13 #include <future>
14 #include <sys/stat.h>
15 
16 #include "lldb/Core/StreamFile.h"
17 #include "lldb/Host/Config.h"
18 #include "lldb/Host/ConnectionFileDescriptor.h"
19 #include "lldb/Host/FileSystem.h"
20 #include "lldb/Host/Host.h"
21 #include "lldb/Host/HostInfo.h"
22 #include "lldb/Host/Pipe.h"
23 #include "lldb/Host/ProcessLaunchInfo.h"
24 #include "lldb/Host/Socket.h"
25 #include "lldb/Host/ThreadLauncher.h"
26 #include "lldb/Host/common/TCPSocket.h"
27 #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
28 #include "lldb/Target/Platform.h"
29 #include "lldb/Utility/Event.h"
30 #include "lldb/Utility/FileSpec.h"
31 #include "lldb/Utility/Log.h"
32 #include "lldb/Utility/RegularExpression.h"
33 #include "lldb/Utility/StreamString.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/Support/ScopedPrinter.h"
36 
37 #include "ProcessGDBRemoteLog.h"
38 
39 #if defined(__APPLE__)
40 #define DEBUGSERVER_BASENAME "debugserver"
41 #elif defined(_WIN32)
42 #define DEBUGSERVER_BASENAME "lldb-server.exe"
43 #else
44 #define DEBUGSERVER_BASENAME "lldb-server"
45 #endif
46 
47 #if defined(HAVE_LIBCOMPRESSION)
48 #include <compression.h>
49 #endif
50 
51 #if LLVM_ENABLE_ZLIB
52 #include <zlib.h>
53 #endif
54 
55 using namespace lldb;
56 using namespace lldb_private;
57 using namespace lldb_private::process_gdb_remote;
58 
59 // GDBRemoteCommunication constructor
60 GDBRemoteCommunication::GDBRemoteCommunication()
61     : Communication(),
62 #ifdef LLDB_CONFIGURATION_DEBUG
63       m_packet_timeout(1000),
64 #else
65       m_packet_timeout(1),
66 #endif
67       m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
68       m_send_acks(true), m_is_platform(false),
69       m_compression_type(CompressionType::None), m_listen_url() {
70 }
71 
72 // Destructor
73 GDBRemoteCommunication::~GDBRemoteCommunication() {
74   if (IsConnected()) {
75     Disconnect();
76   }
77 
78 #if defined(HAVE_LIBCOMPRESSION)
79   if (m_decompression_scratch)
80     free (m_decompression_scratch);
81 #endif
82 }
83 
84 char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
85   int checksum = 0;
86 
87   for (char c : payload)
88     checksum += c;
89 
90   return checksum & 255;
91 }
92 
93 size_t GDBRemoteCommunication::SendAck() {
94   Log *log = GetLog(GDBRLog::Packets);
95   ConnectionStatus status = eConnectionStatusSuccess;
96   char ch = '+';
97   const size_t bytes_written = WriteAll(&ch, 1, status, nullptr);
98   LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
99   m_history.AddPacket(ch, GDBRemotePacket::ePacketTypeSend, bytes_written);
100   return bytes_written;
101 }
102 
103 size_t GDBRemoteCommunication::SendNack() {
104   Log *log = GetLog(GDBRLog::Packets);
105   ConnectionStatus status = eConnectionStatusSuccess;
106   char ch = '-';
107   const size_t bytes_written = WriteAll(&ch, 1, status, nullptr);
108   LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
109   m_history.AddPacket(ch, GDBRemotePacket::ePacketTypeSend, bytes_written);
110   return bytes_written;
111 }
112 
113 GDBRemoteCommunication::PacketResult
114 GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
115   StreamString packet(0, 4, eByteOrderBig);
116   packet.PutChar('$');
117   packet.Write(payload.data(), payload.size());
118   packet.PutChar('#');
119   packet.PutHex8(CalculcateChecksum(payload));
120   std::string packet_str = std::string(packet.GetString());
121 
122   return SendRawPacketNoLock(packet_str);
123 }
124 
125 GDBRemoteCommunication::PacketResult
126 GDBRemoteCommunication::SendNotificationPacketNoLock(
127     llvm::StringRef notify_type, std::deque<std::string> &queue,
128     llvm::StringRef payload) {
129   PacketResult ret = PacketResult::Success;
130 
131   // If there are no notification in the queue, send the notification
132   // packet.
133   if (queue.empty()) {
134     StreamString packet(0, 4, eByteOrderBig);
135     packet.PutChar('%');
136     packet.Write(notify_type.data(), notify_type.size());
137     packet.PutChar(':');
138     packet.Write(payload.data(), payload.size());
139     packet.PutChar('#');
140     packet.PutHex8(CalculcateChecksum(payload));
141     ret = SendRawPacketNoLock(packet.GetString(), true);
142   }
143 
144   queue.push_back(payload.str());
145   return ret;
146 }
147 
148 GDBRemoteCommunication::PacketResult
149 GDBRemoteCommunication::SendRawPacketNoLock(llvm::StringRef packet,
150                                             bool skip_ack) {
151   if (IsConnected()) {
152     Log *log = GetLog(GDBRLog::Packets);
153     ConnectionStatus status = eConnectionStatusSuccess;
154     const char *packet_data = packet.data();
155     const size_t packet_length = packet.size();
156     size_t bytes_written = WriteAll(packet_data, packet_length, status, nullptr);
157     if (log) {
158       size_t binary_start_offset = 0;
159       if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
160           0) {
161         const char *first_comma = strchr(packet_data, ',');
162         if (first_comma) {
163           const char *second_comma = strchr(first_comma + 1, ',');
164           if (second_comma)
165             binary_start_offset = second_comma - packet_data + 1;
166         }
167       }
168 
169       // If logging was just enabled and we have history, then dump out what we
170       // have to the log so we get the historical context. The Dump() call that
171       // logs all of the packet will set a boolean so that we don't dump this
172       // more than once
173       if (!m_history.DidDumpToLog())
174         m_history.Dump(log);
175 
176       if (binary_start_offset) {
177         StreamString strm;
178         // Print non binary data header
179         strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
180                     (int)binary_start_offset, packet_data);
181         const uint8_t *p;
182         // Print binary data exactly as sent
183         for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
184              ++p)
185           strm.Printf("\\x%2.2x", *p);
186         // Print the checksum
187         strm.Printf("%*s", (int)3, p);
188         log->PutString(strm.GetString());
189       } else
190         LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %.*s",
191                   (uint64_t)bytes_written, (int)packet_length, packet_data);
192     }
193 
194     m_history.AddPacket(packet.str(), packet_length,
195                         GDBRemotePacket::ePacketTypeSend, bytes_written);
196 
197     if (bytes_written == packet_length) {
198       if (!skip_ack && GetSendAcks())
199         return GetAck();
200       else
201         return PacketResult::Success;
202     } else {
203       LLDB_LOGF(log, "error: failed to send packet: %.*s", (int)packet_length,
204                 packet_data);
205     }
206   }
207   return PacketResult::ErrorSendFailed;
208 }
209 
210 GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
211   StringExtractorGDBRemote packet;
212   PacketResult result = WaitForPacketNoLock(packet, GetPacketTimeout(), false);
213   if (result == PacketResult::Success) {
214     if (packet.GetResponseType() ==
215         StringExtractorGDBRemote::ResponseType::eAck)
216       return PacketResult::Success;
217     else
218       return PacketResult::ErrorSendAck;
219   }
220   return result;
221 }
222 
223 GDBRemoteCommunication::PacketResult
224 GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
225                                    Timeout<std::micro> timeout,
226                                    bool sync_on_timeout) {
227   using ResponseType = StringExtractorGDBRemote::ResponseType;
228 
229   Log *log = GetLog(GDBRLog::Packets);
230   for (;;) {
231     PacketResult result =
232         WaitForPacketNoLock(response, timeout, sync_on_timeout);
233     if (result != PacketResult::Success ||
234         (response.GetResponseType() != ResponseType::eAck &&
235          response.GetResponseType() != ResponseType::eNack))
236       return result;
237     LLDB_LOG(log, "discarding spurious `{0}` packet", response.GetStringRef());
238   }
239 }
240 
241 GDBRemoteCommunication::PacketResult
242 GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
243                                             Timeout<std::micro> timeout,
244                                             bool sync_on_timeout) {
245   uint8_t buffer[8192];
246   Status error;
247 
248   Log *log = GetLog(GDBRLog::Packets);
249 
250   // Check for a packet from our cache first without trying any reading...
251   if (CheckForPacket(nullptr, 0, packet) != PacketType::Invalid)
252     return PacketResult::Success;
253 
254   bool timed_out = false;
255   bool disconnected = false;
256   while (IsConnected() && !timed_out) {
257     lldb::ConnectionStatus status = eConnectionStatusNoConnection;
258     size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
259 
260     LLDB_LOGV(log,
261               "Read(buffer, sizeof(buffer), timeout = {0}, "
262               "status = {1}, error = {2}) => bytes_read = {3}",
263               timeout, Communication::ConnectionStatusAsString(status), error,
264               bytes_read);
265 
266     if (bytes_read > 0) {
267       if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
268         return PacketResult::Success;
269     } else {
270       switch (status) {
271       case eConnectionStatusTimedOut:
272       case eConnectionStatusInterrupted:
273         if (sync_on_timeout) {
274           /// Sync the remote GDB server and make sure we get a response that
275           /// corresponds to what we send.
276           ///
277           /// Sends a "qEcho" packet and makes sure it gets the exact packet
278           /// echoed back. If the qEcho packet isn't supported, we send a qC
279           /// packet and make sure we get a valid thread ID back. We use the
280           /// "qC" packet since its response if very unique: is responds with
281           /// "QC%x" where %x is the thread ID of the current thread. This
282           /// makes the response unique enough from other packet responses to
283           /// ensure we are back on track.
284           ///
285           /// This packet is needed after we time out sending a packet so we
286           /// can ensure that we are getting the response for the packet we
287           /// are sending. There are no sequence IDs in the GDB remote
288           /// protocol (there used to be, but they are not supported anymore)
289           /// so if you timeout sending packet "abc", you might then send
290           /// packet "cde" and get the response for the previous "abc" packet.
291           /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
292           /// many responses for packets can look like responses for other
293           /// packets. So if we timeout, we need to ensure that we can get
294           /// back on track. If we can't get back on track, we must
295           /// disconnect.
296           bool sync_success = false;
297           bool got_actual_response = false;
298           // We timed out, we need to sync back up with the
299           char echo_packet[32];
300           int echo_packet_len = 0;
301           RegularExpression response_regex;
302 
303           if (m_supports_qEcho == eLazyBoolYes) {
304             echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
305                                          "qEcho:%u", ++m_echo_number);
306             std::string regex_str = "^";
307             regex_str += echo_packet;
308             regex_str += "$";
309             response_regex = RegularExpression(regex_str);
310           } else {
311             echo_packet_len =
312                 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
313             response_regex =
314                 RegularExpression(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
315           }
316 
317           PacketResult echo_packet_result =
318               SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
319           if (echo_packet_result == PacketResult::Success) {
320             const uint32_t max_retries = 3;
321             uint32_t successful_responses = 0;
322             for (uint32_t i = 0; i < max_retries; ++i) {
323               StringExtractorGDBRemote echo_response;
324               echo_packet_result =
325                   WaitForPacketNoLock(echo_response, timeout, false);
326               if (echo_packet_result == PacketResult::Success) {
327                 ++successful_responses;
328                 if (response_regex.Execute(echo_response.GetStringRef())) {
329                   sync_success = true;
330                   break;
331                 } else if (successful_responses == 1) {
332                   // We got something else back as the first successful
333                   // response, it probably is the  response to the packet we
334                   // actually wanted, so copy it over if this is the first
335                   // success and continue to try to get the qEcho response
336                   packet = echo_response;
337                   got_actual_response = true;
338                 }
339               } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
340                 continue; // Packet timed out, continue waiting for a response
341               else
342                 break; // Something else went wrong getting the packet back, we
343                        // failed and are done trying
344             }
345           }
346 
347           // We weren't able to sync back up with the server, we must abort
348           // otherwise all responses might not be from the right packets...
349           if (sync_success) {
350             // We timed out, but were able to recover
351             if (got_actual_response) {
352               // We initially timed out, but we did get a response that came in
353               // before the successful reply to our qEcho packet, so lets say
354               // everything is fine...
355               return PacketResult::Success;
356             }
357           } else {
358             disconnected = true;
359             Disconnect();
360           }
361         }
362         timed_out = true;
363         break;
364       case eConnectionStatusSuccess:
365         // printf ("status = success but error = %s\n",
366         // error.AsCString("<invalid>"));
367         break;
368 
369       case eConnectionStatusEndOfFile:
370       case eConnectionStatusNoConnection:
371       case eConnectionStatusLostConnection:
372       case eConnectionStatusError:
373         disconnected = true;
374         Disconnect();
375         break;
376       }
377     }
378   }
379   packet.Clear();
380   if (disconnected)
381     return PacketResult::ErrorDisconnected;
382   if (timed_out)
383     return PacketResult::ErrorReplyTimeout;
384   else
385     return PacketResult::ErrorReplyFailed;
386 }
387 
388 bool GDBRemoteCommunication::DecompressPacket() {
389   Log *log = GetLog(GDBRLog::Packets);
390 
391   if (!CompressionIsEnabled())
392     return true;
393 
394   size_t pkt_size = m_bytes.size();
395 
396   // Smallest possible compressed packet is $N#00 - an uncompressed empty
397   // reply, most commonly indicating an unsupported packet.  Anything less than
398   // 5 characters, it's definitely not a compressed packet.
399   if (pkt_size < 5)
400     return true;
401 
402   if (m_bytes[0] != '$' && m_bytes[0] != '%')
403     return true;
404   if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
405     return true;
406 
407   size_t hash_mark_idx = m_bytes.find('#');
408   if (hash_mark_idx == std::string::npos)
409     return true;
410   if (hash_mark_idx + 2 >= m_bytes.size())
411     return true;
412 
413   if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
414       !::isxdigit(m_bytes[hash_mark_idx + 2]))
415     return true;
416 
417   size_t content_length =
418       pkt_size -
419       5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
420   size_t content_start = 2; // The first character of the
421                             // compressed/not-compressed text of the packet
422   size_t checksum_idx =
423       hash_mark_idx +
424       1; // The first character of the two hex checksum characters
425 
426   // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
427   // multiple packets. size_of_first_packet is the size of the initial packet
428   // which we'll replace with the decompressed version of, leaving the rest of
429   // m_bytes unmodified.
430   size_t size_of_first_packet = hash_mark_idx + 3;
431 
432   // Compressed packets ("$C") start with a base10 number which is the size of
433   // the uncompressed payload, then a : and then the compressed data.  e.g.
434   // $C1024:<binary>#00 Update content_start and content_length to only include
435   // the <binary> part of the packet.
436 
437   uint64_t decompressed_bufsize = ULONG_MAX;
438   if (m_bytes[1] == 'C') {
439     size_t i = content_start;
440     while (i < hash_mark_idx && isdigit(m_bytes[i]))
441       i++;
442     if (i < hash_mark_idx && m_bytes[i] == ':') {
443       i++;
444       content_start = i;
445       content_length = hash_mark_idx - content_start;
446       std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
447       errno = 0;
448       decompressed_bufsize = ::strtoul(bufsize_str.c_str(), nullptr, 10);
449       if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
450         m_bytes.erase(0, size_of_first_packet);
451         return false;
452       }
453     }
454   }
455 
456   if (GetSendAcks()) {
457     char packet_checksum_cstr[3];
458     packet_checksum_cstr[0] = m_bytes[checksum_idx];
459     packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
460     packet_checksum_cstr[2] = '\0';
461     long packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
462 
463     long actual_checksum = CalculcateChecksum(
464         llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
465     bool success = packet_checksum == actual_checksum;
466     if (!success) {
467       LLDB_LOGF(log,
468                 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
469                 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
470                 (uint8_t)actual_checksum);
471     }
472     // Send the ack or nack if needed
473     if (!success) {
474       SendNack();
475       m_bytes.erase(0, size_of_first_packet);
476       return false;
477     } else {
478       SendAck();
479     }
480   }
481 
482   if (m_bytes[1] == 'N') {
483     // This packet was not compressed -- delete the 'N' character at the start
484     // and the packet may be processed as-is.
485     m_bytes.erase(1, 1);
486     return true;
487   }
488 
489   // Reverse the gdb-remote binary escaping that was done to the compressed
490   // text to guard characters like '$', '#', '}', etc.
491   std::vector<uint8_t> unescaped_content;
492   unescaped_content.reserve(content_length);
493   size_t i = content_start;
494   while (i < hash_mark_idx) {
495     if (m_bytes[i] == '}') {
496       i++;
497       unescaped_content.push_back(m_bytes[i] ^ 0x20);
498     } else {
499       unescaped_content.push_back(m_bytes[i]);
500     }
501     i++;
502   }
503 
504   uint8_t *decompressed_buffer = nullptr;
505   size_t decompressed_bytes = 0;
506 
507   if (decompressed_bufsize != ULONG_MAX) {
508     decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
509     if (decompressed_buffer == nullptr) {
510       m_bytes.erase(0, size_of_first_packet);
511       return false;
512     }
513   }
514 
515 #if defined(HAVE_LIBCOMPRESSION)
516   if (m_compression_type == CompressionType::ZlibDeflate ||
517       m_compression_type == CompressionType::LZFSE ||
518       m_compression_type == CompressionType::LZ4 ||
519       m_compression_type == CompressionType::LZMA) {
520     compression_algorithm compression_type;
521     if (m_compression_type == CompressionType::LZFSE)
522       compression_type = COMPRESSION_LZFSE;
523     else if (m_compression_type == CompressionType::ZlibDeflate)
524       compression_type = COMPRESSION_ZLIB;
525     else if (m_compression_type == CompressionType::LZ4)
526       compression_type = COMPRESSION_LZ4_RAW;
527     else if (m_compression_type == CompressionType::LZMA)
528       compression_type = COMPRESSION_LZMA;
529 
530     if (m_decompression_scratch_type != m_compression_type) {
531       if (m_decompression_scratch) {
532         free (m_decompression_scratch);
533         m_decompression_scratch = nullptr;
534       }
535       size_t scratchbuf_size = 0;
536       if (m_compression_type == CompressionType::LZFSE)
537         scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
538       else if (m_compression_type == CompressionType::LZ4)
539         scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
540       else if (m_compression_type == CompressionType::ZlibDeflate)
541         scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
542       else if (m_compression_type == CompressionType::LZMA)
543         scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZMA);
544       else if (m_compression_type == CompressionType::LZFSE)
545         scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
546       if (scratchbuf_size > 0) {
547         m_decompression_scratch = (void*) malloc (scratchbuf_size);
548         m_decompression_scratch_type = m_compression_type;
549       }
550     }
551 
552     if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
553       decompressed_bytes = compression_decode_buffer(
554           decompressed_buffer, decompressed_bufsize,
555           (uint8_t *)unescaped_content.data(), unescaped_content.size(),
556           m_decompression_scratch, compression_type);
557     }
558   }
559 #endif
560 
561 #if LLVM_ENABLE_ZLIB
562   if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
563       decompressed_buffer != nullptr &&
564       m_compression_type == CompressionType::ZlibDeflate) {
565     z_stream stream;
566     memset(&stream, 0, sizeof(z_stream));
567     stream.next_in = (Bytef *)unescaped_content.data();
568     stream.avail_in = (uInt)unescaped_content.size();
569     stream.total_in = 0;
570     stream.next_out = (Bytef *)decompressed_buffer;
571     stream.avail_out = decompressed_bufsize;
572     stream.total_out = 0;
573     stream.zalloc = Z_NULL;
574     stream.zfree = Z_NULL;
575     stream.opaque = Z_NULL;
576 
577     if (inflateInit2(&stream, -15) == Z_OK) {
578       int status = inflate(&stream, Z_NO_FLUSH);
579       inflateEnd(&stream);
580       if (status == Z_STREAM_END) {
581         decompressed_bytes = stream.total_out;
582       }
583     }
584   }
585 #endif
586 
587   if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
588     if (decompressed_buffer)
589       free(decompressed_buffer);
590     m_bytes.erase(0, size_of_first_packet);
591     return false;
592   }
593 
594   std::string new_packet;
595   new_packet.reserve(decompressed_bytes + 6);
596   new_packet.push_back(m_bytes[0]);
597   new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
598   new_packet.push_back('#');
599   if (GetSendAcks()) {
600     uint8_t decompressed_checksum = CalculcateChecksum(
601         llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
602     char decompressed_checksum_str[3];
603     snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
604     new_packet.append(decompressed_checksum_str);
605   } else {
606     new_packet.push_back('0');
607     new_packet.push_back('0');
608   }
609 
610   m_bytes.replace(0, size_of_first_packet, new_packet.data(),
611                   new_packet.size());
612 
613   free(decompressed_buffer);
614   return true;
615 }
616 
617 GDBRemoteCommunication::PacketType
618 GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
619                                        StringExtractorGDBRemote &packet) {
620   // Put the packet data into the buffer in a thread safe fashion
621   std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
622 
623   Log *log = GetLog(GDBRLog::Packets);
624 
625   if (src && src_len > 0) {
626     if (log && log->GetVerbose()) {
627       StreamString s;
628       LLDB_LOGF(log, "GDBRemoteCommunication::%s adding %u bytes: %.*s",
629                 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
630     }
631     m_bytes.append((const char *)src, src_len);
632   }
633 
634   bool isNotifyPacket = false;
635 
636   // Parse up the packets into gdb remote packets
637   if (!m_bytes.empty()) {
638     // end_idx must be one past the last valid packet byte. Start it off with
639     // an invalid value that is the same as the current index.
640     size_t content_start = 0;
641     size_t content_length = 0;
642     size_t total_length = 0;
643     size_t checksum_idx = std::string::npos;
644 
645     // Size of packet before it is decompressed, for logging purposes
646     size_t original_packet_size = m_bytes.size();
647     if (CompressionIsEnabled()) {
648       if (!DecompressPacket()) {
649         packet.Clear();
650         return GDBRemoteCommunication::PacketType::Standard;
651       }
652     }
653 
654     switch (m_bytes[0]) {
655     case '+':                            // Look for ack
656     case '-':                            // Look for cancel
657     case '\x03':                         // ^C to halt target
658       content_length = total_length = 1; // The command is one byte long...
659       break;
660 
661     case '%': // Async notify packet
662       isNotifyPacket = true;
663       [[fallthrough]];
664 
665     case '$':
666       // Look for a standard gdb packet?
667       {
668         size_t hash_pos = m_bytes.find('#');
669         if (hash_pos != std::string::npos) {
670           if (hash_pos + 2 < m_bytes.size()) {
671             checksum_idx = hash_pos + 1;
672             // Skip the dollar sign
673             content_start = 1;
674             // Don't include the # in the content or the $ in the content
675             // length
676             content_length = hash_pos - 1;
677 
678             total_length =
679                 hash_pos + 3; // Skip the # and the two hex checksum bytes
680           } else {
681             // Checksum bytes aren't all here yet
682             content_length = std::string::npos;
683           }
684         }
685       }
686       break;
687 
688     default: {
689       // We have an unexpected byte and we need to flush all bad data that is
690       // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
691       // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
692       // header) or of course, the end of the data in m_bytes...
693       const size_t bytes_len = m_bytes.size();
694       bool done = false;
695       uint32_t idx;
696       for (idx = 1; !done && idx < bytes_len; ++idx) {
697         switch (m_bytes[idx]) {
698         case '+':
699         case '-':
700         case '\x03':
701         case '%':
702         case '$':
703           done = true;
704           break;
705 
706         default:
707           break;
708         }
709       }
710       LLDB_LOGF(log, "GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
711                 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
712       m_bytes.erase(0, idx - 1);
713     } break;
714     }
715 
716     if (content_length == std::string::npos) {
717       packet.Clear();
718       return GDBRemoteCommunication::PacketType::Invalid;
719     } else if (total_length > 0) {
720 
721       // We have a valid packet...
722       assert(content_length <= m_bytes.size());
723       assert(total_length <= m_bytes.size());
724       assert(content_length <= total_length);
725       size_t content_end = content_start + content_length;
726 
727       bool success = true;
728       if (log) {
729         // If logging was just enabled and we have history, then dump out what
730         // we have to the log so we get the historical context. The Dump() call
731         // that logs all of the packet will set a boolean so that we don't dump
732         // this more than once
733         if (!m_history.DidDumpToLog())
734           m_history.Dump(log);
735 
736         bool binary = false;
737         // Only detect binary for packets that start with a '$' and have a
738         // '#CC' checksum
739         if (m_bytes[0] == '$' && total_length > 4) {
740           for (size_t i = 0; !binary && i < total_length; ++i) {
741             unsigned char c = m_bytes[i];
742             if (!llvm::isPrint(c) && !llvm::isSpace(c)) {
743               binary = true;
744             }
745           }
746         }
747         if (binary) {
748           StreamString strm;
749           // Packet header...
750           if (CompressionIsEnabled())
751             strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
752                         (uint64_t)original_packet_size, (uint64_t)total_length,
753                         m_bytes[0]);
754           else
755             strm.Printf("<%4" PRIu64 "> read packet: %c",
756                         (uint64_t)total_length, m_bytes[0]);
757           for (size_t i = content_start; i < content_end; ++i) {
758             // Remove binary escaped bytes when displaying the packet...
759             const char ch = m_bytes[i];
760             if (ch == 0x7d) {
761               // 0x7d is the escape character.  The next character is to be
762               // XOR'd with 0x20.
763               const char escapee = m_bytes[++i] ^ 0x20;
764               strm.Printf("%2.2x", escapee);
765             } else {
766               strm.Printf("%2.2x", (uint8_t)ch);
767             }
768           }
769           // Packet footer...
770           strm.Printf("%c%c%c", m_bytes[total_length - 3],
771                       m_bytes[total_length - 2], m_bytes[total_length - 1]);
772           log->PutString(strm.GetString());
773         } else {
774           if (CompressionIsEnabled())
775             LLDB_LOGF(log, "<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
776                       (uint64_t)original_packet_size, (uint64_t)total_length,
777                       (int)(total_length), m_bytes.c_str());
778           else
779             LLDB_LOGF(log, "<%4" PRIu64 "> read packet: %.*s",
780                       (uint64_t)total_length, (int)(total_length),
781                       m_bytes.c_str());
782         }
783       }
784 
785       m_history.AddPacket(m_bytes, total_length,
786                           GDBRemotePacket::ePacketTypeRecv, total_length);
787 
788       // Copy the packet from m_bytes to packet_str expanding the run-length
789       // encoding in the process.
790       std ::string packet_str =
791           ExpandRLE(m_bytes.substr(content_start, content_end - content_start));
792       packet = StringExtractorGDBRemote(packet_str);
793 
794       if (m_bytes[0] == '$' || m_bytes[0] == '%') {
795         assert(checksum_idx < m_bytes.size());
796         if (::isxdigit(m_bytes[checksum_idx + 0]) ||
797             ::isxdigit(m_bytes[checksum_idx + 1])) {
798           if (GetSendAcks()) {
799             const char *packet_checksum_cstr = &m_bytes[checksum_idx];
800             char packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
801             char actual_checksum = CalculcateChecksum(
802                 llvm::StringRef(m_bytes).slice(content_start, content_end));
803             success = packet_checksum == actual_checksum;
804             if (!success) {
805               LLDB_LOGF(log,
806                         "error: checksum mismatch: %.*s expected 0x%2.2x, "
807                         "got 0x%2.2x",
808                         (int)(total_length), m_bytes.c_str(),
809                         (uint8_t)packet_checksum, (uint8_t)actual_checksum);
810             }
811             // Send the ack or nack if needed
812             if (!success)
813               SendNack();
814             else
815               SendAck();
816           }
817         } else {
818           success = false;
819           LLDB_LOGF(log, "error: invalid checksum in packet: '%s'\n",
820                     m_bytes.c_str());
821         }
822       }
823 
824       m_bytes.erase(0, total_length);
825       packet.SetFilePos(0);
826 
827       if (isNotifyPacket)
828         return GDBRemoteCommunication::PacketType::Notify;
829       else
830         return GDBRemoteCommunication::PacketType::Standard;
831     }
832   }
833   packet.Clear();
834   return GDBRemoteCommunication::PacketType::Invalid;
835 }
836 
837 Status GDBRemoteCommunication::StartListenThread(const char *hostname,
838                                                  uint16_t port) {
839   if (m_listen_thread.IsJoinable())
840     return Status("listen thread already running");
841 
842   char listen_url[512];
843   if (hostname && hostname[0])
844     snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
845   else
846     snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
847   m_listen_url = listen_url;
848   SetConnection(std::make_unique<ConnectionFileDescriptor>());
849   llvm::Expected<HostThread> listen_thread = ThreadLauncher::LaunchThread(
850       listen_url, [this] { return GDBRemoteCommunication::ListenThread(); });
851   if (!listen_thread)
852     return Status(listen_thread.takeError());
853   m_listen_thread = *listen_thread;
854 
855   return Status();
856 }
857 
858 bool GDBRemoteCommunication::JoinListenThread() {
859   if (m_listen_thread.IsJoinable())
860     m_listen_thread.Join(nullptr);
861   return true;
862 }
863 
864 lldb::thread_result_t GDBRemoteCommunication::ListenThread() {
865   Status error;
866   ConnectionFileDescriptor *connection =
867       (ConnectionFileDescriptor *)GetConnection();
868 
869   if (connection) {
870     // Do the listen on another thread so we can continue on...
871     if (connection->Connect(
872             m_listen_url.c_str(),
873             [this](llvm::StringRef port_str) {
874               uint16_t port = 0;
875               llvm::to_integer(port_str, port, 10);
876               m_port_promise.set_value(port);
877             },
878             &error) != eConnectionStatusSuccess)
879       SetConnection(nullptr);
880   }
881   return {};
882 }
883 
884 Status GDBRemoteCommunication::StartDebugserverProcess(
885     const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
886     uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
887   Log *log = GetLog(GDBRLog::Process);
888   LLDB_LOGF(log, "GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
889             __FUNCTION__, url ? url : "<empty>", port ? *port : uint16_t(0));
890 
891   Status error;
892   // If we locate debugserver, keep that located version around
893   static FileSpec g_debugserver_file_spec;
894 
895   char debugserver_path[PATH_MAX];
896   FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
897 
898   Environment host_env = Host::GetEnvironment();
899 
900   // Always check to see if we have an environment override for the path to the
901   // debugserver to use and use it if we do.
902   std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
903   if (!env_debugserver_path.empty()) {
904     debugserver_file_spec.SetFile(env_debugserver_path,
905                                   FileSpec::Style::native);
906     LLDB_LOGF(log,
907               "GDBRemoteCommunication::%s() gdb-remote stub exe path set "
908               "from environment variable: %s",
909               __FUNCTION__, env_debugserver_path.c_str());
910   } else
911     debugserver_file_spec = g_debugserver_file_spec;
912   bool debugserver_exists =
913       FileSystem::Instance().Exists(debugserver_file_spec);
914   if (!debugserver_exists) {
915     // The debugserver binary is in the LLDB.framework/Resources directory.
916     debugserver_file_spec = HostInfo::GetSupportExeDir();
917     if (debugserver_file_spec) {
918       debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
919       debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
920       if (debugserver_exists) {
921         LLDB_LOGF(log,
922                   "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
923                   __FUNCTION__, debugserver_file_spec.GetPath().c_str());
924 
925         g_debugserver_file_spec = debugserver_file_spec;
926       } else {
927         if (platform)
928           debugserver_file_spec =
929               platform->LocateExecutable(DEBUGSERVER_BASENAME);
930         else
931           debugserver_file_spec.Clear();
932         if (debugserver_file_spec) {
933           // Platform::LocateExecutable() wouldn't return a path if it doesn't
934           // exist
935           debugserver_exists = true;
936         } else {
937           LLDB_LOGF(log,
938                     "GDBRemoteCommunication::%s() could not find "
939                     "gdb-remote stub exe '%s'",
940                     __FUNCTION__, debugserver_file_spec.GetPath().c_str());
941         }
942         // Don't cache the platform specific GDB server binary as it could
943         // change from platform to platform
944         g_debugserver_file_spec.Clear();
945       }
946     }
947   }
948 
949   if (debugserver_exists) {
950     debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
951 
952     Args &debugserver_args = launch_info.GetArguments();
953     debugserver_args.Clear();
954 
955     // Start args with "debugserver /file/path -r --"
956     debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
957 
958 #if !defined(__APPLE__)
959     // First argument to lldb-server must be mode in which to run.
960     debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
961 #endif
962 
963     // If a url is supplied then use it
964     if (url)
965       debugserver_args.AppendArgument(llvm::StringRef(url));
966 
967     if (pass_comm_fd >= 0) {
968       StreamString fd_arg;
969       fd_arg.Printf("--fd=%i", pass_comm_fd);
970       debugserver_args.AppendArgument(fd_arg.GetString());
971       // Send "pass_comm_fd" down to the inferior so it can use it to
972       // communicate back with this process
973       launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
974     }
975 
976     // use native registers, not the GDB registers
977     debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
978 
979     if (launch_info.GetLaunchInSeparateProcessGroup()) {
980       debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
981     }
982 
983     llvm::SmallString<128> named_pipe_path;
984     // socket_pipe is used by debug server to communicate back either
985     // TCP port or domain socket name which it listens on.
986     // The second purpose of the pipe to serve as a synchronization point -
987     // once data is written to the pipe, debug server is up and running.
988     Pipe socket_pipe;
989 
990     // port is null when debug server should listen on domain socket - we're
991     // not interested in port value but rather waiting for debug server to
992     // become available.
993     if (pass_comm_fd == -1) {
994       if (url) {
995 // Create a temporary file to get the stdout/stderr and redirect the output of
996 // the command into this file. We will later read this file if all goes well
997 // and fill the data into "command_output_ptr"
998 #if defined(__APPLE__)
999         // Binding to port zero, we need to figure out what port it ends up
1000         // using using a named pipe...
1001         error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1002                                                  false, named_pipe_path);
1003         if (error.Fail()) {
1004           LLDB_LOGF(log,
1005                     "GDBRemoteCommunication::%s() "
1006                     "named pipe creation failed: %s",
1007                     __FUNCTION__, error.AsCString());
1008           return error;
1009         }
1010         debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
1011         debugserver_args.AppendArgument(named_pipe_path);
1012 #else
1013         // Binding to port zero, we need to figure out what port it ends up
1014         // using using an unnamed pipe...
1015         error = socket_pipe.CreateNew(true);
1016         if (error.Fail()) {
1017           LLDB_LOGF(log,
1018                     "GDBRemoteCommunication::%s() "
1019                     "unnamed pipe creation failed: %s",
1020                     __FUNCTION__, error.AsCString());
1021           return error;
1022         }
1023         pipe_t write = socket_pipe.GetWritePipe();
1024         debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1025         debugserver_args.AppendArgument(llvm::to_string(write));
1026         launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
1027 #endif
1028       } else {
1029         // No host and port given, so lets listen on our end and make the
1030         // debugserver connect to us..
1031         error = StartListenThread("127.0.0.1", 0);
1032         if (error.Fail()) {
1033           LLDB_LOGF(log,
1034                     "GDBRemoteCommunication::%s() unable to start listen "
1035                     "thread: %s",
1036                     __FUNCTION__, error.AsCString());
1037           return error;
1038         }
1039 
1040         // Wait for 10 seconds to resolve the bound port
1041         std::future<uint16_t> port_future = m_port_promise.get_future();
1042         uint16_t port_ = port_future.wait_for(std::chrono::seconds(10)) ==
1043                                  std::future_status::ready
1044                              ? port_future.get()
1045                              : 0;
1046         if (port_ > 0) {
1047           char port_cstr[32];
1048           snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1049           // Send the host and port down that debugserver and specify an option
1050           // so that it connects back to the port we are listening to in this
1051           // process
1052           debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1053           debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
1054           if (port)
1055             *port = port_;
1056         } else {
1057           error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1058           LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s",
1059                     __FUNCTION__, error.AsCString());
1060           return error;
1061         }
1062       }
1063     }
1064     std::string env_debugserver_log_file =
1065         host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
1066     if (!env_debugserver_log_file.empty()) {
1067       debugserver_args.AppendArgument(
1068           llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
1069     }
1070 
1071 #if defined(__APPLE__)
1072     const char *env_debugserver_log_flags =
1073         getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1074     if (env_debugserver_log_flags) {
1075       debugserver_args.AppendArgument(
1076           llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
1077     }
1078 #else
1079     std::string env_debugserver_log_channels =
1080         host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
1081     if (!env_debugserver_log_channels.empty()) {
1082       debugserver_args.AppendArgument(
1083           llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
1084               .str());
1085     }
1086 #endif
1087 
1088     // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1089     // env var doesn't come back.
1090     uint32_t env_var_index = 1;
1091     bool has_env_var;
1092     do {
1093       char env_var_name[64];
1094       snprintf(env_var_name, sizeof(env_var_name),
1095                "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1096       std::string extra_arg = host_env.lookup(env_var_name);
1097       has_env_var = !extra_arg.empty();
1098 
1099       if (has_env_var) {
1100         debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
1101         LLDB_LOGF(log,
1102                   "GDBRemoteCommunication::%s adding env var %s contents "
1103                   "to stub command line (%s)",
1104                   __FUNCTION__, env_var_name, extra_arg.c_str());
1105       }
1106     } while (has_env_var);
1107 
1108     if (inferior_args && inferior_args->GetArgumentCount() > 0) {
1109       debugserver_args.AppendArgument(llvm::StringRef("--"));
1110       debugserver_args.AppendArguments(*inferior_args);
1111     }
1112 
1113     // Copy the current environment to the gdbserver/debugserver instance
1114     launch_info.GetEnvironment() = host_env;
1115 
1116     // Close STDIN, STDOUT and STDERR.
1117     launch_info.AppendCloseFileAction(STDIN_FILENO);
1118     launch_info.AppendCloseFileAction(STDOUT_FILENO);
1119     launch_info.AppendCloseFileAction(STDERR_FILENO);
1120 
1121     // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1122     launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1123     launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1124     launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1125 
1126     if (log) {
1127       StreamString string_stream;
1128       Platform *const platform = nullptr;
1129       launch_info.Dump(string_stream, platform);
1130       LLDB_LOGF(log, "launch info for gdb-remote stub:\n%s",
1131                 string_stream.GetData());
1132     }
1133     error = Host::LaunchProcess(launch_info);
1134 
1135     if (error.Success() &&
1136         (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1137         pass_comm_fd == -1) {
1138       if (named_pipe_path.size() > 0) {
1139         error = socket_pipe.OpenAsReader(named_pipe_path, false);
1140         if (error.Fail())
1141           LLDB_LOGF(log,
1142                     "GDBRemoteCommunication::%s() "
1143                     "failed to open named pipe %s for reading: %s",
1144                     __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1145       }
1146 
1147       if (socket_pipe.CanWrite())
1148         socket_pipe.CloseWriteFileDescriptor();
1149       if (socket_pipe.CanRead()) {
1150         char port_cstr[PATH_MAX] = {0};
1151         port_cstr[0] = '\0';
1152         size_t num_bytes = sizeof(port_cstr);
1153         // Read port from pipe with 10 second timeout.
1154         error = socket_pipe.ReadWithTimeout(
1155             port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1156         if (error.Success() && (port != nullptr)) {
1157           assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
1158           uint16_t child_port = 0;
1159           // FIXME: improve error handling
1160           llvm::to_integer(port_cstr, child_port);
1161           if (*port == 0 || *port == child_port) {
1162             *port = child_port;
1163             LLDB_LOGF(log,
1164                       "GDBRemoteCommunication::%s() "
1165                       "debugserver listens %u port",
1166                       __FUNCTION__, *port);
1167           } else {
1168             LLDB_LOGF(log,
1169                       "GDBRemoteCommunication::%s() "
1170                       "debugserver listening on port "
1171                       "%d but requested port was %d",
1172                       __FUNCTION__, (uint32_t)child_port, (uint32_t)(*port));
1173           }
1174         } else {
1175           LLDB_LOGF(log,
1176                     "GDBRemoteCommunication::%s() "
1177                     "failed to read a port value from pipe %s: %s",
1178                     __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1179         }
1180         socket_pipe.Close();
1181       }
1182 
1183       if (named_pipe_path.size() > 0) {
1184         const auto err = socket_pipe.Delete(named_pipe_path);
1185         if (err.Fail()) {
1186           LLDB_LOGF(log,
1187                     "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1188                     __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
1189         }
1190       }
1191 
1192       // Make sure we actually connect with the debugserver...
1193       JoinListenThread();
1194     }
1195   } else {
1196     error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1197   }
1198 
1199   if (error.Fail()) {
1200     LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1201               error.AsCString());
1202   }
1203 
1204   return error;
1205 }
1206 
1207 void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1208 
1209 llvm::Error
1210 GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1211                                        GDBRemoteCommunication &server) {
1212   const bool child_processes_inherit = false;
1213   const int backlog = 5;
1214   TCPSocket listen_socket(true, child_processes_inherit);
1215   if (llvm::Error error =
1216           listen_socket.Listen("localhost:0", backlog).ToError())
1217     return error;
1218 
1219   Socket *accept_socket = nullptr;
1220   std::future<Status> accept_status = std::async(
1221       std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1222 
1223   llvm::SmallString<32> remote_addr;
1224   llvm::raw_svector_ostream(remote_addr)
1225       << "connect://localhost:" << listen_socket.GetLocalPortNumber();
1226 
1227   std::unique_ptr<ConnectionFileDescriptor> conn_up(
1228       new ConnectionFileDescriptor());
1229   Status status;
1230   if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)
1231     return llvm::createStringError(llvm::inconvertibleErrorCode(),
1232                                    "Unable to connect: %s", status.AsCString());
1233 
1234   client.SetConnection(std::move(conn_up));
1235   if (llvm::Error error = accept_status.get().ToError())
1236     return error;
1237 
1238   server.SetConnection(
1239       std::make_unique<ConnectionFileDescriptor>(accept_socket));
1240   return llvm::Error::success();
1241 }
1242 
1243 GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
1244     GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
1245     : m_gdb_comm(gdb_comm), m_saved_timeout(0), m_timeout_modified(false) {
1246   auto curr_timeout = gdb_comm.GetPacketTimeout();
1247   // Only update the timeout if the timeout is greater than the current
1248   // timeout. If the current timeout is larger, then just use that.
1249   if (curr_timeout < timeout) {
1250     m_timeout_modified = true;
1251     m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1252   }
1253 }
1254 
1255 GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
1256   // Only restore the timeout if we set it in the constructor.
1257   if (m_timeout_modified)
1258     m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1259 }
1260 
1261 void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1262     const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1263     StringRef Style) {
1264   using PacketResult = GDBRemoteCommunication::PacketResult;
1265 
1266   switch (result) {
1267   case PacketResult::Success:
1268     Stream << "Success";
1269     break;
1270   case PacketResult::ErrorSendFailed:
1271     Stream << "ErrorSendFailed";
1272     break;
1273   case PacketResult::ErrorSendAck:
1274     Stream << "ErrorSendAck";
1275     break;
1276   case PacketResult::ErrorReplyFailed:
1277     Stream << "ErrorReplyFailed";
1278     break;
1279   case PacketResult::ErrorReplyTimeout:
1280     Stream << "ErrorReplyTimeout";
1281     break;
1282   case PacketResult::ErrorReplyInvalid:
1283     Stream << "ErrorReplyInvalid";
1284     break;
1285   case PacketResult::ErrorReplyAck:
1286     Stream << "ErrorReplyAck";
1287     break;
1288   case PacketResult::ErrorDisconnected:
1289     Stream << "ErrorDisconnected";
1290     break;
1291   case PacketResult::ErrorNoSequenceLock:
1292     Stream << "ErrorNoSequenceLock";
1293     break;
1294   }
1295 }
1296 
1297 std::string GDBRemoteCommunication::ExpandRLE(std::string packet) {
1298   // Reserve enough byte for the most common case (no RLE used).
1299   std::string decoded;
1300   decoded.reserve(packet.size());
1301   for (std::string::const_iterator c = packet.begin(); c != packet.end(); ++c) {
1302     if (*c == '*') {
1303       // '*' indicates RLE. Next character will give us the repeat count and
1304       // previous character is what is to be repeated.
1305       char char_to_repeat = decoded.back();
1306       // Number of time the previous character is repeated.
1307       int repeat_count = *++c + 3 - ' ';
1308       // We have the char_to_repeat and repeat_count. Now push it in the
1309       // packet.
1310       for (int i = 0; i < repeat_count; ++i)
1311         decoded.push_back(char_to_repeat);
1312     } else if (*c == 0x7d) {
1313       // 0x7d is the escape character.  The next character is to be XOR'd with
1314       // 0x20.
1315       char escapee = *++c ^ 0x20;
1316       decoded.push_back(escapee);
1317     } else {
1318       decoded.push_back(*c);
1319     }
1320   }
1321   return decoded;
1322 }
1323