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