xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp (revision c1dff7152592f1beee9059ee8e2cb3cc68baea4d)
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/Host/Config.h"
17 #include "lldb/Host/ConnectionFileDescriptor.h"
18 #include "lldb/Host/FileSystem.h"
19 #include "lldb/Host/Host.h"
20 #include "lldb/Host/HostInfo.h"
21 #include "lldb/Host/Pipe.h"
22 #include "lldb/Host/ProcessLaunchInfo.h"
23 #include "lldb/Host/Socket.h"
24 #include "lldb/Host/ThreadLauncher.h"
25 #include "lldb/Host/common/TCPSocket.h"
26 #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
27 #include "lldb/Target/Platform.h"
28 #include "lldb/Utility/Event.h"
29 #include "lldb/Utility/FileSpec.h"
30 #include "lldb/Utility/Log.h"
31 #include "lldb/Utility/RegularExpression.h"
32 #include "lldb/Utility/StreamString.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/Config/llvm-config.h" // for LLVM_ENABLE_ZLIB
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 =
544             compression_decode_scratch_buffer_size(COMPRESSION_LZMA);
545       if (scratchbuf_size > 0) {
546         m_decompression_scratch = (void*) malloc (scratchbuf_size);
547         m_decompression_scratch_type = m_compression_type;
548       }
549     }
550 
551     if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
552       decompressed_bytes = compression_decode_buffer(
553           decompressed_buffer, decompressed_bufsize,
554           (uint8_t *)unescaped_content.data(), unescaped_content.size(),
555           m_decompression_scratch, compression_type);
556     }
557   }
558 #endif
559 
560 #if LLVM_ENABLE_ZLIB
561   if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
562       decompressed_buffer != nullptr &&
563       m_compression_type == CompressionType::ZlibDeflate) {
564     z_stream stream;
565     memset(&stream, 0, sizeof(z_stream));
566     stream.next_in = (Bytef *)unescaped_content.data();
567     stream.avail_in = (uInt)unescaped_content.size();
568     stream.total_in = 0;
569     stream.next_out = (Bytef *)decompressed_buffer;
570     stream.avail_out = decompressed_bufsize;
571     stream.total_out = 0;
572     stream.zalloc = Z_NULL;
573     stream.zfree = Z_NULL;
574     stream.opaque = Z_NULL;
575 
576     if (inflateInit2(&stream, -15) == Z_OK) {
577       int status = inflate(&stream, Z_NO_FLUSH);
578       inflateEnd(&stream);
579       if (status == Z_STREAM_END) {
580         decompressed_bytes = stream.total_out;
581       }
582     }
583   }
584 #endif
585 
586   if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
587     if (decompressed_buffer)
588       free(decompressed_buffer);
589     m_bytes.erase(0, size_of_first_packet);
590     return false;
591   }
592 
593   std::string new_packet;
594   new_packet.reserve(decompressed_bytes + 6);
595   new_packet.push_back(m_bytes[0]);
596   new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
597   new_packet.push_back('#');
598   if (GetSendAcks()) {
599     uint8_t decompressed_checksum = CalculcateChecksum(
600         llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
601     char decompressed_checksum_str[3];
602     snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
603     new_packet.append(decompressed_checksum_str);
604   } else {
605     new_packet.push_back('0');
606     new_packet.push_back('0');
607   }
608 
609   m_bytes.replace(0, size_of_first_packet, new_packet.data(),
610                   new_packet.size());
611 
612   free(decompressed_buffer);
613   return true;
614 }
615 
616 GDBRemoteCommunication::PacketType
617 GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
618                                        StringExtractorGDBRemote &packet) {
619   // Put the packet data into the buffer in a thread safe fashion
620   std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
621 
622   Log *log = GetLog(GDBRLog::Packets);
623 
624   if (src && src_len > 0) {
625     if (log && log->GetVerbose()) {
626       StreamString s;
627       LLDB_LOGF(log, "GDBRemoteCommunication::%s adding %u bytes: %.*s",
628                 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
629     }
630     m_bytes.append((const char *)src, src_len);
631   }
632 
633   bool isNotifyPacket = false;
634 
635   // Parse up the packets into gdb remote packets
636   if (!m_bytes.empty()) {
637     // end_idx must be one past the last valid packet byte. Start it off with
638     // an invalid value that is the same as the current index.
639     size_t content_start = 0;
640     size_t content_length = 0;
641     size_t total_length = 0;
642     size_t checksum_idx = std::string::npos;
643 
644     // Size of packet before it is decompressed, for logging purposes
645     size_t original_packet_size = m_bytes.size();
646     if (CompressionIsEnabled()) {
647       if (!DecompressPacket()) {
648         packet.Clear();
649         return GDBRemoteCommunication::PacketType::Standard;
650       }
651     }
652 
653     switch (m_bytes[0]) {
654     case '+':                            // Look for ack
655     case '-':                            // Look for cancel
656     case '\x03':                         // ^C to halt target
657       content_length = total_length = 1; // The command is one byte long...
658       break;
659 
660     case '%': // Async notify packet
661       isNotifyPacket = true;
662       [[fallthrough]];
663 
664     case '$':
665       // Look for a standard gdb packet?
666       {
667         size_t hash_pos = m_bytes.find('#');
668         if (hash_pos != std::string::npos) {
669           if (hash_pos + 2 < m_bytes.size()) {
670             checksum_idx = hash_pos + 1;
671             // Skip the dollar sign
672             content_start = 1;
673             // Don't include the # in the content or the $ in the content
674             // length
675             content_length = hash_pos - 1;
676 
677             total_length =
678                 hash_pos + 3; // Skip the # and the two hex checksum bytes
679           } else {
680             // Checksum bytes aren't all here yet
681             content_length = std::string::npos;
682           }
683         }
684       }
685       break;
686 
687     default: {
688       // We have an unexpected byte and we need to flush all bad data that is
689       // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
690       // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
691       // header) or of course, the end of the data in m_bytes...
692       const size_t bytes_len = m_bytes.size();
693       bool done = false;
694       uint32_t idx;
695       for (idx = 1; !done && idx < bytes_len; ++idx) {
696         switch (m_bytes[idx]) {
697         case '+':
698         case '-':
699         case '\x03':
700         case '%':
701         case '$':
702           done = true;
703           break;
704 
705         default:
706           break;
707         }
708       }
709       LLDB_LOGF(log, "GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
710                 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
711       m_bytes.erase(0, idx - 1);
712     } break;
713     }
714 
715     if (content_length == std::string::npos) {
716       packet.Clear();
717       return GDBRemoteCommunication::PacketType::Invalid;
718     } else if (total_length > 0) {
719 
720       // We have a valid packet...
721       assert(content_length <= m_bytes.size());
722       assert(total_length <= m_bytes.size());
723       assert(content_length <= total_length);
724       size_t content_end = content_start + content_length;
725 
726       bool success = true;
727       if (log) {
728         // If logging was just enabled and we have history, then dump out what
729         // we have to the log so we get the historical context. The Dump() call
730         // that logs all of the packet will set a boolean so that we don't dump
731         // this more than once
732         if (!m_history.DidDumpToLog())
733           m_history.Dump(log);
734 
735         bool binary = false;
736         // Only detect binary for packets that start with a '$' and have a
737         // '#CC' checksum
738         if (m_bytes[0] == '$' && total_length > 4) {
739           for (size_t i = 0; !binary && i < total_length; ++i) {
740             unsigned char c = m_bytes[i];
741             if (!llvm::isPrint(c) && !llvm::isSpace(c)) {
742               binary = true;
743             }
744           }
745         }
746         if (binary) {
747           StreamString strm;
748           // Packet header...
749           if (CompressionIsEnabled())
750             strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
751                         (uint64_t)original_packet_size, (uint64_t)total_length,
752                         m_bytes[0]);
753           else
754             strm.Printf("<%4" PRIu64 "> read packet: %c",
755                         (uint64_t)total_length, m_bytes[0]);
756           for (size_t i = content_start; i < content_end; ++i) {
757             // Remove binary escaped bytes when displaying the packet...
758             const char ch = m_bytes[i];
759             if (ch == 0x7d) {
760               // 0x7d is the escape character.  The next character is to be
761               // XOR'd with 0x20.
762               const char escapee = m_bytes[++i] ^ 0x20;
763               strm.Printf("%2.2x", escapee);
764             } else {
765               strm.Printf("%2.2x", (uint8_t)ch);
766             }
767           }
768           // Packet footer...
769           strm.Printf("%c%c%c", m_bytes[total_length - 3],
770                       m_bytes[total_length - 2], m_bytes[total_length - 1]);
771           log->PutString(strm.GetString());
772         } else {
773           if (CompressionIsEnabled())
774             LLDB_LOGF(log, "<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
775                       (uint64_t)original_packet_size, (uint64_t)total_length,
776                       (int)(total_length), m_bytes.c_str());
777           else
778             LLDB_LOGF(log, "<%4" PRIu64 "> read packet: %.*s",
779                       (uint64_t)total_length, (int)(total_length),
780                       m_bytes.c_str());
781         }
782       }
783 
784       m_history.AddPacket(m_bytes, total_length,
785                           GDBRemotePacket::ePacketTypeRecv, total_length);
786 
787       // Copy the packet from m_bytes to packet_str expanding the run-length
788       // encoding in the process.
789       std ::string packet_str =
790           ExpandRLE(m_bytes.substr(content_start, content_end - content_start));
791       packet = StringExtractorGDBRemote(packet_str);
792 
793       if (m_bytes[0] == '$' || m_bytes[0] == '%') {
794         assert(checksum_idx < m_bytes.size());
795         if (::isxdigit(m_bytes[checksum_idx + 0]) ||
796             ::isxdigit(m_bytes[checksum_idx + 1])) {
797           if (GetSendAcks()) {
798             const char *packet_checksum_cstr = &m_bytes[checksum_idx];
799             char packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
800             char actual_checksum = CalculcateChecksum(
801                 llvm::StringRef(m_bytes).slice(content_start, content_end));
802             success = packet_checksum == actual_checksum;
803             if (!success) {
804               LLDB_LOGF(log,
805                         "error: checksum mismatch: %.*s expected 0x%2.2x, "
806                         "got 0x%2.2x",
807                         (int)(total_length), m_bytes.c_str(),
808                         (uint8_t)packet_checksum, (uint8_t)actual_checksum);
809             }
810             // Send the ack or nack if needed
811             if (!success)
812               SendNack();
813             else
814               SendAck();
815           }
816         } else {
817           success = false;
818           LLDB_LOGF(log, "error: invalid checksum in packet: '%s'\n",
819                     m_bytes.c_str());
820         }
821       }
822 
823       m_bytes.erase(0, total_length);
824       packet.SetFilePos(0);
825 
826       if (isNotifyPacket)
827         return GDBRemoteCommunication::PacketType::Notify;
828       else
829         return GDBRemoteCommunication::PacketType::Standard;
830     }
831   }
832   packet.Clear();
833   return GDBRemoteCommunication::PacketType::Invalid;
834 }
835 
836 Status GDBRemoteCommunication::StartListenThread(const char *hostname,
837                                                  uint16_t port) {
838   if (m_listen_thread.IsJoinable())
839     return Status::FromErrorString("listen thread already running");
840 
841   char listen_url[512];
842   if (hostname && hostname[0])
843     snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
844   else
845     snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
846   m_listen_url = listen_url;
847   SetConnection(std::make_unique<ConnectionFileDescriptor>());
848   llvm::Expected<HostThread> listen_thread = ThreadLauncher::LaunchThread(
849       listen_url, [this] { return GDBRemoteCommunication::ListenThread(); });
850   if (!listen_thread)
851     return Status::FromError(listen_thread.takeError());
852   m_listen_thread = *listen_thread;
853 
854   return Status();
855 }
856 
857 bool GDBRemoteCommunication::JoinListenThread() {
858   if (m_listen_thread.IsJoinable())
859     m_listen_thread.Join(nullptr);
860   return true;
861 }
862 
863 lldb::thread_result_t GDBRemoteCommunication::ListenThread() {
864   Status error;
865   ConnectionFileDescriptor *connection =
866       (ConnectionFileDescriptor *)GetConnection();
867 
868   if (connection) {
869     // Do the listen on another thread so we can continue on...
870     if (connection->Connect(
871             m_listen_url.c_str(),
872             [this](llvm::StringRef port_str) {
873               uint16_t port = 0;
874               llvm::to_integer(port_str, port, 10);
875               m_port_promise.set_value(port);
876             },
877             &error) != eConnectionStatusSuccess)
878       SetConnection(nullptr);
879   }
880   return {};
881 }
882 
883 FileSpec GDBRemoteCommunication::GetDebugserverPath(Platform *platform) {
884   Log *log = GetLog(GDBRLog::Process);
885   // If we locate debugserver, keep that located version around
886   static FileSpec g_debugserver_file_spec;
887   FileSpec debugserver_file_spec;
888 
889   Environment host_env = Host::GetEnvironment();
890 
891   // Always check to see if we have an environment override for the path to the
892   // debugserver to use and use it if we do.
893   std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
894   if (!env_debugserver_path.empty()) {
895     debugserver_file_spec.SetFile(env_debugserver_path,
896                                   FileSpec::Style::native);
897     LLDB_LOGF(log,
898               "GDBRemoteCommunication::%s() gdb-remote stub exe path set "
899               "from environment variable: %s",
900               __FUNCTION__, env_debugserver_path.c_str());
901   } else
902     debugserver_file_spec = g_debugserver_file_spec;
903   bool debugserver_exists =
904       FileSystem::Instance().Exists(debugserver_file_spec);
905   if (!debugserver_exists) {
906     // The debugserver binary is in the LLDB.framework/Resources directory.
907     debugserver_file_spec = HostInfo::GetSupportExeDir();
908     if (debugserver_file_spec) {
909       debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
910       debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
911       if (debugserver_exists) {
912         LLDB_LOGF(log,
913                   "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
914                   __FUNCTION__, debugserver_file_spec.GetPath().c_str());
915 
916         g_debugserver_file_spec = debugserver_file_spec;
917       } else {
918         if (platform)
919           debugserver_file_spec =
920               platform->LocateExecutable(DEBUGSERVER_BASENAME);
921         else
922           debugserver_file_spec.Clear();
923         if (debugserver_file_spec) {
924           // Platform::LocateExecutable() wouldn't return a path if it doesn't
925           // exist
926           debugserver_exists = true;
927         } else {
928           LLDB_LOGF(log,
929                     "GDBRemoteCommunication::%s() could not find "
930                     "gdb-remote stub exe '%s'",
931                     __FUNCTION__, debugserver_file_spec.GetPath().c_str());
932         }
933         // Don't cache the platform specific GDB server binary as it could
934         // change from platform to platform
935         g_debugserver_file_spec.Clear();
936       }
937     }
938   }
939   return debugserver_file_spec;
940 }
941 
942 Status GDBRemoteCommunication::StartDebugserverProcess(
943     const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
944     uint16_t *port, const Args *inferior_args, shared_fd_t pass_comm_fd) {
945   Log *log = GetLog(GDBRLog::Process);
946   LLDB_LOGF(log, "GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
947             __FUNCTION__, url ? url : "<empty>", port ? *port : uint16_t(0));
948 
949   Status error;
950   FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
951   if ((debugserver_file_spec = GetDebugserverPath(platform))) {
952     std::string debugserver_path = debugserver_file_spec.GetPath();
953 
954     Args &debugserver_args = launch_info.GetArguments();
955     debugserver_args.Clear();
956 
957     // Start args with "debugserver /file/path -r --"
958     debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
959 
960 #if !defined(__APPLE__)
961     // First argument to lldb-server must be mode in which to run.
962     debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
963 #endif
964 
965     // If a url is supplied then use it
966     if (url && url[0])
967       debugserver_args.AppendArgument(llvm::StringRef(url));
968 
969     if (pass_comm_fd != SharedSocket::kInvalidFD) {
970       StreamString fd_arg;
971       fd_arg.Printf("--fd=%" PRIi64, (int64_t)pass_comm_fd);
972       debugserver_args.AppendArgument(fd_arg.GetString());
973       // Send "pass_comm_fd" down to the inferior so it can use it to
974       // communicate back with this process. Ignored on Windows.
975 #ifndef _WIN32
976       launch_info.AppendDuplicateFileAction((int)pass_comm_fd,
977                                             (int)pass_comm_fd);
978 #endif
979     }
980 
981     // use native registers, not the GDB registers
982     debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
983 
984     if (launch_info.GetLaunchInSeparateProcessGroup()) {
985       debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
986     }
987 
988     llvm::SmallString<128> named_pipe_path;
989     // socket_pipe is used by debug server to communicate back either
990     // TCP port or domain socket name which it listens on.
991     // The second purpose of the pipe to serve as a synchronization point -
992     // once data is written to the pipe, debug server is up and running.
993     Pipe socket_pipe;
994 
995     // port is null when debug server should listen on domain socket - we're
996     // not interested in port value but rather waiting for debug server to
997     // become available.
998     if (pass_comm_fd == SharedSocket::kInvalidFD) {
999       if (url) {
1000 // Create a temporary file to get the stdout/stderr and redirect the output of
1001 // the command into this file. We will later read this file if all goes well
1002 // and fill the data into "command_output_ptr"
1003 #if defined(__APPLE__)
1004         // Binding to port zero, we need to figure out what port it ends up
1005         // using using a named pipe...
1006         error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1007                                                  false, named_pipe_path);
1008         if (error.Fail()) {
1009           LLDB_LOGF(log,
1010                     "GDBRemoteCommunication::%s() "
1011                     "named pipe creation failed: %s",
1012                     __FUNCTION__, error.AsCString());
1013           return error;
1014         }
1015         debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
1016         debugserver_args.AppendArgument(named_pipe_path);
1017 #else
1018         // Binding to port zero, we need to figure out what port it ends up
1019         // using using an unnamed pipe...
1020         error = socket_pipe.CreateNew(true);
1021         if (error.Fail()) {
1022           LLDB_LOGF(log,
1023                     "GDBRemoteCommunication::%s() "
1024                     "unnamed pipe creation failed: %s",
1025                     __FUNCTION__, error.AsCString());
1026           return error;
1027         }
1028         pipe_t write = socket_pipe.GetWritePipe();
1029         debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1030         debugserver_args.AppendArgument(llvm::to_string(write));
1031         launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
1032 #endif
1033       } else {
1034         // No host and port given, so lets listen on our end and make the
1035         // debugserver connect to us..
1036         error = StartListenThread("127.0.0.1", 0);
1037         if (error.Fail()) {
1038           LLDB_LOGF(log,
1039                     "GDBRemoteCommunication::%s() unable to start listen "
1040                     "thread: %s",
1041                     __FUNCTION__, error.AsCString());
1042           return error;
1043         }
1044 
1045         // Wait for 10 seconds to resolve the bound port
1046         std::future<uint16_t> port_future = m_port_promise.get_future();
1047         uint16_t port_ = port_future.wait_for(std::chrono::seconds(10)) ==
1048                                  std::future_status::ready
1049                              ? port_future.get()
1050                              : 0;
1051         if (port_ > 0) {
1052           char port_cstr[32];
1053           snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1054           // Send the host and port down that debugserver and specify an option
1055           // so that it connects back to the port we are listening to in this
1056           // process
1057           debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1058           debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
1059           if (port)
1060             *port = port_;
1061         } else {
1062           LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s",
1063                     __FUNCTION__, error.AsCString());
1064           return Status::FromErrorString(
1065               "failed to bind to port 0 on 127.0.0.1");
1066         }
1067       }
1068     }
1069 
1070     Environment host_env = Host::GetEnvironment();
1071     std::string env_debugserver_log_file =
1072         host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
1073     if (!env_debugserver_log_file.empty()) {
1074       debugserver_args.AppendArgument(
1075           llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
1076     }
1077 
1078 #if defined(__APPLE__)
1079     const char *env_debugserver_log_flags =
1080         getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1081     if (env_debugserver_log_flags) {
1082       debugserver_args.AppendArgument(
1083           llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
1084     }
1085 #else
1086     std::string env_debugserver_log_channels =
1087         host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
1088     if (!env_debugserver_log_channels.empty()) {
1089       debugserver_args.AppendArgument(
1090           llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
1091               .str());
1092     }
1093 #endif
1094 
1095     // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1096     // env var doesn't come back.
1097     uint32_t env_var_index = 1;
1098     bool has_env_var;
1099     do {
1100       char env_var_name[64];
1101       snprintf(env_var_name, sizeof(env_var_name),
1102                "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1103       std::string extra_arg = host_env.lookup(env_var_name);
1104       has_env_var = !extra_arg.empty();
1105 
1106       if (has_env_var) {
1107         debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
1108         LLDB_LOGF(log,
1109                   "GDBRemoteCommunication::%s adding env var %s contents "
1110                   "to stub command line (%s)",
1111                   __FUNCTION__, env_var_name, extra_arg.c_str());
1112       }
1113     } while (has_env_var);
1114 
1115     if (inferior_args && inferior_args->GetArgumentCount() > 0) {
1116       debugserver_args.AppendArgument(llvm::StringRef("--"));
1117       debugserver_args.AppendArguments(*inferior_args);
1118     }
1119 
1120     // Copy the current environment to the gdbserver/debugserver instance
1121     launch_info.GetEnvironment() = host_env;
1122 
1123     // Close STDIN, STDOUT and STDERR.
1124     launch_info.AppendCloseFileAction(STDIN_FILENO);
1125     launch_info.AppendCloseFileAction(STDOUT_FILENO);
1126     launch_info.AppendCloseFileAction(STDERR_FILENO);
1127 
1128     // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1129     launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1130     launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1131     launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1132 
1133     if (log) {
1134       StreamString string_stream;
1135       Platform *const platform = nullptr;
1136       launch_info.Dump(string_stream, platform);
1137       LLDB_LOGF(log, "launch info for gdb-remote stub:\n%s",
1138                 string_stream.GetData());
1139     }
1140     error = Host::LaunchProcess(launch_info);
1141 
1142     if (error.Success() &&
1143         (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1144         pass_comm_fd == SharedSocket::kInvalidFD) {
1145       if (named_pipe_path.size() > 0) {
1146         error = socket_pipe.OpenAsReader(named_pipe_path, false);
1147         if (error.Fail())
1148           LLDB_LOGF(log,
1149                     "GDBRemoteCommunication::%s() "
1150                     "failed to open named pipe %s for reading: %s",
1151                     __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1152       }
1153 
1154       if (socket_pipe.CanWrite())
1155         socket_pipe.CloseWriteFileDescriptor();
1156       if (socket_pipe.CanRead()) {
1157         // The port number may be up to "65535\0".
1158         char port_cstr[6] = {0};
1159         size_t num_bytes = sizeof(port_cstr);
1160         // Read port from pipe with 10 second timeout.
1161         error = socket_pipe.ReadWithTimeout(
1162             port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1163         if (error.Success() && (port != nullptr)) {
1164           assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
1165           uint16_t child_port = 0;
1166           // FIXME: improve error handling
1167           llvm::to_integer(port_cstr, child_port);
1168           if (*port == 0 || *port == child_port) {
1169             *port = child_port;
1170             LLDB_LOGF(log,
1171                       "GDBRemoteCommunication::%s() "
1172                       "debugserver listens %u port",
1173                       __FUNCTION__, *port);
1174           } else {
1175             LLDB_LOGF(log,
1176                       "GDBRemoteCommunication::%s() "
1177                       "debugserver listening on port "
1178                       "%d but requested port was %d",
1179                       __FUNCTION__, (uint32_t)child_port, (uint32_t)(*port));
1180           }
1181         } else {
1182           LLDB_LOGF(log,
1183                     "GDBRemoteCommunication::%s() "
1184                     "failed to read a port value from pipe %s: %s",
1185                     __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1186         }
1187         socket_pipe.Close();
1188       }
1189 
1190       if (named_pipe_path.size() > 0) {
1191         const auto err = socket_pipe.Delete(named_pipe_path);
1192         if (err.Fail()) {
1193           LLDB_LOGF(log,
1194                     "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1195                     __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
1196         }
1197       }
1198 
1199       // Make sure we actually connect with the debugserver...
1200       JoinListenThread();
1201     }
1202   } else {
1203     error = Status::FromErrorString("unable to locate " DEBUGSERVER_BASENAME);
1204   }
1205 
1206   if (error.Fail()) {
1207     LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1208               error.AsCString());
1209   }
1210 
1211   return error;
1212 }
1213 
1214 void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1215 
1216 llvm::Error
1217 GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1218                                        GDBRemoteCommunication &server) {
1219   const int backlog = 5;
1220   TCPSocket listen_socket(true);
1221   if (llvm::Error error =
1222           listen_socket.Listen("localhost:0", backlog).ToError())
1223     return error;
1224 
1225   llvm::SmallString<32> remote_addr;
1226   llvm::raw_svector_ostream(remote_addr)
1227       << "connect://localhost:" << listen_socket.GetLocalPortNumber();
1228 
1229   std::unique_ptr<ConnectionFileDescriptor> conn_up(
1230       new ConnectionFileDescriptor());
1231   Status status;
1232   if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)
1233     return llvm::createStringError(llvm::inconvertibleErrorCode(),
1234                                    "Unable to connect: %s", status.AsCString());
1235 
1236   // The connection was already established above, so a short timeout is
1237   // sufficient.
1238   Socket *accept_socket = nullptr;
1239   if (Status accept_status =
1240           listen_socket.Accept(std::chrono::seconds(1), accept_socket);
1241       accept_status.Fail())
1242     return accept_status.takeError();
1243 
1244   client.SetConnection(std::move(conn_up));
1245   server.SetConnection(
1246       std::make_unique<ConnectionFileDescriptor>(accept_socket));
1247   return llvm::Error::success();
1248 }
1249 
1250 GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
1251     GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
1252     : m_gdb_comm(gdb_comm), m_saved_timeout(0), m_timeout_modified(false) {
1253   auto curr_timeout = gdb_comm.GetPacketTimeout();
1254   // Only update the timeout if the timeout is greater than the current
1255   // timeout. If the current timeout is larger, then just use that.
1256   if (curr_timeout < timeout) {
1257     m_timeout_modified = true;
1258     m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1259   }
1260 }
1261 
1262 GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
1263   // Only restore the timeout if we set it in the constructor.
1264   if (m_timeout_modified)
1265     m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1266 }
1267 
1268 void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1269     const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1270     StringRef Style) {
1271   using PacketResult = GDBRemoteCommunication::PacketResult;
1272 
1273   switch (result) {
1274   case PacketResult::Success:
1275     Stream << "Success";
1276     break;
1277   case PacketResult::ErrorSendFailed:
1278     Stream << "ErrorSendFailed";
1279     break;
1280   case PacketResult::ErrorSendAck:
1281     Stream << "ErrorSendAck";
1282     break;
1283   case PacketResult::ErrorReplyFailed:
1284     Stream << "ErrorReplyFailed";
1285     break;
1286   case PacketResult::ErrorReplyTimeout:
1287     Stream << "ErrorReplyTimeout";
1288     break;
1289   case PacketResult::ErrorReplyInvalid:
1290     Stream << "ErrorReplyInvalid";
1291     break;
1292   case PacketResult::ErrorReplyAck:
1293     Stream << "ErrorReplyAck";
1294     break;
1295   case PacketResult::ErrorDisconnected:
1296     Stream << "ErrorDisconnected";
1297     break;
1298   case PacketResult::ErrorNoSequenceLock:
1299     Stream << "ErrorNoSequenceLock";
1300     break;
1301   }
1302 }
1303 
1304 std::string GDBRemoteCommunication::ExpandRLE(std::string packet) {
1305   // Reserve enough byte for the most common case (no RLE used).
1306   std::string decoded;
1307   decoded.reserve(packet.size());
1308   for (std::string::const_iterator c = packet.begin(); c != packet.end(); ++c) {
1309     if (*c == '*') {
1310       // '*' indicates RLE. Next character will give us the repeat count and
1311       // previous character is what is to be repeated.
1312       char char_to_repeat = decoded.back();
1313       // Number of time the previous character is repeated.
1314       int repeat_count = *++c + 3 - ' ';
1315       // We have the char_to_repeat and repeat_count. Now push it in the
1316       // packet.
1317       for (int i = 0; i < repeat_count; ++i)
1318         decoded.push_back(char_to_repeat);
1319     } else if (*c == 0x7d) {
1320       // 0x7d is the escape character.  The next character is to be XOR'd with
1321       // 0x20.
1322       char escapee = *++c ^ 0x20;
1323       decoded.push_back(escapee);
1324     } else {
1325       decoded.push_back(*c);
1326     }
1327   }
1328   return decoded;
1329 }
1330