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