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