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