11#include "lldb/Host/Config.h"
25#include "llvm/ADT/SmallString.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/Config/llvm-config.h"
28#include "llvm/Support/Error.h"
29#include "llvm/Support/ScopedPrinter.h"
35#if HAVE_LIBCOMPRESSION
36#include <compression.h>
50#ifdef LLDB_CONFIGURATION_DEBUG
66#if HAVE_LIBCOMPRESSION
67 if (m_decompression_scratch)
68 free (m_decompression_scratch);
75 for (
char c : payload)
78 return checksum & 255;
85 const size_t bytes_written =
WriteAll(&ch, 1, status,
nullptr);
86 LLDB_LOGF(log,
"<%4" PRIu64
"> send packet: %c", (uint64_t)bytes_written, ch);
95 const size_t bytes_written =
WriteAll(&ch, 1, status,
nullptr);
96 LLDB_LOGF(log,
"<%4" PRIu64
"> send packet: %c", (uint64_t)bytes_written, ch);
105 packet.
Write(payload.data(), payload.size());
108 std::string packet_str = std::string(packet.
GetString());
115 llvm::StringRef notify_type, std::deque<std::string> &queue,
116 llvm::StringRef payload) {
124 packet.
Write(notify_type.data(), notify_type.size());
126 packet.
Write(payload.data(), payload.size());
132 queue.push_back(payload.str());
142 const char *packet_data = packet.data();
143 const size_t packet_length = packet.size();
144 size_t bytes_written =
WriteAll(packet_data, packet_length, status,
nullptr);
146 size_t binary_start_offset = 0;
147 if (strncmp(packet_data,
"$vFile:pwrite:", strlen(
"$vFile:pwrite:")) ==
149 const char *first_comma = strchr(packet_data,
',');
151 const char *second_comma = strchr(first_comma + 1,
',');
153 binary_start_offset = second_comma - packet_data + 1;
164 if (binary_start_offset) {
167 strm.
Printf(
"<%4" PRIu64
"> send packet: %.*s", (uint64_t)bytes_written,
168 (
int)binary_start_offset, packet_data);
171 for (p = (
const uint8_t *)packet_data + binary_start_offset; *p !=
'#';
173 strm.
Printf(
"\\x%2.2x", *p);
175 strm.
Printf(
"%*s", (
int)3, p);
178 LLDB_LOGF(log,
"<%4" PRIu64
"> send packet: %.*s",
179 (uint64_t)bytes_written, (
int)packet_length, packet_data);
182 m_history.AddPacket(packet.str(), packet_length,
185 if (bytes_written == packet_length) {
191 LLDB_LOGF(log,
"error: failed to send packet: %.*s", (
int)packet_length,
214 bool sync_on_timeout) {
232 bool sync_on_timeout) {
233 uint8_t buffer[8192];
242 bool timed_out =
false;
243 bool disconnected =
false;
246 size_t bytes_read =
Read(buffer,
sizeof(buffer), timeout, status, &
error);
249 "Read(buffer, sizeof(buffer), timeout = {0}, "
250 "status = {1}, error = {2}) => bytes_read = {3}",
254 if (bytes_read > 0) {
261 if (sync_on_timeout) {
284 bool sync_success =
false;
285 bool got_actual_response =
false;
287 char echo_packet[32];
288 int echo_packet_len = 0;
292 echo_packet_len = ::snprintf(echo_packet,
sizeof(echo_packet),
294 std::string regex_str =
"^";
295 regex_str += echo_packet;
300 ::snprintf(echo_packet,
sizeof(echo_packet),
"qC");
308 const uint32_t max_retries = 3;
309 uint32_t successful_responses = 0;
310 for (uint32_t i = 0; i < max_retries; ++i) {
315 ++successful_responses;
319 }
else if (successful_responses == 1) {
324 packet = echo_response;
325 got_actual_response =
true;
339 if (got_actual_response) {
383 size_t pkt_size =
m_bytes.size();
396 size_t hash_mark_idx =
m_bytes.find(
'#');
397 if (hash_mark_idx == std::string::npos)
399 if (hash_mark_idx + 2 >=
m_bytes.size())
402 if (!::isxdigit(
m_bytes[hash_mark_idx + 1]) ||
403 !::isxdigit(
m_bytes[hash_mark_idx + 2]))
406 size_t content_length =
409 size_t content_start = 2;
411 size_t checksum_idx =
419 size_t size_of_first_packet = hash_mark_idx + 3;
426 uint64_t decompressed_bufsize = ULONG_MAX;
428 size_t i = content_start;
429 while (i < hash_mark_idx && isdigit(
m_bytes[i]))
431 if (i < hash_mark_idx &&
m_bytes[i] ==
':') {
434 content_length = hash_mark_idx - content_start;
435 std::string bufsize_str(
m_bytes.data() + 2, i - 2 - 1);
437 decompressed_bufsize = ::strtoul(bufsize_str.c_str(),
nullptr, 10);
438 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
439 m_bytes.erase(0, size_of_first_packet);
446 char packet_checksum_cstr[3];
447 packet_checksum_cstr[0] =
m_bytes[checksum_idx];
448 packet_checksum_cstr[1] =
m_bytes[checksum_idx + 1];
449 packet_checksum_cstr[2] =
'\0';
450 long packet_checksum = strtol(packet_checksum_cstr,
nullptr, 16);
453 llvm::StringRef(
m_bytes).substr(1, hash_mark_idx - 1));
454 bool success = packet_checksum == actual_checksum;
457 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
458 (
int)(pkt_size),
m_bytes.c_str(), (uint8_t)packet_checksum,
459 (uint8_t)actual_checksum);
464 m_bytes.erase(0, size_of_first_packet);
480 std::vector<uint8_t> unescaped_content;
481 unescaped_content.reserve(content_length);
482 size_t i = content_start;
483 while (i < hash_mark_idx) {
486 unescaped_content.push_back(
m_bytes[i] ^ 0x20);
488 unescaped_content.push_back(
m_bytes[i]);
493 uint8_t *decompressed_buffer =
nullptr;
494 size_t decompressed_bytes = 0;
496 if (decompressed_bufsize != ULONG_MAX) {
497 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
498 if (decompressed_buffer ==
nullptr) {
499 m_bytes.erase(0, size_of_first_packet);
504#if HAVE_LIBCOMPRESSION
509 compression_algorithm compression_type;
511 compression_type = COMPRESSION_LZFSE;
513 compression_type = COMPRESSION_ZLIB;
515 compression_type = COMPRESSION_LZ4_RAW;
517 compression_type = COMPRESSION_LZMA;
520 if (m_decompression_scratch) {
521 free (m_decompression_scratch);
522 m_decompression_scratch =
nullptr;
524 size_t scratchbuf_size = 0;
526 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
528 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
530 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
533 compression_decode_scratch_buffer_size(COMPRESSION_LZMA);
534 if (scratchbuf_size > 0) {
535 m_decompression_scratch = (
void*) malloc (scratchbuf_size);
540 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer !=
nullptr) {
541 decompressed_bytes = compression_decode_buffer(
542 decompressed_buffer, decompressed_bufsize,
543 (uint8_t *)unescaped_content.data(), unescaped_content.size(),
544 m_decompression_scratch, compression_type);
550 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
551 decompressed_buffer !=
nullptr &&
554 memset(&stream, 0,
sizeof(z_stream));
555 stream.next_in = (Bytef *)unescaped_content.data();
556 stream.avail_in = (uInt)unescaped_content.size();
558 stream.next_out = (Bytef *)decompressed_buffer;
559 stream.avail_out = decompressed_bufsize;
560 stream.total_out = 0;
561 stream.zalloc = Z_NULL;
562 stream.zfree = Z_NULL;
563 stream.opaque = Z_NULL;
565 if (inflateInit2(&stream, -15) == Z_OK) {
566 int status = inflate(&stream, Z_NO_FLUSH);
568 if (status == Z_STREAM_END) {
569 decompressed_bytes = stream.total_out;
575 if (decompressed_bytes == 0 || decompressed_buffer ==
nullptr) {
576 if (decompressed_buffer)
577 free(decompressed_buffer);
578 m_bytes.erase(0, size_of_first_packet);
582 std::string new_packet;
583 new_packet.reserve(decompressed_bytes + 6);
584 new_packet.push_back(
m_bytes[0]);
585 new_packet.append((
const char *)decompressed_buffer, decompressed_bytes);
586 new_packet.push_back(
'#');
589 llvm::StringRef((
const char *)decompressed_buffer, decompressed_bytes));
590 char decompressed_checksum_str[3];
591 snprintf(decompressed_checksum_str, 3,
"%02x", decompressed_checksum);
592 new_packet.append(decompressed_checksum_str);
594 new_packet.push_back(
'0');
595 new_packet.push_back(
'0');
598 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
601 free(decompressed_buffer);
613 if (src && src_len > 0) {
616 LLDB_LOGF(log,
"GDBRemoteCommunication::%s adding %u bytes: %.*s",
617 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
619 m_bytes.append((
const char *)src, src_len);
622 bool isNotifyPacket =
false;
628 size_t content_start = 0;
629 size_t content_length = 0;
630 size_t total_length = 0;
631 size_t checksum_idx = std::string::npos;
634 size_t original_packet_size =
m_bytes.size();
646 content_length = total_length = 1;
650 isNotifyPacket =
true;
656 size_t hash_pos =
m_bytes.find(
'#');
657 if (hash_pos != std::string::npos) {
658 if (hash_pos + 2 <
m_bytes.size()) {
659 checksum_idx = hash_pos + 1;
664 content_length = hash_pos - 1;
670 content_length = std::string::npos;
681 const size_t bytes_len =
m_bytes.size();
684 for (idx = 1; !done && idx < bytes_len; ++idx) {
698 LLDB_LOGF(log,
"GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
699 __FUNCTION__, idx - 1, idx - 1,
m_bytes.c_str());
704 if (content_length == std::string::npos) {
707 }
else if (total_length > 0) {
710 assert(content_length <=
m_bytes.size());
711 assert(total_length <=
m_bytes.size());
712 assert(content_length <= total_length);
713 size_t content_end = content_start + content_length;
727 if (
m_bytes[0] ==
'$' && total_length > 4) {
728 for (
size_t i = 0; !binary && i < total_length; ++i) {
730 if (!llvm::isPrint(c) && !llvm::isSpace(c)) {
739 strm.
Printf(
"<%4" PRIu64
":%" PRIu64
"> read packet: %c",
740 (uint64_t)original_packet_size, (uint64_t)total_length,
743 strm.
Printf(
"<%4" PRIu64
"> read packet: %c",
744 (uint64_t)total_length,
m_bytes[0]);
745 for (
size_t i = content_start; i < content_end; ++i) {
751 const char escapee =
m_bytes[++i] ^ 0x20;
752 strm.
Printf(
"%2.2x", escapee);
754 strm.
Printf(
"%2.2x", (uint8_t)ch);
763 LLDB_LOGF(log,
"<%4" PRIu64
":%" PRIu64
"> read packet: %.*s",
764 (uint64_t)original_packet_size, (uint64_t)total_length,
765 (
int)(total_length),
m_bytes.c_str());
767 LLDB_LOGF(log,
"<%4" PRIu64
"> read packet: %.*s",
768 (uint64_t)total_length, (
int)(total_length),
778 auto maybe_packet_str =
780 if (!maybe_packet_str) {
781 m_bytes.erase(0, total_length);
788 assert(checksum_idx <
m_bytes.size());
789 if (::isxdigit(
m_bytes[checksum_idx + 0]) ||
790 ::isxdigit(
m_bytes[checksum_idx + 1])) {
792 const char *packet_checksum_cstr = &
m_bytes[checksum_idx];
793 char packet_checksum = strtol(packet_checksum_cstr,
nullptr, 16);
795 llvm::StringRef(
m_bytes).slice(content_start, content_end));
796 success = packet_checksum == actual_checksum;
799 "error: checksum mismatch: %.*s expected 0x%2.2x, "
801 (
int)(total_length),
m_bytes.c_str(),
802 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
812 LLDB_LOGF(log,
"error: invalid checksum in packet: '%s'\n",
817 m_bytes.erase(0, total_length);
831 std::variant<llvm::StringRef, shared_fd_t> comm,
837#if !defined(__APPLE__)
848 llvm::SmallString<128> named_pipe_path;
857 if (
shared_fd_t *comm_fd = std::get_if<shared_fd_t>(&comm)) {
858 LLDB_LOG(log,
"debugserver communicates over fd {0}", comm_fd);
860 debugserver_args.
AppendArgument(llvm::formatv(
"--fd={0}", *comm_fd).str());
865 llvm::StringRef url = std::get<llvm::StringRef>(comm);
866 LLDB_LOG(log,
"debugserver listens on: {0}", url);
869#if defined(__APPLE__)
894 std::string env_debugserver_log_file =
895 host_env.lookup(
"LLDB_DEBUGSERVER_LOG_FILE");
896 if (!env_debugserver_log_file.empty()) {
898 llvm::formatv(
"--log-file={0}", env_debugserver_log_file).str());
901#if defined(__APPLE__)
902 const char *env_debugserver_log_flags = getenv(
"LLDB_DEBUGSERVER_LOG_FLAGS");
903 if (env_debugserver_log_flags) {
905 llvm::formatv(
"--log-flags={0}", env_debugserver_log_flags).str());
908 std::string env_debugserver_log_channels =
909 host_env.lookup(
"LLDB_SERVER_LOG_CHANNELS");
910 if (!env_debugserver_log_channels.empty()) {
912 llvm::formatv(
"--log-channels={0}", env_debugserver_log_channels)
919 uint32_t env_var_index = 1;
922 char env_var_name[64];
923 snprintf(env_var_name,
sizeof(env_var_name),
924 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
925 std::string extra_arg = host_env.lookup(env_var_name);
926 has_env_var = !extra_arg.empty();
931 "GDBRemoteCommunication::%s adding env var %s contents "
932 "to stub command line (%s)",
933 __FUNCTION__, env_var_name, extra_arg.c_str());
935 }
while (has_env_var);
958 launch_info.
Dump(string_stream, platform);
959 LLDB_LOG(log,
"launch info for gdb-remote stub:\n{0}",
967 if (std::holds_alternative<shared_fd_t>(comm))
971 if (named_pipe_path.size() > 0) {
974 LLDB_LOG(log,
"failed to open named pipe {0} for reading: {1}",
975 named_pipe_path,
error);
984 while (
error.Success()) {
986 if (llvm::Expected<size_t> num_bytes =
987 socket_pipe.
Read(buf, std::size(buf), std::chrono::seconds(10))) {
995 LLDB_LOG(log,
"failed to synchronize on pipe {0}: {1}", named_pipe_path,
1000 if (named_pipe_path.size() > 0) {
1002 LLDB_LOG(log,
"failed to delete pipe {0}: {1}", named_pipe_path, err);
1016 if (curr_timeout < timeout) {
1028void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1038 Stream <<
"ErrorSendFailed";
1041 Stream <<
"ErrorSendAck";
1044 Stream <<
"ErrorReplyFailed";
1047 Stream <<
"ErrorReplyTimeout";
1050 Stream <<
"ErrorReplyInvalid";
1053 Stream <<
"ErrorReplyAck";
1056 Stream <<
"ErrorDisconnected";
1059 Stream <<
"ErrorNoSequenceLock";
1064std::optional<std::string>
1067 std::string decoded;
1068 decoded.reserve(packet.size());
1069 for (std::string::const_iterator c = packet.begin(); c != packet.end(); ++c) {
1071 if (decoded.empty())
1072 return std::nullopt;
1075 char char_to_repeat = decoded.back();
1077 if (++c == packet.end())
1078 return std::nullopt;
1079 int repeat_count = *c + 3 -
' ';
1082 for (
int i = 0; i < repeat_count; ++i)
1083 decoded.push_back(char_to_repeat);
1084 }
else if (*c == 0x7d) {
1087 if (++c == packet.end())
1088 return std::nullopt;
1089 char escapee = *c ^ 0x20;
1090 decoded.push_back(escapee);
1092 decoded.push_back(*c);
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
#define LLDB_LOGF(log,...)
#define LLDB_LOGV(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.
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)
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
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.