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