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 = compression_decode_scratch_buffer_size (COMPRESSION_LZMA);
543       else if (m_compression_type == CompressionType::LZFSE)
544         scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
545       if (scratchbuf_size > 0) {
546         m_decompression_scratch = (void*) malloc (scratchbuf_size);
547         m_decompression_scratch_type = m_compression_type;
548       }
549     }
550 
551     if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
552       decompressed_bytes = compression_decode_buffer(
553           decompressed_buffer, decompressed_bufsize,
554           (uint8_t *)unescaped_content.data(), unescaped_content.size(),
555           m_decompression_scratch, compression_type);
556     }
557   }
558 #endif
559 
560 #if LLVM_ENABLE_ZLIB
561   if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
562       decompressed_buffer != nullptr &&
563       m_compression_type == CompressionType::ZlibDeflate) {
564     z_stream stream;
565     memset(&stream, 0, sizeof(z_stream));
566     stream.next_in = (Bytef *)unescaped_content.data();
567     stream.avail_in = (uInt)unescaped_content.size();
568     stream.total_in = 0;
569     stream.next_out = (Bytef *)decompressed_buffer;
570     stream.avail_out = decompressed_bufsize;
571     stream.total_out = 0;
572     stream.zalloc = Z_NULL;
573     stream.zfree = Z_NULL;
574     stream.opaque = Z_NULL;
575 
576     if (inflateInit2(&stream, -15) == Z_OK) {
577       int status = inflate(&stream, Z_NO_FLUSH);
578       inflateEnd(&stream);
579       if (status == Z_STREAM_END) {
580         decompressed_bytes = stream.total_out;
581       }
582     }
583   }
584 #endif
585 
586   if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
587     if (decompressed_buffer)
588       free(decompressed_buffer);
589     m_bytes.erase(0, size_of_first_packet);
590     return false;
591   }
592 
593   std::string new_packet;
594   new_packet.reserve(decompressed_bytes + 6);
595   new_packet.push_back(m_bytes[0]);
596   new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
597   new_packet.push_back('#');
598   if (GetSendAcks()) {
599     uint8_t decompressed_checksum = CalculcateChecksum(
600         llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
601     char decompressed_checksum_str[3];
602     snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
603     new_packet.append(decompressed_checksum_str);
604   } else {
605     new_packet.push_back('0');
606     new_packet.push_back('0');
607   }
608 
609   m_bytes.replace(0, size_of_first_packet, new_packet.data(),
610                   new_packet.size());
611 
612   free(decompressed_buffer);
613   return true;
614 }
615 
616 GDBRemoteCommunication::PacketType
CheckForPacket(const uint8_t * src,size_t src_len,StringExtractorGDBRemote & packet)617 GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
618                                        StringExtractorGDBRemote &packet) {
619   // Put the packet data into the buffer in a thread safe fashion
620   std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
621 
622   Log *log = GetLog(GDBRLog::Packets);
623 
624   if (src && src_len > 0) {
625     if (log && log->GetVerbose()) {
626       StreamString s;
627       LLDB_LOGF(log, "GDBRemoteCommunication::%s adding %u bytes: %.*s",
628                 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
629     }
630     m_bytes.append((const char *)src, src_len);
631   }
632 
633   bool isNotifyPacket = false;
634 
635   // Parse up the packets into gdb remote packets
636   if (!m_bytes.empty()) {
637     // end_idx must be one past the last valid packet byte. Start it off with
638     // an invalid value that is the same as the current index.
639     size_t content_start = 0;
640     size_t content_length = 0;
641     size_t total_length = 0;
642     size_t checksum_idx = std::string::npos;
643 
644     // Size of packet before it is decompressed, for logging purposes
645     size_t original_packet_size = m_bytes.size();
646     if (CompressionIsEnabled()) {
647       if (!DecompressPacket()) {
648         packet.Clear();
649         return GDBRemoteCommunication::PacketType::Standard;
650       }
651     }
652 
653     switch (m_bytes[0]) {
654     case '+':                            // Look for ack
655     case '-':                            // Look for cancel
656     case '\x03':                         // ^C to halt target
657       content_length = total_length = 1; // The command is one byte long...
658       break;
659 
660     case '%': // Async notify packet
661       isNotifyPacket = true;
662       [[fallthrough]];
663 
664     case '$':
665       // Look for a standard gdb packet?
666       {
667         size_t hash_pos = m_bytes.find('#');
668         if (hash_pos != std::string::npos) {
669           if (hash_pos + 2 < m_bytes.size()) {
670             checksum_idx = hash_pos + 1;
671             // Skip the dollar sign
672             content_start = 1;
673             // Don't include the # in the content or the $ in the content
674             // length
675             content_length = hash_pos - 1;
676 
677             total_length =
678                 hash_pos + 3; // Skip the # and the two hex checksum bytes
679           } else {
680             // Checksum bytes aren't all here yet
681             content_length = std::string::npos;
682           }
683         }
684       }
685       break;
686 
687     default: {
688       // We have an unexpected byte and we need to flush all bad data that is
689       // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
690       // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
691       // header) or of course, the end of the data in m_bytes...
692       const size_t bytes_len = m_bytes.size();
693       bool done = false;
694       uint32_t idx;
695       for (idx = 1; !done && idx < bytes_len; ++idx) {
696         switch (m_bytes[idx]) {
697         case '+':
698         case '-':
699         case '\x03':
700         case '%':
701         case '$':
702           done = true;
703           break;
704 
705         default:
706           break;
707         }
708       }
709       LLDB_LOGF(log, "GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
710                 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
711       m_bytes.erase(0, idx - 1);
712     } break;
713     }
714 
715     if (content_length == std::string::npos) {
716       packet.Clear();
717       return GDBRemoteCommunication::PacketType::Invalid;
718     } else if (total_length > 0) {
719 
720       // We have a valid packet...
721       assert(content_length <= m_bytes.size());
722       assert(total_length <= m_bytes.size());
723       assert(content_length <= total_length);
724       size_t content_end = content_start + content_length;
725 
726       bool success = true;
727       if (log) {
728         // If logging was just enabled and we have history, then dump out what
729         // we have to the log so we get the historical context. The Dump() call
730         // that logs all of the packet will set a boolean so that we don't dump
731         // this more than once
732         if (!m_history.DidDumpToLog())
733           m_history.Dump(log);
734 
735         bool binary = false;
736         // Only detect binary for packets that start with a '$' and have a
737         // '#CC' checksum
738         if (m_bytes[0] == '$' && total_length > 4) {
739           for (size_t i = 0; !binary && i < total_length; ++i) {
740             unsigned char c = m_bytes[i];
741             if (!llvm::isPrint(c) && !llvm::isSpace(c)) {
742               binary = true;
743             }
744           }
745         }
746         if (binary) {
747           StreamString strm;
748           // Packet header...
749           if (CompressionIsEnabled())
750             strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
751                         (uint64_t)original_packet_size, (uint64_t)total_length,
752                         m_bytes[0]);
753           else
754             strm.Printf("<%4" PRIu64 "> read packet: %c",
755                         (uint64_t)total_length, m_bytes[0]);
756           for (size_t i = content_start; i < content_end; ++i) {
757             // Remove binary escaped bytes when displaying the packet...
758             const char ch = m_bytes[i];
759             if (ch == 0x7d) {
760               // 0x7d is the escape character.  The next character is to be
761               // XOR'd with 0x20.
762               const char escapee = m_bytes[++i] ^ 0x20;
763               strm.Printf("%2.2x", escapee);
764             } else {
765               strm.Printf("%2.2x", (uint8_t)ch);
766             }
767           }
768           // Packet footer...
769           strm.Printf("%c%c%c", m_bytes[total_length - 3],
770                       m_bytes[total_length - 2], m_bytes[total_length - 1]);
771           log->PutString(strm.GetString());
772         } else {
773           if (CompressionIsEnabled())
774             LLDB_LOGF(log, "<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
775                       (uint64_t)original_packet_size, (uint64_t)total_length,
776                       (int)(total_length), m_bytes.c_str());
777           else
778             LLDB_LOGF(log, "<%4" PRIu64 "> read packet: %.*s",
779                       (uint64_t)total_length, (int)(total_length),
780                       m_bytes.c_str());
781         }
782       }
783 
784       m_history.AddPacket(m_bytes, total_length,
785                           GDBRemotePacket::ePacketTypeRecv, total_length);
786 
787       // Copy the packet from m_bytes to packet_str expanding the run-length
788       // encoding in the process.
789       std ::string packet_str =
790           ExpandRLE(m_bytes.substr(content_start, content_end - content_start));
791       packet = StringExtractorGDBRemote(packet_str);
792 
793       if (m_bytes[0] == '$' || m_bytes[0] == '%') {
794         assert(checksum_idx < m_bytes.size());
795         if (::isxdigit(m_bytes[checksum_idx + 0]) ||
796             ::isxdigit(m_bytes[checksum_idx + 1])) {
797           if (GetSendAcks()) {
798             const char *packet_checksum_cstr = &m_bytes[checksum_idx];
799             char packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
800             char actual_checksum = CalculcateChecksum(
801                 llvm::StringRef(m_bytes).slice(content_start, content_end));
802             success = packet_checksum == actual_checksum;
803             if (!success) {
804               LLDB_LOGF(log,
805                         "error: checksum mismatch: %.*s expected 0x%2.2x, "
806                         "got 0x%2.2x",
807                         (int)(total_length), m_bytes.c_str(),
808                         (uint8_t)packet_checksum, (uint8_t)actual_checksum);
809             }
810             // Send the ack or nack if needed
811             if (!success)
812               SendNack();
813             else
814               SendAck();
815           }
816         } else {
817           success = false;
818           LLDB_LOGF(log, "error: invalid checksum in packet: '%s'\n",
819                     m_bytes.c_str());
820         }
821       }
822 
823       m_bytes.erase(0, total_length);
824       packet.SetFilePos(0);
825 
826       if (isNotifyPacket)
827         return GDBRemoteCommunication::PacketType::Notify;
828       else
829         return GDBRemoteCommunication::PacketType::Standard;
830     }
831   }
832   packet.Clear();
833   return GDBRemoteCommunication::PacketType::Invalid;
834 }
835 
StartListenThread(const char * hostname,uint16_t port)836 Status GDBRemoteCommunication::StartListenThread(const char *hostname,
837                                                  uint16_t port) {
838   if (m_listen_thread.IsJoinable())
839     return Status("listen thread already running");
840 
841   char listen_url[512];
842   if (hostname && hostname[0])
843     snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
844   else
845     snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
846   m_listen_url = listen_url;
847   SetConnection(std::make_unique<ConnectionFileDescriptor>());
848   llvm::Expected<HostThread> listen_thread = ThreadLauncher::LaunchThread(
849       listen_url, [this] { return GDBRemoteCommunication::ListenThread(); });
850   if (!listen_thread)
851     return Status(listen_thread.takeError());
852   m_listen_thread = *listen_thread;
853 
854   return Status();
855 }
856 
JoinListenThread()857 bool GDBRemoteCommunication::JoinListenThread() {
858   if (m_listen_thread.IsJoinable())
859     m_listen_thread.Join(nullptr);
860   return true;
861 }
862 
ListenThread()863 lldb::thread_result_t GDBRemoteCommunication::ListenThread() {
864   Status error;
865   ConnectionFileDescriptor *connection =
866       (ConnectionFileDescriptor *)GetConnection();
867 
868   if (connection) {
869     // Do the listen on another thread so we can continue on...
870     if (connection->Connect(
871             m_listen_url.c_str(),
872             [this](llvm::StringRef port_str) {
873               uint16_t port = 0;
874               llvm::to_integer(port_str, port, 10);
875               m_port_promise.set_value(port);
876             },
877             &error) != eConnectionStatusSuccess)
878       SetConnection(nullptr);
879   }
880   return {};
881 }
882 
StartDebugserverProcess(const char * url,Platform * platform,ProcessLaunchInfo & launch_info,uint16_t * port,const Args * inferior_args,int pass_comm_fd)883 Status GDBRemoteCommunication::StartDebugserverProcess(
884     const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
885     uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
886   Log *log = GetLog(GDBRLog::Process);
887   LLDB_LOGF(log, "GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
888             __FUNCTION__, url ? url : "<empty>", port ? *port : uint16_t(0));
889 
890   Status error;
891   // If we locate debugserver, keep that located version around
892   static FileSpec g_debugserver_file_spec;
893 
894   char debugserver_path[PATH_MAX];
895   FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
896 
897   Environment host_env = Host::GetEnvironment();
898 
899   // Always check to see if we have an environment override for the path to the
900   // debugserver to use and use it if we do.
901   std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
902   if (!env_debugserver_path.empty()) {
903     debugserver_file_spec.SetFile(env_debugserver_path,
904                                   FileSpec::Style::native);
905     LLDB_LOGF(log,
906               "GDBRemoteCommunication::%s() gdb-remote stub exe path set "
907               "from environment variable: %s",
908               __FUNCTION__, env_debugserver_path.c_str());
909   } else
910     debugserver_file_spec = g_debugserver_file_spec;
911   bool debugserver_exists =
912       FileSystem::Instance().Exists(debugserver_file_spec);
913   if (!debugserver_exists) {
914     // The debugserver binary is in the LLDB.framework/Resources directory.
915     debugserver_file_spec = HostInfo::GetSupportExeDir();
916     if (debugserver_file_spec) {
917       debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
918       debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
919       if (debugserver_exists) {
920         LLDB_LOGF(log,
921                   "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
922                   __FUNCTION__, debugserver_file_spec.GetPath().c_str());
923 
924         g_debugserver_file_spec = debugserver_file_spec;
925       } else {
926         if (platform)
927           debugserver_file_spec =
928               platform->LocateExecutable(DEBUGSERVER_BASENAME);
929         else
930           debugserver_file_spec.Clear();
931         if (debugserver_file_spec) {
932           // Platform::LocateExecutable() wouldn't return a path if it doesn't
933           // exist
934           debugserver_exists = true;
935         } else {
936           LLDB_LOGF(log,
937                     "GDBRemoteCommunication::%s() could not find "
938                     "gdb-remote stub exe '%s'",
939                     __FUNCTION__, debugserver_file_spec.GetPath().c_str());
940         }
941         // Don't cache the platform specific GDB server binary as it could
942         // change from platform to platform
943         g_debugserver_file_spec.Clear();
944       }
945     }
946   }
947 
948   if (debugserver_exists) {
949     debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
950 
951     Args &debugserver_args = launch_info.GetArguments();
952     debugserver_args.Clear();
953 
954     // Start args with "debugserver /file/path -r --"
955     debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
956 
957 #if !defined(__APPLE__)
958     // First argument to lldb-server must be mode in which to run.
959     debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
960 #endif
961 
962     // If a url is supplied then use it
963     if (url)
964       debugserver_args.AppendArgument(llvm::StringRef(url));
965 
966     if (pass_comm_fd >= 0) {
967       StreamString fd_arg;
968       fd_arg.Printf("--fd=%i", pass_comm_fd);
969       debugserver_args.AppendArgument(fd_arg.GetString());
970       // Send "pass_comm_fd" down to the inferior so it can use it to
971       // communicate back with this process
972       launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
973     }
974 
975     // use native registers, not the GDB registers
976     debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
977 
978     if (launch_info.GetLaunchInSeparateProcessGroup()) {
979       debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
980     }
981 
982     llvm::SmallString<128> named_pipe_path;
983     // socket_pipe is used by debug server to communicate back either
984     // TCP port or domain socket name which it listens on.
985     // The second purpose of the pipe to serve as a synchronization point -
986     // once data is written to the pipe, debug server is up and running.
987     Pipe socket_pipe;
988 
989     // port is null when debug server should listen on domain socket - we're
990     // not interested in port value but rather waiting for debug server to
991     // become available.
992     if (pass_comm_fd == -1) {
993       if (url) {
994 // Create a temporary file to get the stdout/stderr and redirect the output of
995 // the command into this file. We will later read this file if all goes well
996 // and fill the data into "command_output_ptr"
997 #if defined(__APPLE__)
998         // Binding to port zero, we need to figure out what port it ends up
999         // using using a named pipe...
1000         error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1001                                                  false, named_pipe_path);
1002         if (error.Fail()) {
1003           LLDB_LOGF(log,
1004                     "GDBRemoteCommunication::%s() "
1005                     "named pipe creation failed: %s",
1006                     __FUNCTION__, error.AsCString());
1007           return error;
1008         }
1009         debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
1010         debugserver_args.AppendArgument(named_pipe_path);
1011 #else
1012         // Binding to port zero, we need to figure out what port it ends up
1013         // using using an unnamed pipe...
1014         error = socket_pipe.CreateNew(true);
1015         if (error.Fail()) {
1016           LLDB_LOGF(log,
1017                     "GDBRemoteCommunication::%s() "
1018                     "unnamed pipe creation failed: %s",
1019                     __FUNCTION__, error.AsCString());
1020           return error;
1021         }
1022         pipe_t write = socket_pipe.GetWritePipe();
1023         debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1024         debugserver_args.AppendArgument(llvm::to_string(write));
1025         launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
1026 #endif
1027       } else {
1028         // No host and port given, so lets listen on our end and make the
1029         // debugserver connect to us..
1030         error = StartListenThread("127.0.0.1", 0);
1031         if (error.Fail()) {
1032           LLDB_LOGF(log,
1033                     "GDBRemoteCommunication::%s() unable to start listen "
1034                     "thread: %s",
1035                     __FUNCTION__, error.AsCString());
1036           return error;
1037         }
1038 
1039         // Wait for 10 seconds to resolve the bound port
1040         std::future<uint16_t> port_future = m_port_promise.get_future();
1041         uint16_t port_ = port_future.wait_for(std::chrono::seconds(10)) ==
1042                                  std::future_status::ready
1043                              ? port_future.get()
1044                              : 0;
1045         if (port_ > 0) {
1046           char port_cstr[32];
1047           snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1048           // Send the host and port down that debugserver and specify an option
1049           // so that it connects back to the port we are listening to in this
1050           // process
1051           debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1052           debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
1053           if (port)
1054             *port = port_;
1055         } else {
1056           error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1057           LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s",
1058                     __FUNCTION__, error.AsCString());
1059           return error;
1060         }
1061       }
1062     }
1063     std::string env_debugserver_log_file =
1064         host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
1065     if (!env_debugserver_log_file.empty()) {
1066       debugserver_args.AppendArgument(
1067           llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
1068     }
1069 
1070 #if defined(__APPLE__)
1071     const char *env_debugserver_log_flags =
1072         getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1073     if (env_debugserver_log_flags) {
1074       debugserver_args.AppendArgument(
1075           llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
1076     }
1077 #else
1078     std::string env_debugserver_log_channels =
1079         host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
1080     if (!env_debugserver_log_channels.empty()) {
1081       debugserver_args.AppendArgument(
1082           llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
1083               .str());
1084     }
1085 #endif
1086 
1087     // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1088     // env var doesn't come back.
1089     uint32_t env_var_index = 1;
1090     bool has_env_var;
1091     do {
1092       char env_var_name[64];
1093       snprintf(env_var_name, sizeof(env_var_name),
1094                "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1095       std::string extra_arg = host_env.lookup(env_var_name);
1096       has_env_var = !extra_arg.empty();
1097 
1098       if (has_env_var) {
1099         debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
1100         LLDB_LOGF(log,
1101                   "GDBRemoteCommunication::%s adding env var %s contents "
1102                   "to stub command line (%s)",
1103                   __FUNCTION__, env_var_name, extra_arg.c_str());
1104       }
1105     } while (has_env_var);
1106 
1107     if (inferior_args && inferior_args->GetArgumentCount() > 0) {
1108       debugserver_args.AppendArgument(llvm::StringRef("--"));
1109       debugserver_args.AppendArguments(*inferior_args);
1110     }
1111 
1112     // Copy the current environment to the gdbserver/debugserver instance
1113     launch_info.GetEnvironment() = host_env;
1114 
1115     // Close STDIN, STDOUT and STDERR.
1116     launch_info.AppendCloseFileAction(STDIN_FILENO);
1117     launch_info.AppendCloseFileAction(STDOUT_FILENO);
1118     launch_info.AppendCloseFileAction(STDERR_FILENO);
1119 
1120     // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1121     launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1122     launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1123     launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1124 
1125     if (log) {
1126       StreamString string_stream;
1127       Platform *const platform = nullptr;
1128       launch_info.Dump(string_stream, platform);
1129       LLDB_LOGF(log, "launch info for gdb-remote stub:\n%s",
1130                 string_stream.GetData());
1131     }
1132     error = Host::LaunchProcess(launch_info);
1133 
1134     if (error.Success() &&
1135         (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1136         pass_comm_fd == -1) {
1137       if (named_pipe_path.size() > 0) {
1138         error = socket_pipe.OpenAsReader(named_pipe_path, false);
1139         if (error.Fail())
1140           LLDB_LOGF(log,
1141                     "GDBRemoteCommunication::%s() "
1142                     "failed to open named pipe %s for reading: %s",
1143                     __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1144       }
1145 
1146       if (socket_pipe.CanWrite())
1147         socket_pipe.CloseWriteFileDescriptor();
1148       if (socket_pipe.CanRead()) {
1149         char port_cstr[PATH_MAX] = {0};
1150         port_cstr[0] = '\0';
1151         size_t num_bytes = sizeof(port_cstr);
1152         // Read port from pipe with 10 second timeout.
1153         error = socket_pipe.ReadWithTimeout(
1154             port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1155         if (error.Success() && (port != nullptr)) {
1156           assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
1157           uint16_t child_port = 0;
1158           // FIXME: improve error handling
1159           llvm::to_integer(port_cstr, child_port);
1160           if (*port == 0 || *port == child_port) {
1161             *port = child_port;
1162             LLDB_LOGF(log,
1163                       "GDBRemoteCommunication::%s() "
1164                       "debugserver listens %u port",
1165                       __FUNCTION__, *port);
1166           } else {
1167             LLDB_LOGF(log,
1168                       "GDBRemoteCommunication::%s() "
1169                       "debugserver listening on port "
1170                       "%d but requested port was %d",
1171                       __FUNCTION__, (uint32_t)child_port, (uint32_t)(*port));
1172           }
1173         } else {
1174           LLDB_LOGF(log,
1175                     "GDBRemoteCommunication::%s() "
1176                     "failed to read a port value from pipe %s: %s",
1177                     __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1178         }
1179         socket_pipe.Close();
1180       }
1181 
1182       if (named_pipe_path.size() > 0) {
1183         const auto err = socket_pipe.Delete(named_pipe_path);
1184         if (err.Fail()) {
1185           LLDB_LOGF(log,
1186                     "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1187                     __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
1188         }
1189       }
1190 
1191       // Make sure we actually connect with the debugserver...
1192       JoinListenThread();
1193     }
1194   } else {
1195     error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1196   }
1197 
1198   if (error.Fail()) {
1199     LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1200               error.AsCString());
1201   }
1202 
1203   return error;
1204 }
1205 
DumpHistory(Stream & strm)1206 void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1207 
1208 llvm::Error
ConnectLocally(GDBRemoteCommunication & client,GDBRemoteCommunication & server)1209 GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1210                                        GDBRemoteCommunication &server) {
1211   const bool child_processes_inherit = false;
1212   const int backlog = 5;
1213   TCPSocket listen_socket(true, child_processes_inherit);
1214   if (llvm::Error error =
1215           listen_socket.Listen("localhost:0", backlog).ToError())
1216     return error;
1217 
1218   Socket *accept_socket = nullptr;
1219   std::future<Status> accept_status = std::async(
1220       std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1221 
1222   llvm::SmallString<32> remote_addr;
1223   llvm::raw_svector_ostream(remote_addr)
1224       << "connect://localhost:" << listen_socket.GetLocalPortNumber();
1225 
1226   std::unique_ptr<ConnectionFileDescriptor> conn_up(
1227       new ConnectionFileDescriptor());
1228   Status status;
1229   if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)
1230     return llvm::createStringError(llvm::inconvertibleErrorCode(),
1231                                    "Unable to connect: %s", status.AsCString());
1232 
1233   client.SetConnection(std::move(conn_up));
1234   if (llvm::Error error = accept_status.get().ToError())
1235     return error;
1236 
1237   server.SetConnection(
1238       std::make_unique<ConnectionFileDescriptor>(accept_socket));
1239   return llvm::Error::success();
1240 }
1241 
ScopedTimeout(GDBRemoteCommunication & gdb_comm,std::chrono::seconds timeout)1242 GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
1243     GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
1244     : m_gdb_comm(gdb_comm), m_saved_timeout(0), m_timeout_modified(false) {
1245   auto curr_timeout = gdb_comm.GetPacketTimeout();
1246   // Only update the timeout if the timeout is greater than the current
1247   // timeout. If the current timeout is larger, then just use that.
1248   if (curr_timeout < timeout) {
1249     m_timeout_modified = true;
1250     m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1251   }
1252 }
1253 
~ScopedTimeout()1254 GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
1255   // Only restore the timeout if we set it in the constructor.
1256   if (m_timeout_modified)
1257     m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1258 }
1259 
format(const GDBRemoteCommunication::PacketResult & result,raw_ostream & Stream,StringRef Style)1260 void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1261     const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1262     StringRef Style) {
1263   using PacketResult = GDBRemoteCommunication::PacketResult;
1264 
1265   switch (result) {
1266   case PacketResult::Success:
1267     Stream << "Success";
1268     break;
1269   case PacketResult::ErrorSendFailed:
1270     Stream << "ErrorSendFailed";
1271     break;
1272   case PacketResult::ErrorSendAck:
1273     Stream << "ErrorSendAck";
1274     break;
1275   case PacketResult::ErrorReplyFailed:
1276     Stream << "ErrorReplyFailed";
1277     break;
1278   case PacketResult::ErrorReplyTimeout:
1279     Stream << "ErrorReplyTimeout";
1280     break;
1281   case PacketResult::ErrorReplyInvalid:
1282     Stream << "ErrorReplyInvalid";
1283     break;
1284   case PacketResult::ErrorReplyAck:
1285     Stream << "ErrorReplyAck";
1286     break;
1287   case PacketResult::ErrorDisconnected:
1288     Stream << "ErrorDisconnected";
1289     break;
1290   case PacketResult::ErrorNoSequenceLock:
1291     Stream << "ErrorNoSequenceLock";
1292     break;
1293   }
1294 }
1295 
ExpandRLE(std::string packet)1296 std::string GDBRemoteCommunication::ExpandRLE(std::string packet) {
1297   // Reserve enough byte for the most common case (no RLE used).
1298   std::string decoded;
1299   decoded.reserve(packet.size());
1300   for (std::string::const_iterator c = packet.begin(); c != packet.end(); ++c) {
1301     if (*c == '*') {
1302       // '*' indicates RLE. Next character will give us the repeat count and
1303       // previous character is what is to be repeated.
1304       char char_to_repeat = decoded.back();
1305       // Number of time the previous character is repeated.
1306       int repeat_count = *++c + 3 - ' ';
1307       // We have the char_to_repeat and repeat_count. Now push it in the
1308       // packet.
1309       for (int i = 0; i < repeat_count; ++i)
1310         decoded.push_back(char_to_repeat);
1311     } else if (*c == 0x7d) {
1312       // 0x7d is the escape character.  The next character is to be XOR'd with
1313       // 0x20.
1314       char escapee = *++c ^ 0x20;
1315       decoded.push_back(escapee);
1316     } else {
1317       decoded.push_back(*c);
1318     }
1319   }
1320   return decoded;
1321 }
1322