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 if (CheckForPacket(nullptr, 0, packet) != PacketType::Invalid)
247
248 bool timed_out = false;
249 bool disconnected = false;
250 while (IsConnected() && !timed_out) {
252 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
253
255 "Read(buffer, sizeof(buffer), timeout = {0}, "
256 "status = {1}, error = {2}) => bytes_read = {3}",
258 error, bytes_read);
259
260 if (bytes_read > 0) {
261 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
263 } else {
264 switch (status) {
267 if (sync_on_timeout) {
268 /// Sync the remote GDB server and make sure we get a response that
269 /// corresponds to what we send.
270 ///
271 /// Sends a "qEcho" packet and makes sure it gets the exact packet
272 /// echoed back. If the qEcho packet isn't supported, we send a qC
273 /// packet and make sure we get a valid thread ID back. We use the
274 /// "qC" packet since its response if very unique: is responds with
275 /// "QC%x" where %x is the thread ID of the current thread. This
276 /// makes the response unique enough from other packet responses to
277 /// ensure we are back on track.
278 ///
279 /// This packet is needed after we time out sending a packet so we
280 /// can ensure that we are getting the response for the packet we
281 /// are sending. There are no sequence IDs in the GDB remote
282 /// protocol (there used to be, but they are not supported anymore)
283 /// so if you timeout sending packet "abc", you might then send
284 /// packet "cde" and get the response for the previous "abc" packet.
285 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
286 /// many responses for packets can look like responses for other
287 /// packets. So if we timeout, we need to ensure that we can get
288 /// back on track. If we can't get back on track, we must
289 /// disconnect.
290 bool sync_success = false;
291 bool got_actual_response = false;
292 // We timed out, we need to sync back up with the
293 char echo_packet[32];
294 int echo_packet_len = 0;
295 RegularExpression response_regex;
296
298 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
299 "qEcho:%u", ++m_echo_number);
300 std::string regex_str = "^";
301 regex_str += echo_packet;
302 regex_str += "$";
303 response_regex = RegularExpression(regex_str);
304 } else {
305 echo_packet_len =
306 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
307 response_regex =
308 RegularExpression(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
309 }
310
311 PacketResult echo_packet_result =
312 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
313 if (echo_packet_result == PacketResult::Success) {
314 const uint32_t max_retries = 3;
315 uint32_t successful_responses = 0;
316 for (uint32_t i = 0; i < max_retries; ++i) {
317 StringExtractorGDBRemote echo_response;
318 echo_packet_result =
319 WaitForPacketNoLock(echo_response, timeout, false);
320 if (echo_packet_result == PacketResult::Success) {
321 ++successful_responses;
322 if (response_regex.Execute(echo_response.GetStringRef())) {
323 sync_success = true;
324 break;
325 } else if (successful_responses == 1) {
326 // We got something else back as the first successful
327 // response, it probably is the response to the packet we
328 // actually wanted, so copy it over if this is the first
329 // success and continue to try to get the qEcho response
330 packet = echo_response;
331 got_actual_response = true;
332 }
333 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
334 continue; // Packet timed out, continue waiting for a response
335 else
336 break; // Something else went wrong getting the packet back, we
337 // failed and are done trying
338 }
339 }
340
341 // We weren't able to sync back up with the server, we must abort
342 // otherwise all responses might not be from the right packets...
343 if (sync_success) {
344 // We timed out, but were able to recover
345 if (got_actual_response) {
346 // We initially timed out, but we did get a response that came in
347 // before the successful reply to our qEcho packet, so lets say
348 // everything is fine...
350 }
351 } else {
352 disconnected = true;
353 Disconnect();
354 }
355 } else {
356 timed_out = true;
357 }
358 break;
360 // printf ("status = success but error = %s\n",
361 // error.AsCString("<invalid>"));
362 break;
363
368 disconnected = true;
369 Disconnect();
370 break;
371 }
372 }
373 }
374 packet.Clear();
375 if (disconnected)
377 if (timed_out)
379 else
381}
382
385
387 return true;
388
389 size_t pkt_size = m_bytes.size();
390
391 // Smallest possible compressed packet is $N#00 - an uncompressed empty
392 // reply, most commonly indicating an unsupported packet. Anything less than
393 // 5 characters, it's definitely not a compressed packet.
394 if (pkt_size < 5)
395 return true;
396
397 if (m_bytes[0] != '$' && m_bytes[0] != '%')
398 return true;
399 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
400 return true;
401
402 size_t hash_mark_idx = m_bytes.find('#');
403 if (hash_mark_idx == std::string::npos)
404 return true;
405 if (hash_mark_idx + 2 >= m_bytes.size())
406 return true;
407
408 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
409 !::isxdigit(m_bytes[hash_mark_idx + 2]))
410 return true;
411
412 size_t content_length =
413 pkt_size -
414 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
415 size_t content_start = 2; // The first character of the
416 // compressed/not-compressed text of the packet
417 size_t checksum_idx =
418 hash_mark_idx +
419 1; // The first character of the two hex checksum characters
420
421 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
422 // multiple packets. size_of_first_packet is the size of the initial packet
423 // which we'll replace with the decompressed version of, leaving the rest of
424 // m_bytes unmodified.
425 size_t size_of_first_packet = hash_mark_idx + 3;
426
427 // Compressed packets ("$C") start with a base10 number which is the size of
428 // the uncompressed payload, then a : and then the compressed data. e.g.
429 // $C1024:<binary>#00 Update content_start and content_length to only include
430 // the <binary> part of the packet.
431
432 uint64_t decompressed_bufsize = ULONG_MAX;
433 if (m_bytes[1] == 'C') {
434 size_t i = content_start;
435 while (i < hash_mark_idx && isdigit(m_bytes[i]))
436 i++;
437 if (i < hash_mark_idx && m_bytes[i] == ':') {
438 i++;
439 content_start = i;
440 content_length = hash_mark_idx - content_start;
441 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
442 errno = 0;
443 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), nullptr, 10);
444 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
445 m_bytes.erase(0, size_of_first_packet);
446 return false;
447 }
448 }
449 }
450
451 if (GetSendAcks()) {
452 char packet_checksum_cstr[3];
453 packet_checksum_cstr[0] = m_bytes[checksum_idx];
454 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
455 packet_checksum_cstr[2] = '\0';
456 long packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
457
458 long actual_checksum = CalculcateChecksum(
459 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
460 bool success = packet_checksum == actual_checksum;
461 if (!success) {
462 LLDB_LOGF(log,
463 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
464 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
465 (uint8_t)actual_checksum);
466 }
467 // Send the ack or nack if needed
468 if (!success) {
469 SendNack();
470 m_bytes.erase(0, size_of_first_packet);
471 return false;
472 } else {
473 SendAck();
474 }
475 }
476
477 if (m_bytes[1] == 'N') {
478 // This packet was not compressed -- delete the 'N' character at the start
479 // and the packet may be processed as-is.
480 m_bytes.erase(1, 1);
481 return true;
482 }
483
484 // Reverse the gdb-remote binary escaping that was done to the compressed
485 // text to guard characters like '$', '#', '}', etc.
486 std::vector<uint8_t> unescaped_content;
487 unescaped_content.reserve(content_length);
488 size_t i = content_start;
489 while (i < hash_mark_idx) {
490 if (m_bytes[i] == '}') {
491 i++;
492 unescaped_content.push_back(m_bytes[i] ^ 0x20);
493 } else {
494 unescaped_content.push_back(m_bytes[i]);
495 }
496 i++;
497 }
498
499 uint8_t *decompressed_buffer = nullptr;
500 size_t decompressed_bytes = 0;
501
502 if (decompressed_bufsize != ULONG_MAX) {
503 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
504 if (decompressed_buffer == nullptr) {
505 m_bytes.erase(0, size_of_first_packet);
506 return false;
507 }
508 }
509
510#if HAVE_LIBCOMPRESSION
515 compression_algorithm compression_type;
517 compression_type = COMPRESSION_LZFSE;
519 compression_type = COMPRESSION_ZLIB;
521 compression_type = COMPRESSION_LZ4_RAW;
523 compression_type = COMPRESSION_LZMA;
524
525 if (m_decompression_scratch_type != m_compression_type) {
526 if (m_decompression_scratch) {
527 free (m_decompression_scratch);
528 m_decompression_scratch = nullptr;
529 }
530 size_t scratchbuf_size = 0;
532 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
534 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
536 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
538 scratchbuf_size =
539 compression_decode_scratch_buffer_size(COMPRESSION_LZMA);
540 if (scratchbuf_size > 0) {
541 m_decompression_scratch = (void*) malloc (scratchbuf_size);
542 m_decompression_scratch_type = m_compression_type;
543 }
544 }
545
546 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
547 decompressed_bytes = compression_decode_buffer(
548 decompressed_buffer, decompressed_bufsize,
549 (uint8_t *)unescaped_content.data(), unescaped_content.size(),
550 m_decompression_scratch, compression_type);
551 }
552 }
553#endif
554
555#if LLVM_ENABLE_ZLIB
556 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
557 decompressed_buffer != nullptr &&
559 z_stream stream;
560 memset(&stream, 0, sizeof(z_stream));
561 stream.next_in = (Bytef *)unescaped_content.data();
562 stream.avail_in = (uInt)unescaped_content.size();
563 stream.total_in = 0;
564 stream.next_out = (Bytef *)decompressed_buffer;
565 stream.avail_out = decompressed_bufsize;
566 stream.total_out = 0;
567 stream.zalloc = Z_NULL;
568 stream.zfree = Z_NULL;
569 stream.opaque = Z_NULL;
570
571 if (inflateInit2(&stream, -15) == Z_OK) {
572 int status = inflate(&stream, Z_NO_FLUSH);
573 inflateEnd(&stream);
574 if (status == Z_STREAM_END) {
575 decompressed_bytes = stream.total_out;
576 }
577 }
578 }
579#endif
580
581 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
582 if (decompressed_buffer)
583 free(decompressed_buffer);
584 m_bytes.erase(0, size_of_first_packet);
585 return false;
586 }
587
588 std::string new_packet;
589 new_packet.reserve(decompressed_bytes + 6);
590 new_packet.push_back(m_bytes[0]);
591 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
592 new_packet.push_back('#');
593 if (GetSendAcks()) {
594 uint8_t decompressed_checksum = CalculcateChecksum(
595 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
596 char decompressed_checksum_str[3];
597 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
598 new_packet.append(decompressed_checksum_str);
599 } else {
600 new_packet.push_back('0');
601 new_packet.push_back('0');
602 }
603
604 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
605 new_packet.size());
606
607 free(decompressed_buffer);
608 return true;
609}
610
611// `content` is the body between '$' and '#', `payload` is the full raw packet
612// (e.g. "$body#CC");
613static void AddToLog(llvm::StringRef content, llvm::StringRef payload,
614 uint64_t original_packet_size,
616 bool compression_enabled) {
618 if (!log)
619 return;
620
621 // If logging was just enabled, flush the history. m_history has a flag
622 // ensuring this is done only once.
623 if (!history.DidDumpToLog())
624 history.Dump(log);
625
626 bool binary = false;
627 // Detect binary for packets starting with a '$' and with a '#CC' checksum.
628 if (payload.front() == '$' && payload.size() > 4)
629 for (char c : payload)
630 if (!llvm::isPrint(c) && !llvm::isSpace(c)) {
631 binary = true;
632 break;
633 }
634
635 uint64_t total_length = payload.size();
636 if (!binary) {
637 if (compression_enabled)
638 LLDB_LOGF(log, "<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
639 original_packet_size, total_length, (int)(total_length),
640 payload.data());
641 else
642 LLDB_LOGF(log, "<%4" PRIu64 "> read packet: %.*s", total_length,
643 (int)(total_length), payload.data());
644 return;
645 }
646
647 StreamString strm;
648 // Packet header.
649 if (compression_enabled)
650 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
651 original_packet_size, total_length, payload[0]);
652 else
653 strm.Printf("<%4" PRIu64 "> read packet: %c", total_length, payload[0]);
654 for (size_t i = 0; i < content.size(); ++i) {
655 // Remove binary escaped bytes when displaying the packet.
656 const char ch = content[i];
657 if (ch == 0x7d) {
658 // Escape character: the next character is to be XOR'd with 0x20.
659 const char escapee = content[++i] ^ 0x20;
660 strm.Printf("%2.2x", escapee);
661 } else {
662 strm.Printf("%2.2x", (uint8_t)ch);
663 }
664 }
665 // Packet footer.
666 strm.Printf("%c%c%c", payload[total_length - 3], payload[total_length - 2],
667 payload[total_length - 1]);
668 log->PutString(strm.GetString());
669}
670
672GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
673 StringExtractorGDBRemote &packet) {
674 // Put the packet data into the buffer in a thread safe fashion
675 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
676
678
679 if (src && src_len > 0) {
680 if (log && log->GetVerbose()) {
681 LLDB_LOGF(log, "GDBRemoteCommunication::%s adding %u bytes: %.*s",
682 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
683 }
684 m_bytes.append((const char *)src, src_len);
685 }
686
687 bool isNotifyPacket = false;
688
689 // Parse up the packets into gdb remote packets
690 if (!m_bytes.empty()) {
691 // end_idx must be one past the last valid packet byte. Start it off with
692 // an invalid value that is the same as the current index.
693 size_t content_start = 0;
694 size_t content_length = 0;
695 size_t total_length = 0;
696 size_t checksum_idx = std::string::npos;
697
698 // Size of packet before it is decompressed, for logging purposes
699 size_t original_packet_size = m_bytes.size();
700 if (CompressionIsEnabled()) {
701 if (!DecompressPacket()) {
702 packet.Clear();
704 }
705 }
706
707 switch (m_bytes[0]) {
708 case '+': // Look for ack
709 case '-': // Look for cancel
710 case '\x03': // ^C to halt target
711 content_length = total_length = 1; // The command is one byte long...
712 break;
713
714 case '%': // Async notify packet
715 isNotifyPacket = true;
716 [[fallthrough]];
717
718 case '$':
719 // Look for a standard gdb packet?
720 {
721 size_t hash_pos = m_bytes.find('#');
722 if (hash_pos != std::string::npos) {
723 if (hash_pos + 2 < m_bytes.size()) {
724 checksum_idx = hash_pos + 1;
725 // Skip the dollar sign
726 content_start = 1;
727 // Don't include the # in the content or the $ in the content
728 // length
729 content_length = hash_pos - 1;
730
731 total_length =
732 hash_pos + 3; // Skip the # and the two hex checksum bytes
733 } else {
734 // Checksum bytes aren't all here yet
735 content_length = std::string::npos;
736 }
737 }
738 }
739 break;
740
741 default: {
742 // We have an unexpected byte and we need to flush all bad data that is
743 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
744 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
745 // header) or of course, the end of the data in m_bytes...
746 const size_t bytes_len = m_bytes.size();
747 bool done = false;
748 uint32_t idx;
749 for (idx = 1; !done && idx < bytes_len; ++idx) {
750 switch (m_bytes[idx]) {
751 case '+':
752 case '-':
753 case '\x03':
754 case '%':
755 case '$':
756 done = true;
757 break;
758
759 default:
760 break;
761 }
762 }
763 LLDB_LOGF(log, "GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
764 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
765 m_bytes.erase(0, idx - 1);
766 } break;
767 }
768
769 if (content_length == std::string::npos) {
770 packet.Clear();
772 } else if (total_length > 0) {
773
774 // We have a valid packet...
775 assert(content_length <= m_bytes.size());
776 assert(total_length <= m_bytes.size());
777 assert(content_length <= total_length);
778 size_t content_end = content_start + content_length;
779
780 AddToLog(llvm::StringRef(m_bytes).slice(content_start, content_end),
781 llvm::StringRef(m_bytes).take_front(total_length),
782 original_packet_size, m_history, CompressionIsEnabled());
783
784 m_history.AddPacket(m_bytes, total_length,
786
787 // Copy the packet from m_bytes to packet_str expanding the run-length
788 // encoding in the process.
789 auto maybe_packet_str =
790 ExpandRLE(m_bytes.substr(content_start, content_end - content_start));
791 if (!maybe_packet_str) {
792 m_bytes.erase(0, total_length);
793 packet.Clear();
795 }
796 packet = StringExtractorGDBRemote(*maybe_packet_str);
797
798 bool success = true;
799 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
800 assert(checksum_idx < m_bytes.size());
801 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
802 ::isxdigit(m_bytes[checksum_idx + 1])) {
803 if (GetSendAcks()) {
804 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
805 char packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
806 char actual_checksum = CalculcateChecksum(
807 llvm::StringRef(m_bytes).slice(content_start, content_end));
808 success = packet_checksum == actual_checksum;
809 if (!success) {
810 LLDB_LOGF(log,
811 "error: checksum mismatch: %.*s expected 0x%2.2x, "
812 "got 0x%2.2x",
813 (int)(total_length), m_bytes.c_str(),
814 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
815 }
816 // Send the ack or nack if needed
817 if (!success)
818 SendNack();
819 else
820 SendAck();
821 }
822 } else {
823 success = false;
824 LLDB_LOGF(log, "error: invalid checksum in packet: '%s'\n",
825 m_bytes.c_str());
826 }
827 }
828
829 m_bytes.erase(0, total_length);
830 packet.SetFilePos(0);
831
832 if (isNotifyPacket)
834 else
836 }
837 }
838 packet.Clear();
840}
841
843 std::variant<llvm::StringRef, shared_fd_t> comm,
844 ProcessLaunchInfo &launch_info, const Args *inferior_args) {
846
847 Args &debugserver_args = launch_info.GetArguments();
848
849#if !defined(__APPLE__)
850 // First argument to lldb-server must be mode in which to run.
851 debugserver_args.AppendArgument("gdbserver");
852#endif
853
854 // use native registers, not the GDB registers
855 debugserver_args.AppendArgument("--native-regs");
856
857 if (launch_info.GetLaunchInSeparateProcessGroup())
858 debugserver_args.AppendArgument("--setsid");
859
860 llvm::SmallString<128> named_pipe_path;
861 // socket_pipe is used by debug server to communicate back either
862 // TCP port or domain socket name which it listens on. However, we're not
863 // interested in the actualy value here.
864 // The only reason for using the pipe is to serve as a synchronization point -
865 // once data is written to the pipe, debug server is up and running.
866 Pipe socket_pipe;
867
868 // If a url is supplied then use it
869 if (shared_fd_t *comm_fd = std::get_if<shared_fd_t>(&comm)) {
870 LLDB_LOG(log, "debugserver communicates over fd {0}", comm_fd);
871 assert(*comm_fd != SharedSocket::kInvalidFD);
872 debugserver_args.AppendArgument(llvm::formatv("--fd={0}", *comm_fd).str());
873 // Send "comm_fd" down to the inferior so it can use it to communicate back
874 // with this process.
875 launch_info.AppendDuplicateFileAction(*comm_fd, *comm_fd);
876 } else {
877 llvm::StringRef url = std::get<llvm::StringRef>(comm);
878 LLDB_LOG(log, "debugserver listens on: {0}", url);
879 debugserver_args.AppendArgument(url);
880
881#if defined(__APPLE__)
882 // Using a named pipe as debugserver does not support --pipe.
883 Status error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
884 named_pipe_path);
885 if (error.Fail()) {
886 LLDB_LOG(log, "named pipe creation failed: {0}", error);
887 return error;
888 }
889 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
890 debugserver_args.AppendArgument(named_pipe_path);
891#else
892 // Using an unnamed pipe as it's simpler.
893 Status error = socket_pipe.CreateNew();
894 if (error.Fail()) {
895 LLDB_LOG(log, "unnamed pipe creation failed: {0}", error);
896 return error;
897 }
898 pipe_t write = socket_pipe.GetWritePipe();
899 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
900 debugserver_args.AppendArgument(llvm::to_string(write));
901 launch_info.AppendDuplicateFileAction(write, write);
902#endif
903 }
904
906 std::string env_debugserver_log_file =
907 host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
908 if (!env_debugserver_log_file.empty()) {
909 debugserver_args.AppendArgument(
910 llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
911 }
912
913#if defined(__APPLE__)
914 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
915 if (env_debugserver_log_flags) {
916 debugserver_args.AppendArgument(
917 llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
918 }
919#else
920 std::string env_debugserver_log_channels =
921 host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
922 if (!env_debugserver_log_channels.empty()) {
923 debugserver_args.AppendArgument(
924 llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
925 .str());
926 }
927#endif
928
929 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
930 // env var doesn't come back.
931 uint32_t env_var_index = 1;
932 bool has_env_var;
933 do {
934 char env_var_name[64];
935 snprintf(env_var_name, sizeof(env_var_name),
936 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
937 std::string extra_arg = host_env.lookup(env_var_name);
938 has_env_var = !extra_arg.empty();
939
940 if (has_env_var) {
941 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
942 LLDB_LOGF(log,
943 "GDBRemoteCommunication::%s adding env var %s contents "
944 "to stub command line (%s)",
945 __FUNCTION__, env_var_name, extra_arg.c_str());
946 }
947 } while (has_env_var);
948
949 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
950 debugserver_args.AppendArgument(llvm::StringRef("--"));
951 debugserver_args.AppendArguments(*inferior_args);
952 }
953
954 // Copy the current environment to the gdbserver/debugserver instance
955 launch_info.GetEnvironment() = host_env;
956
957 // Close STDIN, STDOUT and STDERR.
958 launch_info.AppendCloseFileAction(STDIN_FILENO);
959 launch_info.AppendCloseFileAction(STDOUT_FILENO);
960 launch_info.AppendCloseFileAction(STDERR_FILENO);
961
962 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
963 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
964 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
965 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
966
967 if (log) {
968 StreamString string_stream;
969 Platform *const platform = nullptr;
970 launch_info.Dump(string_stream, platform);
971 LLDB_LOG(log, "launch info for gdb-remote stub:\n{0}",
972 string_stream.GetData());
973 }
974 if (Status error = Host::LaunchProcess(launch_info); error.Fail()) {
975 LLDB_LOG(log, "launch failed: {0}", error);
976 return error;
977 }
978
979 if (std::holds_alternative<shared_fd_t>(comm))
980 return Status();
981
983 if (named_pipe_path.size() > 0) {
984 error = socket_pipe.OpenAsReader(named_pipe_path);
985 if (error.Fail()) {
986 LLDB_LOG(log, "failed to open named pipe {0} for reading: {1}",
987 named_pipe_path, error);
988 }
989 }
990
991 if (socket_pipe.CanWrite())
992 socket_pipe.CloseWriteFileDescriptor();
993 assert(socket_pipe.CanRead());
994
995 // Read data from the pipe -- and ignore it (see comment above).
996 while (error.Success()) {
997 char buf[10];
998 if (llvm::Expected<size_t> num_bytes =
999 socket_pipe.Read(buf, std::size(buf), std::chrono::seconds(10))) {
1000 if (*num_bytes == 0)
1001 break;
1002 } else {
1003 error = Status::FromError(num_bytes.takeError());
1004 }
1005 }
1006 if (error.Fail()) {
1007 LLDB_LOG(log, "failed to synchronize on pipe {0}: {1}", named_pipe_path,
1008 error);
1009 }
1010 socket_pipe.Close();
1011
1012 if (named_pipe_path.size() > 0) {
1013 if (Status err = socket_pipe.Delete(named_pipe_path); err.Fail())
1014 LLDB_LOG(log, "failed to delete pipe {0}: {1}", named_pipe_path, err);
1015 }
1016
1017 return error;
1018}
1019
1021
1023 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
1024 : m_gdb_comm(gdb_comm), m_saved_timeout(0), m_timeout_modified(false) {
1025 auto curr_timeout = gdb_comm.GetPacketTimeout();
1026 // Only update the timeout if the timeout is greater than the current
1027 // timeout. If the current timeout is larger, then just use that.
1028 if (curr_timeout < timeout) {
1029 m_timeout_modified = true;
1030 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1031 }
1032}
1033
1035 // Only restore the timeout if we set it in the constructor.
1037 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1038}
1039
1040void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1041 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1042 StringRef Style) {
1044
1045 switch (result) {
1047 Stream << "Success";
1048 break;
1050 Stream << "ErrorSendFailed";
1051 break;
1053 Stream << "ErrorSendAck";
1054 break;
1056 Stream << "ErrorReplyFailed";
1057 break;
1059 Stream << "ErrorReplyTimeout";
1060 break;
1062 Stream << "ErrorReplyInvalid";
1063 break;
1065 Stream << "ErrorReplyAck";
1066 break;
1068 Stream << "ErrorDisconnected";
1069 break;
1071 Stream << "ErrorNoSequenceLock";
1072 break;
1073 }
1074}
1075
1076std::optional<std::string>
1078 // Reserve enough byte for the most common case (no RLE used).
1079 std::string decoded;
1080 decoded.reserve(packet.size());
1081 for (std::string::const_iterator c = packet.begin(); c != packet.end(); ++c) {
1082 if (*c == '*') {
1083 if (decoded.empty())
1084 return std::nullopt;
1085 // '*' indicates RLE. Next character will give us the repeat count and
1086 // previous character is what is to be repeated.
1087 char char_to_repeat = decoded.back();
1088 // Number of time the previous character is repeated.
1089 if (++c == packet.end())
1090 return std::nullopt;
1091 int repeat_count = *c + 3 - ' ';
1092 // We have the char_to_repeat and repeat_count. Now push it in the
1093 // packet.
1094 for (int i = 0; i < repeat_count; ++i)
1095 decoded.push_back(char_to_repeat);
1096 } else if (*c == 0x7d) {
1097 // 0x7d is the escape character. The next character is to be XOR'd with
1098 // 0x20.
1099 if (++c == packet.end())
1100 return std::nullopt;
1101 char escapee = *c ^ 0x20;
1102 decoded.push_back(escapee);
1103 } else {
1104 decoded.push_back(*c);
1105 }
1106 }
1107 return decoded;
1108}
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:364
#define LLDB_LOGF(log,...)
Definition Log.h:378
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:371
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:300
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: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)
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:327
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.