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