LLDB mainline
GDBRemoteCommunication.cpp
Go to the documentation of this file.
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
10#include "ProcessGDBRemoteLog.h"
11#include "lldb/Host/Config.h"
13#include "lldb/Host/Host.h"
14#include "lldb/Host/Pipe.h"
16#include "lldb/Host/Socket.h"
20#include "lldb/Utility/Event.h"
22#include "lldb/Utility/Log.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
43using namespace lldb;
44using namespace lldb_private;
46
47// GDBRemoteCommunication constructor
59
60// Destructor
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
72char 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
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
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
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
115 llvm::StringRef notify_type, std::deque<std::string> &queue,
116 llvm::StringRef payload) {
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
138 bool skip_ack) {
139 if (IsConnected()) {
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
190 } else {
191 LLDB_LOGF(log, "error: failed to send packet: %.*s", (int)packet_length,
192 packet_data);
193 }
194 }
196}
197
210
213 Timeout<std::micro> timeout,
214 bool sync_on_timeout) {
215 using ResponseType = StringExtractorGDBRemote::ResponseType;
216
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
231 Timeout<std::micro> timeout,
232 bool sync_on_timeout) {
233 uint8_t buffer[8192];
235
237
238 // Check for a packet from our cache first without trying any reading...
239 if (CheckForPacket(nullptr, 0, packet) != PacketType::Invalid)
241
242 bool timed_out = false;
243 bool disconnected = false;
244 while (IsConnected() && !timed_out) {
246 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
247
249 "Read(buffer, sizeof(buffer), timeout = {0}, "
250 "status = {1}, error = {2}) => bytes_read = {3}",
252 error, bytes_read);
253
254 if (bytes_read > 0) {
255 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
257 } else {
258 switch (status) {
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
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...
344 }
345 } else {
346 disconnected = true;
347 Disconnect();
348 }
349 } else {
350 timed_out = true;
351 }
352 break;
354 // printf ("status = success but error = %s\n",
355 // error.AsCString("<invalid>"));
356 break;
357
362 disconnected = true;
363 Disconnect();
364 break;
365 }
366 }
367 }
368 packet.Clear();
369 if (disconnected)
371 if (timed_out)
373 else
375}
376
379
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
509 compression_algorithm compression_type;
511 compression_type = COMPRESSION_LZFSE;
513 compression_type = COMPRESSION_ZLIB;
515 compression_type = COMPRESSION_LZ4_RAW;
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;
526 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
528 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
530 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
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 &&
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
606GDBRemoteCommunication::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
612
613 if (src && src_len > 0) {
614 if (log && log->GetVerbose()) {
615 LLDB_LOGF(log, "GDBRemoteCommunication::%s adding %u bytes: %.*s",
616 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
617 }
618 m_bytes.append((const char *)src, src_len);
619 }
620
621 bool isNotifyPacket = false;
622
623 // Parse up the packets into gdb remote packets
624 if (!m_bytes.empty()) {
625 // end_idx must be one past the last valid packet byte. Start it off with
626 // an invalid value that is the same as the current index.
627 size_t content_start = 0;
628 size_t content_length = 0;
629 size_t total_length = 0;
630 size_t checksum_idx = std::string::npos;
631
632 // Size of packet before it is decompressed, for logging purposes
633 size_t original_packet_size = m_bytes.size();
634 if (CompressionIsEnabled()) {
635 if (!DecompressPacket()) {
636 packet.Clear();
638 }
639 }
640
641 switch (m_bytes[0]) {
642 case '+': // Look for ack
643 case '-': // Look for cancel
644 case '\x03': // ^C to halt target
645 content_length = total_length = 1; // The command is one byte long...
646 break;
647
648 case '%': // Async notify packet
649 isNotifyPacket = true;
650 [[fallthrough]];
651
652 case '$':
653 // Look for a standard gdb packet?
654 {
655 size_t hash_pos = m_bytes.find('#');
656 if (hash_pos != std::string::npos) {
657 if (hash_pos + 2 < m_bytes.size()) {
658 checksum_idx = hash_pos + 1;
659 // Skip the dollar sign
660 content_start = 1;
661 // Don't include the # in the content or the $ in the content
662 // length
663 content_length = hash_pos - 1;
664
665 total_length =
666 hash_pos + 3; // Skip the # and the two hex checksum bytes
667 } else {
668 // Checksum bytes aren't all here yet
669 content_length = std::string::npos;
670 }
671 }
672 }
673 break;
674
675 default: {
676 // We have an unexpected byte and we need to flush all bad data that is
677 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
678 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
679 // header) or of course, the end of the data in m_bytes...
680 const size_t bytes_len = m_bytes.size();
681 bool done = false;
682 uint32_t idx;
683 for (idx = 1; !done && idx < bytes_len; ++idx) {
684 switch (m_bytes[idx]) {
685 case '+':
686 case '-':
687 case '\x03':
688 case '%':
689 case '$':
690 done = true;
691 break;
692
693 default:
694 break;
695 }
696 }
697 LLDB_LOGF(log, "GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
698 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
699 m_bytes.erase(0, idx - 1);
700 } break;
701 }
702
703 if (content_length == std::string::npos) {
704 packet.Clear();
706 } else if (total_length > 0) {
707
708 // We have a valid packet...
709 assert(content_length <= m_bytes.size());
710 assert(total_length <= m_bytes.size());
711 assert(content_length <= total_length);
712 size_t content_end = content_start + content_length;
713
714 bool success = true;
715 if (log) {
716 // If logging was just enabled and we have history, then dump out what
717 // we have to the log so we get the historical context. The Dump() call
718 // that logs all of the packet will set a boolean so that we don't dump
719 // this more than once
720 if (!m_history.DidDumpToLog())
721 m_history.Dump(log);
722
723 bool binary = false;
724 // Only detect binary for packets that start with a '$' and have a
725 // '#CC' checksum
726 if (m_bytes[0] == '$' && total_length > 4) {
727 for (size_t i = 0; !binary && i < total_length; ++i) {
728 unsigned char c = m_bytes[i];
729 if (!llvm::isPrint(c) && !llvm::isSpace(c)) {
730 binary = true;
731 }
732 }
733 }
734 if (binary) {
735 StreamString strm;
736 // Packet header...
738 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
739 (uint64_t)original_packet_size, (uint64_t)total_length,
740 m_bytes[0]);
741 else
742 strm.Printf("<%4" PRIu64 "> read packet: %c",
743 (uint64_t)total_length, m_bytes[0]);
744 for (size_t i = content_start; i < content_end; ++i) {
745 // Remove binary escaped bytes when displaying the packet...
746 const char ch = m_bytes[i];
747 if (ch == 0x7d) {
748 // 0x7d is the escape character. The next character is to be
749 // XOR'd with 0x20.
750 const char escapee = m_bytes[++i] ^ 0x20;
751 strm.Printf("%2.2x", escapee);
752 } else {
753 strm.Printf("%2.2x", (uint8_t)ch);
754 }
755 }
756 // Packet footer...
757 strm.Printf("%c%c%c", m_bytes[total_length - 3],
758 m_bytes[total_length - 2], m_bytes[total_length - 1]);
759 log->PutString(strm.GetString());
760 } else {
762 LLDB_LOGF(log, "<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
763 (uint64_t)original_packet_size, (uint64_t)total_length,
764 (int)(total_length), m_bytes.c_str());
765 else
766 LLDB_LOGF(log, "<%4" PRIu64 "> read packet: %.*s",
767 (uint64_t)total_length, (int)(total_length),
768 m_bytes.c_str());
769 }
770 }
771
772 m_history.AddPacket(m_bytes, total_length,
774
775 // Copy the packet from m_bytes to packet_str expanding the run-length
776 // encoding in the process.
777 auto maybe_packet_str =
778 ExpandRLE(m_bytes.substr(content_start, content_end - content_start));
779 if (!maybe_packet_str) {
780 m_bytes.erase(0, total_length);
781 packet.Clear();
783 }
784 packet = StringExtractorGDBRemote(*maybe_packet_str);
785
786 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
787 assert(checksum_idx < m_bytes.size());
788 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
789 ::isxdigit(m_bytes[checksum_idx + 1])) {
790 if (GetSendAcks()) {
791 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
792 char packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
793 char actual_checksum = CalculcateChecksum(
794 llvm::StringRef(m_bytes).slice(content_start, content_end));
795 success = packet_checksum == actual_checksum;
796 if (!success) {
797 LLDB_LOGF(log,
798 "error: checksum mismatch: %.*s expected 0x%2.2x, "
799 "got 0x%2.2x",
800 (int)(total_length), m_bytes.c_str(),
801 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
802 }
803 // Send the ack or nack if needed
804 if (!success)
805 SendNack();
806 else
807 SendAck();
808 }
809 } else {
810 success = false;
811 LLDB_LOGF(log, "error: invalid checksum in packet: '%s'\n",
812 m_bytes.c_str());
813 }
814 }
815
816 m_bytes.erase(0, total_length);
817 packet.SetFilePos(0);
818
819 if (isNotifyPacket)
821 else
823 }
824 }
825 packet.Clear();
827}
828
830 std::variant<llvm::StringRef, shared_fd_t> comm,
831 ProcessLaunchInfo &launch_info, const Args *inferior_args) {
833
834 Args &debugserver_args = launch_info.GetArguments();
835
836#if !defined(__APPLE__)
837 // First argument to lldb-server must be mode in which to run.
838 debugserver_args.AppendArgument("gdbserver");
839#endif
840
841 // use native registers, not the GDB registers
842 debugserver_args.AppendArgument("--native-regs");
843
844 if (launch_info.GetLaunchInSeparateProcessGroup())
845 debugserver_args.AppendArgument("--setsid");
846
847 llvm::SmallString<128> named_pipe_path;
848 // socket_pipe is used by debug server to communicate back either
849 // TCP port or domain socket name which it listens on. However, we're not
850 // interested in the actualy value here.
851 // The only reason for using the pipe is to serve as a synchronization point -
852 // once data is written to the pipe, debug server is up and running.
853 Pipe socket_pipe;
854
855 // If a url is supplied then use it
856 if (shared_fd_t *comm_fd = std::get_if<shared_fd_t>(&comm)) {
857 LLDB_LOG(log, "debugserver communicates over fd {0}", comm_fd);
858 assert(*comm_fd != SharedSocket::kInvalidFD);
859 debugserver_args.AppendArgument(llvm::formatv("--fd={0}", *comm_fd).str());
860 // Send "comm_fd" down to the inferior so it can use it to communicate back
861 // with this process.
862 launch_info.AppendDuplicateFileAction(*comm_fd, *comm_fd);
863 } else {
864 llvm::StringRef url = std::get<llvm::StringRef>(comm);
865 LLDB_LOG(log, "debugserver listens on: {0}", url);
866 debugserver_args.AppendArgument(url);
867
868#if defined(__APPLE__)
869 // Using a named pipe as debugserver does not support --pipe.
870 Status error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
871 named_pipe_path);
872 if (error.Fail()) {
873 LLDB_LOG(log, "named pipe creation failed: {0}", error);
874 return error;
875 }
876 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
877 debugserver_args.AppendArgument(named_pipe_path);
878#else
879 // Using an unnamed pipe as it's simpler.
880 Status error = socket_pipe.CreateNew();
881 if (error.Fail()) {
882 LLDB_LOG(log, "unnamed pipe creation failed: {0}", error);
883 return error;
884 }
885 pipe_t write = socket_pipe.GetWritePipe();
886 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
887 debugserver_args.AppendArgument(llvm::to_string(write));
888 launch_info.AppendDuplicateFileAction(write, write);
889#endif
890 }
891
893 std::string env_debugserver_log_file =
894 host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
895 if (!env_debugserver_log_file.empty()) {
896 debugserver_args.AppendArgument(
897 llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
898 }
899
900#if defined(__APPLE__)
901 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
902 if (env_debugserver_log_flags) {
903 debugserver_args.AppendArgument(
904 llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
905 }
906#else
907 std::string env_debugserver_log_channels =
908 host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
909 if (!env_debugserver_log_channels.empty()) {
910 debugserver_args.AppendArgument(
911 llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
912 .str());
913 }
914#endif
915
916 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
917 // env var doesn't come back.
918 uint32_t env_var_index = 1;
919 bool has_env_var;
920 do {
921 char env_var_name[64];
922 snprintf(env_var_name, sizeof(env_var_name),
923 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
924 std::string extra_arg = host_env.lookup(env_var_name);
925 has_env_var = !extra_arg.empty();
926
927 if (has_env_var) {
928 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
929 LLDB_LOGF(log,
930 "GDBRemoteCommunication::%s adding env var %s contents "
931 "to stub command line (%s)",
932 __FUNCTION__, env_var_name, extra_arg.c_str());
933 }
934 } while (has_env_var);
935
936 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
937 debugserver_args.AppendArgument(llvm::StringRef("--"));
938 debugserver_args.AppendArguments(*inferior_args);
939 }
940
941 // Copy the current environment to the gdbserver/debugserver instance
942 launch_info.GetEnvironment() = host_env;
943
944 // Close STDIN, STDOUT and STDERR.
945 launch_info.AppendCloseFileAction(STDIN_FILENO);
946 launch_info.AppendCloseFileAction(STDOUT_FILENO);
947 launch_info.AppendCloseFileAction(STDERR_FILENO);
948
949 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
950 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
951 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
952 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
953
954 if (log) {
955 StreamString string_stream;
956 Platform *const platform = nullptr;
957 launch_info.Dump(string_stream, platform);
958 LLDB_LOG(log, "launch info for gdb-remote stub:\n{0}",
959 string_stream.GetData());
960 }
961 if (Status error = Host::LaunchProcess(launch_info); error.Fail()) {
962 LLDB_LOG(log, "launch failed: {0}", error);
963 return error;
964 }
965
966 if (std::holds_alternative<shared_fd_t>(comm))
967 return Status();
968
970 if (named_pipe_path.size() > 0) {
971 error = socket_pipe.OpenAsReader(named_pipe_path);
972 if (error.Fail()) {
973 LLDB_LOG(log, "failed to open named pipe {0} for reading: {1}",
974 named_pipe_path, error);
975 }
976 }
977
978 if (socket_pipe.CanWrite())
979 socket_pipe.CloseWriteFileDescriptor();
980 assert(socket_pipe.CanRead());
981
982 // Read data from the pipe -- and ignore it (see comment above).
983 while (error.Success()) {
984 char buf[10];
985 if (llvm::Expected<size_t> num_bytes =
986 socket_pipe.Read(buf, std::size(buf), std::chrono::seconds(10))) {
987 if (*num_bytes == 0)
988 break;
989 } else {
990 error = Status::FromError(num_bytes.takeError());
991 }
992 }
993 if (error.Fail()) {
994 LLDB_LOG(log, "failed to synchronize on pipe {0}: {1}", named_pipe_path,
995 error);
996 }
997 socket_pipe.Close();
998
999 if (named_pipe_path.size() > 0) {
1000 if (Status err = socket_pipe.Delete(named_pipe_path); err.Fail())
1001 LLDB_LOG(log, "failed to delete pipe {0}: {1}", named_pipe_path, err);
1002 }
1003
1004 return error;
1005}
1006
1008
1010 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
1011 : m_gdb_comm(gdb_comm), m_saved_timeout(0), m_timeout_modified(false) {
1012 auto curr_timeout = gdb_comm.GetPacketTimeout();
1013 // Only update the timeout if the timeout is greater than the current
1014 // timeout. If the current timeout is larger, then just use that.
1015 if (curr_timeout < timeout) {
1016 m_timeout_modified = true;
1017 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1018 }
1019}
1020
1022 // Only restore the timeout if we set it in the constructor.
1024 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1025}
1026
1027void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1028 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1029 StringRef Style) {
1031
1032 switch (result) {
1034 Stream << "Success";
1035 break;
1037 Stream << "ErrorSendFailed";
1038 break;
1040 Stream << "ErrorSendAck";
1041 break;
1043 Stream << "ErrorReplyFailed";
1044 break;
1046 Stream << "ErrorReplyTimeout";
1047 break;
1049 Stream << "ErrorReplyInvalid";
1050 break;
1052 Stream << "ErrorReplyAck";
1053 break;
1055 Stream << "ErrorDisconnected";
1056 break;
1058 Stream << "ErrorNoSequenceLock";
1059 break;
1060 }
1061}
1062
1063std::optional<std::string>
1065 // Reserve enough byte for the most common case (no RLE used).
1066 std::string decoded;
1067 decoded.reserve(packet.size());
1068 for (std::string::const_iterator c = packet.begin(); c != packet.end(); ++c) {
1069 if (*c == '*') {
1070 if (decoded.empty())
1071 return std::nullopt;
1072 // '*' indicates RLE. Next character will give us the repeat count and
1073 // previous character is what is to be repeated.
1074 char char_to_repeat = decoded.back();
1075 // Number of time the previous character is repeated.
1076 if (++c == packet.end())
1077 return std::nullopt;
1078 int repeat_count = *c + 3 - ' ';
1079 // We have the char_to_repeat and repeat_count. Now push it in the
1080 // packet.
1081 for (int i = 0; i < repeat_count; ++i)
1082 decoded.push_back(char_to_repeat);
1083 } else if (*c == 0x7d) {
1084 // 0x7d is the escape character. The next character is to be XOR'd with
1085 // 0x20.
1086 if (++c == packet.end())
1087 return std::nullopt;
1088 char escapee = *c ^ 0x20;
1089 decoded.push_back(escapee);
1090 } else {
1091 decoded.push_back(*c);
1092 }
1093 }
1094 return decoded;
1095}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:369
#define LLDB_LOGF(log,...)
Definition Log.h:383
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:376
void SetFilePos(uint32_t idx)
llvm::StringRef GetStringRef() const
A command line argument class.
Definition Args.h:33
void AppendArguments(const Args &rhs)
Definition Args.cpp:307
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition Args.cpp:332
virtual size_t Read(void *dst, size_t dst_len, const Timeout< std::micro > &timeout, lldb::ConnectionStatus &status, Status *error_ptr)
Read bytes from the current connection.
bool IsConnected() const
Check if the connection is valid.
size_t WriteAll(const void *src, size_t src_len, lldb::ConnectionStatus &status, Status *error_ptr)
Repeatedly attempt writing until either src_len bytes are written or a permanent failure occurs.
Communication()
Construct the Communication object.
virtual lldb::ConnectionStatus Disconnect(Status *error_ptr=nullptr)
Disconnect the communications connection if one is currently connected.
static std::string ConnectionStatusAsString(lldb::ConnectionStatus status)
static Status LaunchProcess(ProcessLaunchInfo &launch_info)
Launch the process specified in launch_info.
static Environment GetEnvironment()
bool GetVerbose() const
Definition Log.cpp:326
void PutString(llvm::StringRef str)
Definition Log.cpp:147
lldb::pipe_t GetWritePipe() const override
Definition PipePosix.h:49
void CloseWriteFileDescriptor() override
Status CreateNew() override
Definition PipePosix.cpp:82
bool CanWrite() const override
bool CanRead() const override
void Close() override
llvm::Expected< size_t > Read(void *buf, size_t size, const Timeout< std::micro > &timeout=std::nullopt) override
Status Delete(llvm::StringRef name) override
Status OpenAsReader(llvm::StringRef name) override
Status CreateWithUniqueName(llvm::StringRef prefix, llvm::SmallVectorImpl< char > &name) override
A plug-in interface definition class for debug platform that includes many platform abilities such as...
Definition Platform.h:79
void Dump(Stream &s, Platform *platform) const
Environment & GetEnvironment()
Definition ProcessInfo.h:88
bool AppendSuppressFileAction(int fd, bool read, bool write)
bool AppendDuplicateFileAction(int fd, int dup_fd)
bool Execute(llvm::StringRef string, llvm::SmallVectorImpl< llvm::StringRef > *matches=nullptr) const
Execute a regular expression match using the compiled regular expression that is already in this obje...
static const shared_fd_t kInvalidFD
Definition Socket.h:50
An error handling class.
Definition Status.h:118
bool Fail() const
Test for error condition.
Definition Status.cpp:293
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
Definition Stream.h:112
size_t size_t PutHex8(uint8_t uvalue)
Append an uint8_t value in the hexadecimal format to the stream.
Definition Stream.cpp:275
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutChar(char ch)
Definition Stream.cpp:131
ScopedTimeout(GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
PacketResult ReadPacket(StringExtractorGDBRemote &response, Timeout< std::micro > timeout, bool sync_on_timeout)
PacketResult SendNotificationPacketNoLock(llvm::StringRef notify_type, std::deque< std::string > &queue, llvm::StringRef payload)
PacketResult WaitForPacketNoLock(StringExtractorGDBRemote &response, Timeout< std::micro > timeout, bool sync_on_timeout)
PacketResult SendRawPacketNoLock(llvm::StringRef payload, bool skip_ack=false)
static Status StartDebugserverProcess(std::variant< llvm::StringRef, shared_fd_t > comm, ProcessLaunchInfo &launch_info, const Args *inferior_args)
static std::optional< std::string > ExpandRLE(std::string)
Expand GDB run-length encoding.
PacketType CheckForPacket(const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
NativeSocket shared_fd_t
Definition Socket.h:42
PipePosix Pipe
Definition Pipe.h:20
int pipe_t
Definition lldb-types.h:64
ConnectionStatus
Connection Status Types.
@ eConnectionStatusError
Check GetError() for details.
@ eConnectionStatusInterrupted
Interrupted read.
@ eConnectionStatusTimedOut
Request timed out.
@ eConnectionStatusEndOfFile
End-of-file encountered.
@ eConnectionStatusSuccess
Success.
@ eConnectionStatusLostConnection
Lost connection while connected to a valid connection.
@ eConnectionStatusNoConnection
No connection.