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