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(packet_str);
918             success = packet_checksum == actual_checksum;
919             if (!success) {
920               if (log)
921                 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
922                             "got 0x%2.2x",
923                             (int)(total_length), m_bytes.c_str(),
924                             (uint8_t)packet_checksum, (uint8_t)actual_checksum);
925             }
926             // Send the ack or nack if needed
927             if (!success)
928               SendNack();
929             else
930               SendAck();
931           }
932         } else {
933           success = false;
934           if (log)
935             log->Printf("error: invalid checksum in packet: '%s'\n",
936                         m_bytes.c_str());
937         }
938       }
939 
940       m_bytes.erase(0, total_length);
941       packet.SetFilePos(0);
942 
943       if (isNotifyPacket)
944         return GDBRemoteCommunication::PacketType::Notify;
945       else
946         return GDBRemoteCommunication::PacketType::Standard;
947     }
948   }
949   packet.Clear();
950   return GDBRemoteCommunication::PacketType::Invalid;
951 }
952 
953 Status GDBRemoteCommunication::StartListenThread(const char *hostname,
954                                                  uint16_t port) {
955   Status error;
956   if (m_listen_thread.IsJoinable()) {
957     error.SetErrorString("listen thread already running");
958   } else {
959     char listen_url[512];
960     if (hostname && hostname[0])
961       snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname,
962                port);
963     else
964       snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
965     m_listen_url = listen_url;
966     SetConnection(new ConnectionFileDescriptor());
967     m_listen_thread = ThreadLauncher::LaunchThread(
968         listen_url, GDBRemoteCommunication::ListenThread, this, &error);
969   }
970   return error;
971 }
972 
973 bool GDBRemoteCommunication::JoinListenThread() {
974   if (m_listen_thread.IsJoinable())
975     m_listen_thread.Join(nullptr);
976   return true;
977 }
978 
979 lldb::thread_result_t
980 GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
981   GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
982   Status error;
983   ConnectionFileDescriptor *connection =
984       (ConnectionFileDescriptor *)comm->GetConnection();
985 
986   if (connection) {
987     // Do the listen on another thread so we can continue on...
988     if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
989         eConnectionStatusSuccess)
990       comm->SetConnection(NULL);
991   }
992   return NULL;
993 }
994 
995 Status GDBRemoteCommunication::StartDebugserverProcess(
996     const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
997     uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
998   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
999   if (log)
1000     log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
1001                 __FUNCTION__, url ? url : "<empty>",
1002                 port ? *port : uint16_t(0));
1003 
1004   Status error;
1005   // If we locate debugserver, keep that located version around
1006   static FileSpec g_debugserver_file_spec;
1007 
1008   char debugserver_path[PATH_MAX];
1009   FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
1010 
1011   // Always check to see if we have an environment override for the path
1012   // to the debugserver to use and use it if we do.
1013   const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1014   if (env_debugserver_path) {
1015     debugserver_file_spec.SetFile(env_debugserver_path, false);
1016     if (log)
1017       log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
1018                   "from environment variable: %s",
1019                   __FUNCTION__, env_debugserver_path);
1020   } else
1021     debugserver_file_spec = g_debugserver_file_spec;
1022   bool debugserver_exists = debugserver_file_spec.Exists();
1023   if (!debugserver_exists) {
1024     // The debugserver binary is in the LLDB.framework/Resources
1025     // directory.
1026     if (HostInfo::GetLLDBPath(ePathTypeSupportExecutableDir,
1027                               debugserver_file_spec)) {
1028       debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
1029       debugserver_exists = debugserver_file_spec.Exists();
1030       if (debugserver_exists) {
1031         if (log)
1032           log->Printf(
1033               "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
1034               __FUNCTION__, debugserver_file_spec.GetPath().c_str());
1035 
1036         g_debugserver_file_spec = debugserver_file_spec;
1037       } else {
1038         debugserver_file_spec =
1039             platform->LocateExecutable(DEBUGSERVER_BASENAME);
1040         if (debugserver_file_spec) {
1041           // Platform::LocateExecutable() wouldn't return a path if it doesn't
1042           // exist
1043           debugserver_exists = true;
1044         } else {
1045           if (log)
1046             log->Printf("GDBRemoteCommunication::%s() could not find "
1047                         "gdb-remote stub exe '%s'",
1048                         __FUNCTION__, debugserver_file_spec.GetPath().c_str());
1049         }
1050         // Don't cache the platform specific GDB server binary as it could
1051         // change
1052         // from platform to platform
1053         g_debugserver_file_spec.Clear();
1054       }
1055     }
1056   }
1057 
1058   if (debugserver_exists) {
1059     debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
1060 
1061     Args &debugserver_args = launch_info.GetArguments();
1062     debugserver_args.Clear();
1063     char arg_cstr[PATH_MAX];
1064 
1065     // Start args with "debugserver /file/path -r --"
1066     debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
1067 
1068 #if !defined(__APPLE__)
1069     // First argument to lldb-server must be mode in which to run.
1070     debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
1071 #endif
1072 
1073     // If a url is supplied then use it
1074     if (url)
1075       debugserver_args.AppendArgument(llvm::StringRef(url));
1076 
1077     if (pass_comm_fd >= 0) {
1078       StreamString fd_arg;
1079       fd_arg.Printf("--fd=%i", pass_comm_fd);
1080       debugserver_args.AppendArgument(fd_arg.GetString());
1081       // Send "pass_comm_fd" down to the inferior so it can use it to
1082       // communicate back with this process
1083       launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1084     }
1085 
1086     // use native registers, not the GDB registers
1087     debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
1088 
1089     if (launch_info.GetLaunchInSeparateProcessGroup()) {
1090       debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
1091     }
1092 
1093     llvm::SmallString<PATH_MAX> named_pipe_path;
1094     // socket_pipe is used by debug server to communicate back either
1095     // TCP port or domain socket name which it listens on.
1096     // The second purpose of the pipe to serve as a synchronization point -
1097     // once data is written to the pipe, debug server is up and running.
1098     Pipe socket_pipe;
1099 
1100     // port is null when debug server should listen on domain socket -
1101     // we're not interested in port value but rather waiting for debug server
1102     // to become available.
1103     if (pass_comm_fd == -1) {
1104       if (url) {
1105 // Create a temporary file to get the stdout/stderr and redirect the
1106 // output of the command into this file. We will later read this file
1107 // if all goes well and fill the data into "command_output_ptr"
1108 #if defined(__APPLE__)
1109         // Binding to port zero, we need to figure out what port it ends up
1110         // using using a named pipe...
1111         error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1112                                                  false, named_pipe_path);
1113         if (error.Fail()) {
1114           if (log)
1115             log->Printf("GDBRemoteCommunication::%s() "
1116                         "named pipe creation failed: %s",
1117                         __FUNCTION__, error.AsCString());
1118           return error;
1119         }
1120         debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
1121         debugserver_args.AppendArgument(named_pipe_path);
1122 #else
1123         // Binding to port zero, we need to figure out what port it ends up
1124         // using using an unnamed pipe...
1125         error = socket_pipe.CreateNew(true);
1126         if (error.Fail()) {
1127           if (log)
1128             log->Printf("GDBRemoteCommunication::%s() "
1129                         "unnamed pipe creation failed: %s",
1130                         __FUNCTION__, error.AsCString());
1131           return error;
1132         }
1133         int write_fd = socket_pipe.GetWriteFileDescriptor();
1134         debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1135         debugserver_args.AppendArgument(llvm::to_string(write_fd));
1136         launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
1137 #endif
1138       } else {
1139         // No host and port given, so lets listen on our end and make the
1140         // debugserver
1141         // connect to us..
1142         error = StartListenThread("127.0.0.1", 0);
1143         if (error.Fail()) {
1144           if (log)
1145             log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1146                         "thread: %s",
1147                         __FUNCTION__, error.AsCString());
1148           return error;
1149         }
1150 
1151         ConnectionFileDescriptor *connection =
1152             (ConnectionFileDescriptor *)GetConnection();
1153         // Wait for 10 seconds to resolve the bound port
1154         uint16_t port_ = connection->GetListeningPort(10);
1155         if (port_ > 0) {
1156           char port_cstr[32];
1157           snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1158           // Send the host and port down that debugserver and specify an option
1159           // so that it connects back to the port we are listening to in this
1160           // process
1161           debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1162           debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
1163           if (port)
1164             *port = port_;
1165         } else {
1166           error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1167           if (log)
1168             log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1169                         error.AsCString());
1170           return error;
1171         }
1172       }
1173     }
1174 
1175     const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1176     if (env_debugserver_log_file) {
1177       ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-file=%s",
1178                  env_debugserver_log_file);
1179       debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
1180     }
1181 
1182 #if defined(__APPLE__)
1183     const char *env_debugserver_log_flags =
1184         getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1185     if (env_debugserver_log_flags) {
1186       ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-flags=%s",
1187                  env_debugserver_log_flags);
1188       debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
1189     }
1190 #else
1191     const char *env_debugserver_log_channels =
1192         getenv("LLDB_SERVER_LOG_CHANNELS");
1193     if (env_debugserver_log_channels) {
1194       ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-channels=%s",
1195                  env_debugserver_log_channels);
1196       debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
1197     }
1198 #endif
1199 
1200     // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1201     // env var doesn't come back.
1202     uint32_t env_var_index = 1;
1203     bool has_env_var;
1204     do {
1205       char env_var_name[64];
1206       snprintf(env_var_name, sizeof(env_var_name),
1207                "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1208       const char *extra_arg = getenv(env_var_name);
1209       has_env_var = extra_arg != nullptr;
1210 
1211       if (has_env_var) {
1212         debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
1213         if (log)
1214           log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1215                       "to stub command line (%s)",
1216                       __FUNCTION__, env_var_name, extra_arg);
1217       }
1218     } while (has_env_var);
1219 
1220     if (inferior_args && inferior_args->GetArgumentCount() > 0) {
1221       debugserver_args.AppendArgument(llvm::StringRef("--"));
1222       debugserver_args.AppendArguments(*inferior_args);
1223     }
1224 
1225     // Copy the current environment to the gdbserver/debugserver instance
1226     launch_info.GetEnvironment() = Host::GetEnvironment();
1227 
1228     // Close STDIN, STDOUT and STDERR.
1229     launch_info.AppendCloseFileAction(STDIN_FILENO);
1230     launch_info.AppendCloseFileAction(STDOUT_FILENO);
1231     launch_info.AppendCloseFileAction(STDERR_FILENO);
1232 
1233     // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1234     launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1235     launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1236     launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1237 
1238     if (log) {
1239       StreamString string_stream;
1240       Platform *const platform = nullptr;
1241       launch_info.Dump(string_stream, platform);
1242       log->Printf("launch info for gdb-remote stub:\n%s",
1243                   string_stream.GetData());
1244     }
1245     error = Host::LaunchProcess(launch_info);
1246 
1247     if (error.Success() &&
1248         (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1249         pass_comm_fd == -1) {
1250       if (named_pipe_path.size() > 0) {
1251         error = socket_pipe.OpenAsReader(named_pipe_path, false);
1252         if (error.Fail())
1253           if (log)
1254             log->Printf("GDBRemoteCommunication::%s() "
1255                         "failed to open named pipe %s for reading: %s",
1256                         __FUNCTION__, named_pipe_path.c_str(),
1257                         error.AsCString());
1258       }
1259 
1260       if (socket_pipe.CanWrite())
1261         socket_pipe.CloseWriteFileDescriptor();
1262       if (socket_pipe.CanRead()) {
1263         char port_cstr[PATH_MAX] = {0};
1264         port_cstr[0] = '\0';
1265         size_t num_bytes = sizeof(port_cstr);
1266         // Read port from pipe with 10 second timeout.
1267         error = socket_pipe.ReadWithTimeout(
1268             port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1269         if (error.Success() && (port != nullptr)) {
1270           assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
1271           uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1272           if (*port == 0 || *port == child_port) {
1273             *port = child_port;
1274             if (log)
1275               log->Printf("GDBRemoteCommunication::%s() "
1276                           "debugserver listens %u port",
1277                           __FUNCTION__, *port);
1278           } else {
1279             if (log)
1280               log->Printf("GDBRemoteCommunication::%s() "
1281                           "debugserver listening on port "
1282                           "%d but requested port was %d",
1283                           __FUNCTION__, (uint32_t)child_port,
1284                           (uint32_t)(*port));
1285           }
1286         } else {
1287           if (log)
1288             log->Printf("GDBRemoteCommunication::%s() "
1289                         "failed to read a port value from pipe %s: %s",
1290                         __FUNCTION__, named_pipe_path.c_str(),
1291                         error.AsCString());
1292         }
1293         socket_pipe.Close();
1294       }
1295 
1296       if (named_pipe_path.size() > 0) {
1297         const auto err = socket_pipe.Delete(named_pipe_path);
1298         if (err.Fail()) {
1299           if (log)
1300             log->Printf(
1301                 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1302                 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
1303         }
1304       }
1305 
1306       // Make sure we actually connect with the debugserver...
1307       JoinListenThread();
1308     }
1309   } else {
1310     error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1311   }
1312 
1313   if (error.Fail()) {
1314     if (log)
1315       log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1316                   error.AsCString());
1317   }
1318 
1319   return error;
1320 }
1321 
1322 void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1323 
1324 GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
1325     GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
1326   : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1327     auto curr_timeout = gdb_comm.GetPacketTimeout();
1328     // Only update the timeout if the timeout is greater than the current
1329     // timeout. If the current timeout is larger, then just use that.
1330     if (curr_timeout < timeout) {
1331       m_timeout_modified = true;
1332       m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1333     }
1334 }
1335 
1336 GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
1337   // Only restore the timeout if we set it in the constructor.
1338   if (m_timeout_modified)
1339     m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1340 }
1341 
1342 // This function is called via the Communications class read thread when bytes
1343 // become available
1344 // for this connection. This function will consume all incoming bytes and try to
1345 // parse whole
1346 // packets as they become available. Full packets are placed in a queue, so that
1347 // all packet
1348 // requests can simply pop from this queue. Async notification packets will be
1349 // dispatched
1350 // immediately to the ProcessGDBRemote Async thread via an event.
1351 void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1352                                                 size_t len, bool broadcast,
1353                                                 lldb::ConnectionStatus status) {
1354   StringExtractorGDBRemote packet;
1355 
1356   while (true) {
1357     PacketType type = CheckForPacket(bytes, len, packet);
1358 
1359     // scrub the data so we do not pass it back to CheckForPacket
1360     // on future passes of the loop
1361     bytes = nullptr;
1362     len = 0;
1363 
1364     // we may have received no packet so lets bail out
1365     if (type == PacketType::Invalid)
1366       break;
1367 
1368     if (type == PacketType::Standard) {
1369       // scope for the mutex
1370       {
1371         // lock down the packet queue
1372         std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1373         // push a new packet into the queue
1374         m_packet_queue.push(packet);
1375         // Signal condition variable that we have a packet
1376         m_condition_queue_not_empty.notify_one();
1377       }
1378     }
1379 
1380     if (type == PacketType::Notify) {
1381       // put this packet into an event
1382       const char *pdata = packet.GetStringRef().c_str();
1383 
1384       // as the communication class, we are a broadcaster and the
1385       // async thread is tuned to listen to us
1386       BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1387                      new EventDataBytes(pdata));
1388     }
1389   }
1390 }
1391 
1392 void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1393     const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1394     StringRef Style) {
1395   using PacketResult = GDBRemoteCommunication::PacketResult;
1396 
1397   switch (result) {
1398   case PacketResult::Success:
1399     Stream << "Success";
1400     break;
1401   case PacketResult::ErrorSendFailed:
1402     Stream << "ErrorSendFailed";
1403     break;
1404   case PacketResult::ErrorSendAck:
1405     Stream << "ErrorSendAck";
1406     break;
1407   case PacketResult::ErrorReplyFailed:
1408     Stream << "ErrorReplyFailed";
1409     break;
1410   case PacketResult::ErrorReplyTimeout:
1411     Stream << "ErrorReplyTimeout";
1412     break;
1413   case PacketResult::ErrorReplyInvalid:
1414     Stream << "ErrorReplyInvalid";
1415     break;
1416   case PacketResult::ErrorReplyAck:
1417     Stream << "ErrorReplyAck";
1418     break;
1419   case PacketResult::ErrorDisconnected:
1420     Stream << "ErrorDisconnected";
1421     break;
1422   case PacketResult::ErrorNoSequenceLock:
1423     Stream << "ErrorNoSequenceLock";
1424     break;
1425   }
1426 }
1427