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