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