17 #include "lldb/Host/Config.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/Support/ScopedPrinter.h"
40 #if defined(__APPLE__)
41 #define DEBUGSERVER_BASENAME "debugserver"
43 #define DEBUGSERVER_BASENAME "lldb-server.exe"
45 #define DEBUGSERVER_BASENAME "lldb-server"
48 #if defined(HAVE_LIBCOMPRESSION)
49 #include <compression.h>
61 GDBRemoteCommunication::GDBRemoteCommunication(
const char *comm_name,
62 const char *listener_name)
64 #ifdef LLDB_CONFIGURATION_DEBUG
65 m_packet_timeout(1000),
80 #if defined(HAVE_LIBCOMPRESSION)
81 if (m_decompression_scratch)
82 free (m_decompression_scratch);
89 for (
char c : payload)
92 return checksum & 255;
99 const size_t bytes_written =
WriteAll(&ch, 1, status,
nullptr);
100 LLDB_LOGF(log,
"<%4" PRIu64
"> send packet: %c", (uint64_t)bytes_written, ch);
102 return bytes_written;
109 const size_t bytes_written =
WriteAll(&ch, 1, status,
nullptr);
110 LLDB_LOGF(log,
"<%4" PRIu64
"> send packet: %c", (uint64_t)bytes_written, ch);
112 return bytes_written;
119 packet.
Write(payload.data(), payload.size());
133 const char *packet_data = packet.data();
134 const size_t packet_length = packet.size();
135 size_t bytes_written =
WriteAll(packet_data, packet_length, status,
nullptr);
137 size_t binary_start_offset = 0;
138 if (strncmp(packet_data,
"$vFile:pwrite:", strlen(
"$vFile:pwrite:")) ==
140 const char *first_comma = strchr(packet_data,
',');
142 const char *second_comma = strchr(first_comma + 1,
',');
144 binary_start_offset = second_comma - packet_data + 1;
155 if (binary_start_offset) {
158 strm.
Printf(
"<%4" PRIu64
"> send packet: %.*s", (uint64_t)bytes_written,
159 (
int)binary_start_offset, packet_data);
162 for (p = (
const uint8_t *)packet_data + binary_start_offset; *p !=
'#';
164 strm.
Printf(
"\\x%2.2x", *p);
166 strm.
Printf(
"%*s", (
int)3, p);
169 LLDB_LOGF(log,
"<%4" PRIu64
"> send packet: %.*s",
170 (uint64_t)bytes_written, (
int)packet_length, packet_data);
176 if (bytes_written == packet_length) {
182 LLDB_LOGF(log,
"error: failed to send packet: %.*s", (
int)packet_length,
194 StringExtractorGDBRemote::ResponseType::eAck)
205 bool sync_on_timeout,
206 llvm::function_ref<
void(llvm::StringRef)> output_callback) {
207 auto result =
ReadPacket(response, timeout, sync_on_timeout);
213 output_callback(output);
214 result =
ReadPacket(response, timeout, sync_on_timeout);
222 bool sync_on_timeout) {
240 bool sync_on_timeout) {
241 uint8_t buffer[8192];
250 bool timed_out =
false;
251 bool disconnected =
false;
254 size_t bytes_read =
Read(buffer,
sizeof(buffer), timeout, status, &
error);
257 "Read(buffer, sizeof(buffer), timeout = {0}, "
258 "status = {1}, error = {2}) => bytes_read = {3}",
262 if (bytes_read > 0) {
269 if (sync_on_timeout) {
292 bool sync_success =
false;
293 bool got_actual_response =
false;
295 char echo_packet[32];
296 int echo_packet_len = 0;
300 echo_packet_len = ::snprintf(echo_packet,
sizeof(echo_packet),
303 regex_str += echo_packet;
308 ::snprintf(echo_packet,
sizeof(echo_packet),
"qC");
318 for (
uint32_t i = 0; i < max_retries; ++i) {
323 ++successful_responses;
327 }
else if (successful_responses == 1) {
332 packet = echo_response;
333 got_actual_response =
true;
347 if (got_actual_response) {
390 size_t pkt_size =
m_bytes.size();
403 size_t hash_mark_idx =
m_bytes.find(
'#');
404 if (hash_mark_idx == std::string::npos)
406 if (hash_mark_idx + 2 >=
m_bytes.size())
409 if (!::isxdigit(
m_bytes[hash_mark_idx + 1]) ||
410 !::isxdigit(
m_bytes[hash_mark_idx + 2]))
413 size_t content_length =
416 size_t content_start = 2;
418 size_t checksum_idx =
426 size_t size_of_first_packet = hash_mark_idx + 3;
433 uint64_t decompressed_bufsize = ULONG_MAX;
435 size_t i = content_start;
436 while (i < hash_mark_idx && isdigit(
m_bytes[i]))
438 if (i < hash_mark_idx &&
m_bytes[i] ==
':') {
441 content_length = hash_mark_idx - content_start;
444 decompressed_bufsize = ::strtoul(bufsize_str.c_str(),
nullptr, 10);
445 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
446 m_bytes.erase(0, size_of_first_packet);
453 char packet_checksum_cstr[3];
454 packet_checksum_cstr[0] =
m_bytes[checksum_idx];
455 packet_checksum_cstr[1] =
m_bytes[checksum_idx + 1];
456 packet_checksum_cstr[2] =
'\0';
457 long packet_checksum = strtol(packet_checksum_cstr,
nullptr, 16);
460 llvm::StringRef(
m_bytes).substr(1, hash_mark_idx - 1));
461 bool success = packet_checksum == actual_checksum;
464 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
465 (
int)(pkt_size),
m_bytes.c_str(), (uint8_t)packet_checksum,
466 (uint8_t)actual_checksum);
471 m_bytes.erase(0, size_of_first_packet);
487 std::vector<uint8_t> unescaped_content;
488 unescaped_content.reserve(content_length);
489 size_t i = content_start;
490 while (i < hash_mark_idx) {
493 unescaped_content.push_back(
m_bytes[i] ^ 0
x20);
495 unescaped_content.push_back(
m_bytes[i]);
500 uint8_t *decompressed_buffer =
nullptr;
501 size_t decompressed_bytes = 0;
503 if (decompressed_bufsize != ULONG_MAX) {
504 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
505 if (decompressed_buffer ==
nullptr) {
506 m_bytes.erase(0, size_of_first_packet);
511 #if defined(HAVE_LIBCOMPRESSION)
516 compression_algorithm compression_type;
518 compression_type = COMPRESSION_LZFSE;
520 compression_type = COMPRESSION_ZLIB;
522 compression_type = COMPRESSION_LZ4_RAW;
524 compression_type = COMPRESSION_LZMA;
527 if (m_decompression_scratch) {
528 free (m_decompression_scratch);
529 m_decompression_scratch =
nullptr;
531 size_t scratchbuf_size = 0;
533 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
535 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
537 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
539 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZMA);
541 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
542 if (scratchbuf_size > 0) {
543 m_decompression_scratch = (
void*) malloc (scratchbuf_size);
548 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer !=
nullptr) {
549 decompressed_bytes = compression_decode_buffer(
550 decompressed_buffer, decompressed_bufsize,
551 (uint8_t *)unescaped_content.data(), unescaped_content.size(),
552 m_decompression_scratch, compression_type);
558 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
559 decompressed_buffer !=
nullptr &&
562 memset(&stream, 0,
sizeof(z_stream));
563 stream.next_in = (Bytef *)unescaped_content.data();
564 stream.avail_in = (uInt)unescaped_content.size();
566 stream.next_out = (Bytef *)decompressed_buffer;
567 stream.avail_out = decompressed_bufsize;
568 stream.total_out = 0;
569 stream.zalloc = Z_NULL;
570 stream.zfree = Z_NULL;
571 stream.opaque = Z_NULL;
573 if (inflateInit2(&stream, -15) == Z_OK) {
574 int status = inflate(&stream, Z_NO_FLUSH);
576 if (status == Z_STREAM_END) {
577 decompressed_bytes = stream.total_out;
583 if (decompressed_bytes == 0 || decompressed_buffer ==
nullptr) {
584 if (decompressed_buffer)
585 free(decompressed_buffer);
586 m_bytes.erase(0, size_of_first_packet);
591 new_packet.reserve(decompressed_bytes + 6);
592 new_packet.push_back(
m_bytes[0]);
593 new_packet.append((
const char *)decompressed_buffer, decompressed_bytes);
594 new_packet.push_back(
'#');
597 llvm::StringRef((
const char *)decompressed_buffer, decompressed_bytes));
598 char decompressed_checksum_str[3];
599 snprintf(decompressed_checksum_str, 3,
"%02x", decompressed_checksum);
600 new_packet.append(decompressed_checksum_str);
602 new_packet.push_back(
'0');
603 new_packet.push_back(
'0');
606 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
609 free(decompressed_buffer);
621 if (src && src_len > 0) {
624 LLDB_LOGF(log,
"GDBRemoteCommunication::%s adding %u bytes: %.*s",
627 m_bytes.append((
const char *)src, src_len);
630 bool isNotifyPacket =
false;
636 size_t content_start = 0;
637 size_t content_length = 0;
638 size_t total_length = 0;
639 size_t checksum_idx = std::string::npos;
642 size_t original_packet_size =
m_bytes.size();
654 content_length = total_length = 1;
658 isNotifyPacket =
true;
664 size_t hash_pos =
m_bytes.find(
'#');
665 if (hash_pos != std::string::npos) {
666 if (hash_pos + 2 <
m_bytes.size()) {
667 checksum_idx = hash_pos + 1;
672 content_length = hash_pos - 1;
678 content_length = std::string::npos;
689 const size_t bytes_len =
m_bytes.size();
692 for (idx = 1; !done && idx < bytes_len; ++idx) {
706 LLDB_LOGF(log,
"GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
707 __FUNCTION__, idx - 1, idx - 1,
m_bytes.c_str());
712 if (content_length == std::string::npos) {
715 }
else if (total_length > 0) {
718 assert(content_length <=
m_bytes.size());
719 assert(total_length <=
m_bytes.size());
720 assert(content_length <= total_length);
721 size_t content_end = content_start + content_length;
735 if (
m_bytes[0] ==
'$' && total_length > 4) {
736 for (
size_t i = 0; !binary && i < total_length; ++i) {
738 if (!llvm::isPrint(c) && !llvm::isSpace(c)) {
747 strm.
Printf(
"<%4" PRIu64
":%" PRIu64
"> read packet: %c",
748 (uint64_t)original_packet_size, (uint64_t)total_length,
751 strm.
Printf(
"<%4" PRIu64
"> read packet: %c",
752 (uint64_t)total_length,
m_bytes[0]);
753 for (
size_t i = content_start; i < content_end; ++i) {
759 const char escapee =
m_bytes[++i] ^ 0x20;
760 strm.
Printf(
"%2.2x", escapee);
762 strm.
Printf(
"%2.2x", (uint8_t)ch);
771 LLDB_LOGF(log,
"<%4" PRIu64
":%" PRIu64
"> read packet: %.*s",
772 (uint64_t)original_packet_size, (uint64_t)total_length,
773 (
int)(total_length),
m_bytes.c_str());
775 LLDB_LOGF(log,
"<%4" PRIu64
"> read packet: %.*s",
776 (uint64_t)total_length, (
int)(total_length),
791 assert(checksum_idx <
m_bytes.size());
792 if (::isxdigit(
m_bytes[checksum_idx + 0]) ||
793 ::isxdigit(
m_bytes[checksum_idx + 1])) {
795 const char *packet_checksum_cstr = &
m_bytes[checksum_idx];
796 char packet_checksum = strtol(packet_checksum_cstr,
nullptr, 16);
798 llvm::StringRef(
m_bytes).slice(content_start, content_end));
799 success = packet_checksum == actual_checksum;
802 "error: checksum mismatch: %.*s expected 0x%2.2x, "
804 (
int)(total_length),
m_bytes.c_str(),
805 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
815 LLDB_LOGF(log,
"error: invalid checksum in packet: '%s'\n",
820 m_bytes.erase(0, total_length);
836 return Status(
"listen thread already running");
838 char listen_url[512];
839 if (hostname && hostname[0])
840 snprintf(listen_url,
sizeof(listen_url),
"listen://%s:%i", hostname, port);
842 snprintf(listen_url,
sizeof(listen_url),
"listen://%i", port);
848 return Status(listen_thread.takeError());
869 [
this](llvm::StringRef port_str) {
871 llvm::to_integer(port_str, port, 10);
872 m_port_promise.set_value(port);
882 uint16_t *port,
const Args *inferior_args,
int pass_comm_fd) {
884 LLDB_LOGF(log,
"GDBRemoteCommunication::%s(url=%s, port=%" PRIu16
")",
885 __FUNCTION__, url ? url :
"<empty>", port ? *port :
uint16_t(0));
889 static FileSpec g_debugserver_file_spec;
898 std::string env_debugserver_path = host_env.lookup(
"LLDB_DEBUGSERVER_PATH");
899 if (!env_debugserver_path.empty()) {
900 debugserver_file_spec.
SetFile(env_debugserver_path,
901 FileSpec::Style::native);
903 "GDBRemoteCommunication::%s() gdb-remote stub exe path set "
904 "from environment variable: %s",
905 __FUNCTION__, env_debugserver_path.c_str());
907 debugserver_file_spec = g_debugserver_file_spec;
908 bool debugserver_exists =
910 if (!debugserver_exists) {
912 debugserver_file_spec = HostInfo::GetSupportExeDir();
913 if (debugserver_file_spec) {
916 if (debugserver_exists) {
918 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
919 __FUNCTION__, debugserver_file_spec.
GetPath().c_str());
921 g_debugserver_file_spec = debugserver_file_spec;
924 debugserver_file_spec =
927 debugserver_file_spec.
Clear();
928 if (debugserver_file_spec) {
931 debugserver_exists =
true;
934 "GDBRemoteCommunication::%s() could not find "
935 "gdb-remote stub exe '%s'",
936 __FUNCTION__, debugserver_file_spec.
GetPath().c_str());
940 g_debugserver_file_spec.
Clear();
945 if (debugserver_exists) {
946 debugserver_file_spec.
GetPath(debugserver_path,
sizeof(debugserver_path));
949 debugserver_args.
Clear();
952 debugserver_args.
AppendArgument(llvm::StringRef(debugserver_path));
954 #if !defined(__APPLE__)
963 if (pass_comm_fd >= 0) {
965 fd_arg.
Printf(
"--fd=%i", pass_comm_fd);
973 debugserver_args.
AppendArgument(llvm::StringRef(
"--native-regs"));
979 llvm::SmallString<128> named_pipe_path;
989 if (pass_comm_fd == -1) {
994 #if defined(__APPLE__)
997 error = socket_pipe.CreateWithUniqueName(
"debugserver-named-pipe",
998 false, named_pipe_path);
1001 "GDBRemoteCommunication::%s() "
1002 "named pipe creation failed: %s",
1003 __FUNCTION__,
error.AsCString());
1006 debugserver_args.
AppendArgument(llvm::StringRef(
"--named-pipe"));
1011 error = socket_pipe.CreateNew(
true);
1014 "GDBRemoteCommunication::%s() "
1015 "unnamed pipe creation failed: %s",
1016 __FUNCTION__,
error.AsCString());
1019 pipe_t write = socket_pipe.GetWritePipe();
1030 "GDBRemoteCommunication::%s() unable to start listen "
1032 __FUNCTION__,
error.AsCString());
1038 uint16_t port_ = port_future.wait_for(std::chrono::seconds(10)) ==
1039 std::future_status::ready
1044 snprintf(port_cstr,
sizeof(port_cstr),
"127.0.0.1:%i", port_);
1048 debugserver_args.
AppendArgument(llvm::StringRef(
"--reverse-connect"));
1053 error.SetErrorString(
"failed to bind to port 0 on 127.0.0.1");
1054 LLDB_LOGF(log,
"GDBRemoteCommunication::%s() failed: %s",
1055 __FUNCTION__,
error.AsCString());
1061 host_env.lookup(
"LLDB_DEBUGSERVER_LOG_FILE");
1062 if (!env_debugserver_log_file.empty()) {
1064 llvm::formatv(
"--log-file={0}", env_debugserver_log_file).str());
1067 #if defined(__APPLE__)
1068 const char *env_debugserver_log_flags =
1069 getenv(
"LLDB_DEBUGSERVER_LOG_FLAGS");
1070 if (env_debugserver_log_flags) {
1072 llvm::formatv(
"--log-flags={0}", env_debugserver_log_flags).str());
1076 host_env.lookup(
"LLDB_SERVER_LOG_CHANNELS");
1077 if (!env_debugserver_log_channels.empty()) {
1079 llvm::formatv(
"--log-channels={0}", env_debugserver_log_channels)
1089 char env_var_name[64];
1090 snprintf(env_var_name,
sizeof(env_var_name),
1091 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1092 std::string extra_arg = host_env.lookup(env_var_name);
1093 has_env_var = !extra_arg.empty();
1098 "GDBRemoteCommunication::%s adding env var %s contents "
1099 "to stub command line (%s)",
1100 __FUNCTION__, env_var_name, extra_arg.c_str());
1102 }
while (has_env_var);
1124 Platform *
const platform =
nullptr;
1125 launch_info.
Dump(string_stream, platform);
1126 LLDB_LOGF(log,
"launch info for gdb-remote stub:\n%s",
1131 if (
error.Success() &&
1133 pass_comm_fd == -1) {
1134 if (named_pipe_path.size() > 0) {
1135 error = socket_pipe.OpenAsReader(named_pipe_path,
false);
1138 "GDBRemoteCommunication::%s() "
1139 "failed to open named pipe %s for reading: %s",
1140 __FUNCTION__, named_pipe_path.c_str(),
error.AsCString());
1143 if (socket_pipe.CanWrite())
1144 socket_pipe.CloseWriteFileDescriptor();
1145 if (socket_pipe.CanRead()) {
1147 port_cstr[0] =
'\0';
1148 size_t num_bytes =
sizeof(port_cstr);
1150 error = socket_pipe.ReadWithTimeout(
1151 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1152 if (
error.Success() && (port !=
nullptr)) {
1153 assert(num_bytes > 0 && port_cstr[num_bytes - 1] ==
'\0');
1156 llvm::to_integer(port_cstr, child_port);
1157 if (*port == 0 || *port == child_port) {
1160 "GDBRemoteCommunication::%s() "
1161 "debugserver listens %u port",
1162 __FUNCTION__, *port);
1165 "GDBRemoteCommunication::%s() "
1166 "debugserver listening on port "
1167 "%d but requested port was %d",
1172 "GDBRemoteCommunication::%s() "
1173 "failed to read a port value from pipe %s: %s",
1174 __FUNCTION__, named_pipe_path.c_str(),
error.AsCString());
1176 socket_pipe.Close();
1179 if (named_pipe_path.size() > 0) {
1180 const auto err = socket_pipe.Delete(named_pipe_path);
1183 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1184 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
1196 LLDB_LOGF(log,
"GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1213 const bool child_processes_inherit =
false;
1214 const int backlog = 5;
1215 TCPSocket listen_socket(
true, child_processes_inherit);
1221 std::future<Status> accept_status = std::async(
1222 std::launch::async, [&] {
return listen_socket.
Accept(accept_socket); });
1224 llvm::SmallString<32> remote_addr;
1225 llvm::raw_svector_ostream(remote_addr)
1228 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1232 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1233 "Unable to connect: %s", status.
AsCString());
1240 std::make_unique<ConnectionFileDescriptor>(accept_socket));
1241 return llvm::Error::success();
1246 : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1250 if (curr_timeout < timeout) {
1258 if (m_timeout_modified)
1259 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1262 void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1272 Stream <<
"ErrorSendFailed";
1275 Stream <<
"ErrorSendAck";
1278 Stream <<
"ErrorReplyFailed";
1281 Stream <<
"ErrorReplyTimeout";
1284 Stream <<
"ErrorReplyInvalid";
1287 Stream <<
"ErrorReplyAck";
1290 Stream <<
"ErrorDisconnected";
1293 Stream <<
"ErrorNoSequenceLock";
1301 decoded.reserve(packet.size());
1302 for (std::string::const_iterator c = packet.begin(); c != packet.end(); ++c) {
1306 char char_to_repeat = decoded.back();
1308 int repeat_count = *++c + 3 -
' ';
1311 for (
int i = 0; i < repeat_count; ++i)
1312 decoded.push_back(char_to_repeat);
1313 }
else if (*c == 0x7d) {
1316 char escapee = *++c ^ 0x20;
1317 decoded.push_back(escapee);
1319 decoded.push_back(*c);