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