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