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