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