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