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