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