12#include "lldb/Host/Config.h"
26#include "llvm/ADT/SmallString.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/Config/llvm-config.h"
29#include "llvm/Support/Error.h"
30#include "llvm/Support/ScopedPrinter.h"
37#if HAVE_LIBCOMPRESSION
38#include <compression.h>
52#ifdef LLDB_CONFIGURATION_DEBUG
68#if HAVE_LIBCOMPRESSION
69 if (m_decompression_scratch)
70 free (m_decompression_scratch);
77 for (
char c : payload)
80 return checksum & 255;
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);
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);
100 return bytes_written;
107 packet.
Write(payload.data(), payload.size());
110 std::string packet_str = std::string(packet.
GetString());
117 llvm::StringRef notify_type, std::deque<std::string> &queue,
118 llvm::StringRef payload) {
126 packet.
Write(notify_type.data(), notify_type.size());
128 packet.
Write(payload.data(), payload.size());
134 queue.push_back(payload.str());
142 if (delay.count() > 0)
143 std::this_thread::sleep_for(delay);
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);
152 size_t binary_start_offset = 0;
153 if (strncmp(packet_data,
"$vFile:pwrite:", strlen(
"$vFile:pwrite:")) ==
155 const char *first_comma = strchr(packet_data,
',');
157 const char *second_comma = strchr(first_comma + 1,
',');
159 binary_start_offset = second_comma - packet_data + 1;
170 if (binary_start_offset) {
173 strm.
Printf(
"<%4" PRIu64
"> send packet: %.*s", (uint64_t)bytes_written,
174 (
int)binary_start_offset, packet_data);
177 for (p = (
const uint8_t *)packet_data + binary_start_offset; *p !=
'#';
179 strm.
Printf(
"\\x%2.2x", *p);
181 strm.
Printf(
"%*s", (
int)3, p);
184 LLDB_LOGF(log,
"<%4" PRIu64
"> send packet: %.*s",
185 (uint64_t)bytes_written, (
int)packet_length, packet_data);
188 m_history.AddPacket(packet.str(), packet_length,
191 if (bytes_written == packet_length) {
197 LLDB_LOGF(log,
"error: failed to send packet: %.*s", (
int)packet_length,
220 bool sync_on_timeout) {
238 bool sync_on_timeout) {
239 uint8_t buffer[8192];
252 llvm_unreachable(
"unreachable");
255 bool timed_out =
false;
256 bool disconnected =
false;
259 size_t bytes_read =
Read(buffer,
sizeof(buffer), timeout, status, &
error);
262 "Read(buffer, sizeof(buffer), timeout = {0}, "
263 "status = {1}, error = {2}) => bytes_read = {3}",
267 if (bytes_read > 0) {
275 llvm_unreachable(
"unreachable");
281 if (sync_on_timeout) {
304 bool sync_success =
false;
305 bool got_actual_response =
false;
307 char echo_packet[32];
308 int echo_packet_len = 0;
312 echo_packet_len = ::snprintf(echo_packet,
sizeof(echo_packet),
314 std::string regex_str =
"^";
315 regex_str += echo_packet;
320 ::snprintf(echo_packet,
sizeof(echo_packet),
"qC");
328 const uint32_t max_retries = 3;
329 uint32_t successful_responses = 0;
330 for (uint32_t i = 0; i < max_retries; ++i) {
335 ++successful_responses;
339 }
else if (successful_responses == 1) {
344 packet = echo_response;
345 got_actual_response =
true;
359 if (got_actual_response) {
403 size_t pkt_size =
m_bytes.size();
416 size_t hash_mark_idx =
m_bytes.find(
'#');
417 if (hash_mark_idx == std::string::npos)
419 if (hash_mark_idx + 2 >=
m_bytes.size())
422 if (!::isxdigit(
m_bytes[hash_mark_idx + 1]) ||
423 !::isxdigit(
m_bytes[hash_mark_idx + 2]))
426 size_t content_length =
429 size_t content_start = 2;
431 size_t checksum_idx =
439 size_t size_of_first_packet = hash_mark_idx + 3;
446 uint64_t decompressed_bufsize = ULONG_MAX;
448 size_t i = content_start;
449 while (i < hash_mark_idx && isdigit(
m_bytes[i]))
451 if (i < hash_mark_idx &&
m_bytes[i] ==
':') {
454 content_length = hash_mark_idx - content_start;
455 std::string bufsize_str(
m_bytes.data() + 2, i - 2 - 1);
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);
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);
473 llvm::StringRef(
m_bytes).substr(1, hash_mark_idx - 1));
474 bool success = packet_checksum == actual_checksum;
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);
484 m_bytes.erase(0, size_of_first_packet);
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) {
506 unescaped_content.push_back(
m_bytes[i] ^ 0x20);
508 unescaped_content.push_back(
m_bytes[i]);
513 uint8_t *decompressed_buffer =
nullptr;
514 size_t decompressed_bytes = 0;
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);
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;
540 if (m_decompression_scratch) {
541 free (m_decompression_scratch);
542 m_decompression_scratch =
nullptr;
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);
553 compression_decode_scratch_buffer_size(COMPRESSION_LZMA);
554 if (scratchbuf_size > 0) {
555 m_decompression_scratch = (
void*) malloc (scratchbuf_size);
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);
570 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
571 decompressed_buffer !=
nullptr &&
574 memset(&stream, 0,
sizeof(z_stream));
575 stream.next_in = (Bytef *)unescaped_content.data();
576 stream.avail_in = (uInt)unescaped_content.size();
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;
585 if (inflateInit2(&stream, -15) == Z_OK) {
586 int status = inflate(&stream, Z_NO_FLUSH);
588 if (status == Z_STREAM_END) {
589 decompressed_bytes = stream.total_out;
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);
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(
'#');
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);
614 new_packet.push_back(
'0');
615 new_packet.push_back(
'0');
618 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
621 free(decompressed_buffer);
627static void AddToLog(llvm::StringRef content, llvm::StringRef payload,
628 uint64_t original_packet_size,
630 bool compression_enabled) {
642 if (payload.front() ==
'$' && payload.size() > 4)
643 for (
char c : payload)
644 if (!llvm::isPrint(c) && !llvm::isSpace(c)) {
649 uint64_t total_length = payload.size();
651 if (compression_enabled)
652 LLDB_LOGF(log,
"<%4" PRIu64
":%" PRIu64
"> read packet: %.*s",
653 original_packet_size, total_length, (
int)(total_length),
656 LLDB_LOGF(log,
"<%4" PRIu64
"> read packet: %.*s", total_length,
657 (
int)(total_length), payload.data());
663 if (compression_enabled)
664 strm.
Printf(
"<%4" PRIu64
":%" PRIu64
"> read packet: %c",
665 original_packet_size, total_length, payload[0]);
667 strm.
Printf(
"<%4" PRIu64
"> read packet: %c", total_length, payload[0]);
668 for (
size_t i = 0; i < content.size(); ++i) {
670 const char ch = content[i];
673 const char escapee = content[++i] ^ 0x20;
674 strm.
Printf(
"%2.2x", escapee);
676 strm.
Printf(
"%2.2x", (uint8_t)ch);
680 strm.
Printf(
"%c%c%c", payload[total_length - 3], payload[total_length - 2],
681 payload[total_length - 1]);
693 if (src && src_len > 0) {
695 LLDB_LOGF(log,
"GDBRemoteCommunication::%s adding %u bytes: %.*s",
696 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
698 m_bytes.append((
const char *)src, src_len);
701 bool isNotifyPacket =
false;
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;
713 size_t original_packet_size =
m_bytes.size();
725 content_length = total_length = 1;
729 isNotifyPacket =
true;
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;
743 content_length = hash_pos - 1;
749 content_length = std::string::npos;
760 const size_t bytes_len =
m_bytes.size();
763 for (idx = 1; !done && idx < bytes_len; ++idx) {
777 LLDB_LOGF(log,
"GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
778 __FUNCTION__, idx - 1, idx - 1,
m_bytes.c_str());
783 if (content_length == std::string::npos) {
786 }
else if (total_length > 0) {
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;
795 llvm::StringRef(
m_bytes).take_front(total_length),
803 auto maybe_packet_str =
805 if (!maybe_packet_str) {
806 m_bytes.erase(0, total_length);
814 assert(checksum_idx <
m_bytes.size());
815 if (::isxdigit(
m_bytes[checksum_idx + 0]) ||
816 ::isxdigit(
m_bytes[checksum_idx + 1])) {
818 const char *packet_checksum_cstr = &
m_bytes[checksum_idx];
819 char packet_checksum = strtol(packet_checksum_cstr,
nullptr, 16);
821 llvm::StringRef(
m_bytes).slice(content_start, content_end));
822 success = packet_checksum == actual_checksum;
825 "error: checksum mismatch: %.*s expected 0x%2.2x, "
827 (
int)(total_length),
m_bytes.c_str(),
828 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
838 LLDB_LOGF(log,
"error: invalid checksum in packet: '%s'\n",
843 m_bytes.erase(0, total_length);
881 std::variant<llvm::StringRef, shared_fd_t> comm,
887#if !defined(__APPLE__)
898 llvm::SmallString<128> named_pipe_path;
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);
910 debugserver_args.
AppendArgument(llvm::formatv(
"--fd={0}", *comm_fd).str());
915 llvm::StringRef url = std::get<llvm::StringRef>(comm);
916 LLDB_LOG(log,
"debugserver listens on: {0}", url);
919#if defined(__APPLE__)
944 std::string env_debugserver_log_file =
945 host_env.lookup(
"LLDB_DEBUGSERVER_LOG_FILE");
946 if (!env_debugserver_log_file.empty()) {
948 llvm::formatv(
"--log-file={0}", env_debugserver_log_file).str());
951#if defined(__APPLE__)
952 const char *env_debugserver_log_flags = getenv(
"LLDB_DEBUGSERVER_LOG_FLAGS");
953 if (env_debugserver_log_flags) {
955 llvm::formatv(
"--log-flags={0}", env_debugserver_log_flags).str());
958 std::string env_debugserver_log_channels =
959 host_env.lookup(
"LLDB_SERVER_LOG_CHANNELS");
960 if (!env_debugserver_log_channels.empty()) {
962 llvm::formatv(
"--log-channels={0}", env_debugserver_log_channels)
969 uint32_t env_var_index = 1;
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();
981 "GDBRemoteCommunication::%s adding env var %s contents "
982 "to stub command line (%s)",
983 __FUNCTION__, env_var_name, extra_arg.c_str());
985 }
while (has_env_var);
1007 Platform *
const platform =
nullptr;
1008 launch_info.
Dump(string_stream, platform);
1009 LLDB_LOG(log,
"launch info for gdb-remote stub:\n{0}",
1017 if (std::holds_alternative<shared_fd_t>(comm))
1021 if (named_pipe_path.size() > 0) {
1024 LLDB_LOG(log,
"failed to open named pipe {0} for reading: {1}",
1025 named_pipe_path,
error);
1031 assert(socket_pipe.
CanRead());
1034 while (
error.Success()) {
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)
1045 LLDB_LOG(log,
"failed to synchronize on pipe {0}: {1}", named_pipe_path,
1048 socket_pipe.
Close();
1050 if (named_pipe_path.size() > 0) {
1052 LLDB_LOG(log,
"failed to delete pipe {0}: {1}", named_pipe_path, err);
1066 if (curr_timeout < timeout) {
1078void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1088 Stream <<
"ErrorSendFailed";
1091 Stream <<
"ErrorSendAck";
1094 Stream <<
"ErrorReplyFailed";
1097 Stream <<
"ErrorReplyTimeout";
1100 Stream <<
"ErrorReplyInvalid";
1103 Stream <<
"ErrorReplyAck";
1106 Stream <<
"ErrorDisconnected";
1109 Stream <<
"ErrorNoSequenceLock";
1114std::optional<std::string>
1117 std::string decoded;
1118 decoded.reserve(packet.size());
1119 for (std::string::const_iterator c = packet.begin(); c != packet.end(); ++c) {
1121 if (decoded.empty())
1122 return std::nullopt;
1125 char char_to_repeat = decoded.back();
1127 if (++c == packet.end())
1128 return std::nullopt;
1129 int repeat_count = *c + 3 -
' ';
1132 for (
int i = 0; i < repeat_count; ++i)
1133 decoded.push_back(char_to_repeat);
1134 }
else if (*c == 0x7d) {
1137 if (++c == packet.end())
1138 return std::nullopt;
1139 char escapee = *c ^ 0x20;
1140 decoded.push_back(escapee);
1142 decoded.push_back(*c);
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.
#define LLDB_LOGF(log,...)
#define LLDB_LOG_VERBOSE(log,...)
A command line argument class.
void AppendArguments(const Args &rhs)
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
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()
void PutString(llvm::StringRef str)
lldb::pipe_t GetWritePipe() const override
void CloseWriteFileDescriptor() override
Status CreateNew() override
bool CanWrite() const override
bool CanRead() const 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
void Dump(Stream &s, Platform *platform) const
Environment & GetEnvironment()
bool AppendSuppressFileAction(int fd, bool read, bool write)
bool AppendCloseFileAction(int fd)
bool AppendDuplicateFileAction(int fd, int dup_fd)
bool GetLaunchInSeparateProcessGroup() const
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
bool Fail() const
Test for error condition.
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
size_t size_t PutHex8(uint8_t uvalue)
Append an uint8_t value in the hexadecimal format to the stream.
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
The history keeps a circular buffer of GDB remote packets.
void Dump(Stream &strm) const
bool DidDumpToLog() const
std::chrono::seconds m_saved_timeout
GDBRemoteCommunication & m_gdb_comm
ScopedTimeout(GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
PacketResult ReadPacket(StringExtractorGDBRemote &response, Timeout< std::micro > timeout, bool sync_on_timeout)
char CalculcateChecksum(llvm::StringRef payload)
~GDBRemoteCommunication() override
PacketResult SendNotificationPacketNoLock(llvm::StringRef notify_type, std::deque< std::string > &queue, llvm::StringRef payload)
std::recursive_mutex m_bytes_mutex
PacketResult WaitForPacketNoLock(StringExtractorGDBRemote &response, Timeout< std::micro > timeout, bool sync_on_timeout)
void DumpHistory(Stream &strm)
bool CompressionIsEnabled()
LazyBool m_supports_qEcho
PacketResult SendRawPacketNoLock(llvm::StringRef payload, bool skip_ack=false)
CompressionType m_compression_type
static Status StartDebugserverProcess(std::variant< llvm::StringRef, shared_fd_t > comm, ProcessLaunchInfo &launch_info, const Args *inferior_args)
PacketResult SendPacketNoLock(llvm::StringRef payload)
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.
std::chrono::seconds GetPacketTimeout() const
std::chrono::seconds m_packet_timeout
PacketType CheckForPacket(const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
GDBRemoteCommunicationHistory m_history
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.
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.