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