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