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