1 //===-- GDBRemoteCommunication.cpp ------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "GDBRemoteCommunication.h"
16 #include "lldb/Core/StreamFile.h"
17 #include "lldb/Host/ConnectionFileDescriptor.h"
18 #include "lldb/Host/FileSystem.h"
19 #include "lldb/Host/Host.h"
20 #include "lldb/Host/HostInfo.h"
21 #include "lldb/Host/Pipe.h"
22 #include "lldb/Host/ProcessLaunchInfo.h"
23 #include "lldb/Host/Socket.h"
24 #include "lldb/Host/StringConvert.h"
25 #include "lldb/Host/ThreadLauncher.h"
26 #include "lldb/Host/common/TCPSocket.h"
27 #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
28 #include "lldb/Target/Platform.h"
29 #include "lldb/Utility/Event.h"
30 #include "lldb/Utility/FileSpec.h"
31 #include "lldb/Utility/Log.h"
32 #include "lldb/Utility/RegularExpression.h"
33 #include "lldb/Utility/StreamString.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/Support/ScopedPrinter.h"
37 #include "ProcessGDBRemoteLog.h"
39 #if defined(__APPLE__)
40 #define DEBUGSERVER_BASENAME "debugserver"
42 #define DEBUGSERVER_BASENAME "lldb-server"
45 #if defined(HAVE_LIBCOMPRESSION)
46 #include <compression.h>
49 #if defined(HAVE_LIBZ)
54 using namespace lldb_private;
55 using namespace lldb_private::process_gdb_remote;
57 // GDBRemoteCommunication constructor
58 GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
59 const char *listener_name)
60 : Communication(comm_name),
61 #ifdef LLDB_CONFIGURATION_DEBUG
62 m_packet_timeout(1000),
66 m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
67 m_send_acks(true), m_compression_type(CompressionType::None),
72 GDBRemoteCommunication::~GDBRemoteCommunication() {
77 #if defined(HAVE_LIBCOMPRESSION)
78 if (m_decompression_scratch)
79 free (m_decompression_scratch);
82 // Stop the communications read thread which is used to parse all incoming
83 // packets. This function will block until the read thread returns.
84 if (m_read_thread_enabled)
88 char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
91 for (char c : payload)
94 return checksum & 255;
97 size_t GDBRemoteCommunication::SendAck() {
98 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
99 ConnectionStatus status = eConnectionStatusSuccess;
101 const size_t bytes_written = Write(&ch, 1, status, nullptr);
103 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
104 m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend,
106 return bytes_written;
109 size_t GDBRemoteCommunication::SendNack() {
110 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
111 ConnectionStatus status = eConnectionStatusSuccess;
113 const size_t bytes_written = Write(&ch, 1, status, nullptr);
115 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
116 m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend,
118 return bytes_written;
121 GDBRemoteCommunication::PacketResult
122 GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
123 StreamString packet(0, 4, eByteOrderBig);
125 packet.Write(payload.data(), payload.size());
127 packet.PutHex8(CalculcateChecksum(payload));
128 std::string packet_str = packet.GetString();
130 return SendRawPacketNoLock(packet_str);
133 GDBRemoteCommunication::PacketResult
134 GDBRemoteCommunication::SendRawPacketNoLock(llvm::StringRef packet,
137 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
138 ConnectionStatus status = eConnectionStatusSuccess;
139 const char *packet_data = packet.data();
140 const size_t packet_length = packet.size();
141 size_t bytes_written = Write(packet_data, packet_length, status, nullptr);
143 size_t binary_start_offset = 0;
144 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
146 const char *first_comma = strchr(packet_data, ',');
148 const char *second_comma = strchr(first_comma + 1, ',');
150 binary_start_offset = second_comma - packet_data + 1;
154 // If logging was just enabled and we have history, then dump out what we
155 // have to the log so we get the historical context. The Dump() call that
156 // logs all of the packet will set a boolean so that we don't dump this
158 if (!m_history.DidDumpToLog())
161 if (binary_start_offset) {
163 // Print non binary data header
164 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
165 (int)binary_start_offset, packet_data);
167 // Print binary data exactly as sent
168 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
170 strm.Printf("\\x%2.2x", *p);
171 // Print the checksum
172 strm.Printf("%*s", (int)3, p);
173 log->PutString(strm.GetString());
175 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
176 (int)packet_length, packet_data);
179 m_history.AddPacket(packet.str(), packet_length,
180 GDBRemoteCommunicationHistory::ePacketTypeSend,
183 if (bytes_written == packet_length) {
184 if (!skip_ack && GetSendAcks())
187 return PacketResult::Success;
190 log->Printf("error: failed to send packet: %.*s", (int)packet_length,
194 return PacketResult::ErrorSendFailed;
197 GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
198 StringExtractorGDBRemote packet;
199 PacketResult result = ReadPacket(packet, GetPacketTimeout(), false);
200 if (result == PacketResult::Success) {
201 if (packet.GetResponseType() ==
202 StringExtractorGDBRemote::ResponseType::eAck)
203 return PacketResult::Success;
205 return PacketResult::ErrorSendAck;
210 GDBRemoteCommunication::PacketResult
211 GDBRemoteCommunication::ReadPacketWithOutputSupport(
212 StringExtractorGDBRemote &response, Timeout<std::micro> timeout,
213 bool sync_on_timeout,
214 llvm::function_ref<void(llvm::StringRef)> output_callback) {
215 auto result = ReadPacket(response, timeout, sync_on_timeout);
216 while (result == PacketResult::Success && response.IsNormalResponse() &&
217 response.PeekChar() == 'O') {
220 if (response.GetHexByteString(output))
221 output_callback(output);
222 result = ReadPacket(response, timeout, sync_on_timeout);
227 GDBRemoteCommunication::PacketResult
228 GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
229 Timeout<std::micro> timeout,
230 bool sync_on_timeout) {
231 if (m_read_thread_enabled)
232 return PopPacketFromQueue(response, timeout);
234 return WaitForPacketNoLock(response, timeout, sync_on_timeout);
237 // This function is called when a packet is requested.
238 // A whole packet is popped from the packet queue and returned to the caller.
239 // Packets are placed into this queue from the communication read thread. See
240 // GDBRemoteCommunication::AppendBytesToCache.
241 GDBRemoteCommunication::PacketResult
242 GDBRemoteCommunication::PopPacketFromQueue(StringExtractorGDBRemote &response,
243 Timeout<std::micro> timeout) {
244 auto pred = [&] { return !m_packet_queue.empty() && IsConnected(); };
245 // lock down the packet queue
246 std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
249 m_condition_queue_not_empty.wait(lock, pred);
251 if (!m_condition_queue_not_empty.wait_for(lock, *timeout, pred))
252 return PacketResult::ErrorReplyTimeout;
254 return PacketResult::ErrorDisconnected;
257 // get the front element of the queue
258 response = m_packet_queue.front();
260 // remove the front element
261 m_packet_queue.pop();
264 return PacketResult::Success;
267 GDBRemoteCommunication::PacketResult
268 GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
269 Timeout<std::micro> timeout,
270 bool sync_on_timeout) {
271 uint8_t buffer[8192];
274 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
276 // Check for a packet from our cache first without trying any reading...
277 if (CheckForPacket(nullptr, 0, packet) != PacketType::Invalid)
278 return PacketResult::Success;
280 bool timed_out = false;
281 bool disconnected = false;
282 while (IsConnected() && !timed_out) {
283 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
284 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
287 "Read(buffer, sizeof(buffer), timeout = {0}, "
288 "status = {1}, error = {2}) => bytes_read = {3}",
289 timeout, Communication::ConnectionStatusAsCString(status), error,
292 if (bytes_read > 0) {
293 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
294 return PacketResult::Success;
297 case eConnectionStatusTimedOut:
298 case eConnectionStatusInterrupted:
299 if (sync_on_timeout) {
300 /// Sync the remote GDB server and make sure we get a response that
301 /// corresponds to what we send.
303 /// Sends a "qEcho" packet and makes sure it gets the exact packet
304 /// echoed back. If the qEcho packet isn't supported, we send a qC
305 /// packet and make sure we get a valid thread ID back. We use the
306 /// "qC" packet since its response if very unique: is responds with
307 /// "QC%x" where %x is the thread ID of the current thread. This
308 /// makes the response unique enough from other packet responses to
309 /// ensure we are back on track.
311 /// This packet is needed after we time out sending a packet so we
312 /// can ensure that we are getting the response for the packet we
313 /// are sending. There are no sequence IDs in the GDB remote
314 /// protocol (there used to be, but they are not supported anymore)
315 /// so if you timeout sending packet "abc", you might then send
316 /// packet "cde" and get the response for the previous "abc" packet.
317 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
318 /// many responses for packets can look like responses for other
319 /// packets. So if we timeout, we need to ensure that we can get
320 /// back on track. If we can't get back on track, we must
322 bool sync_success = false;
323 bool got_actual_response = false;
324 // We timed out, we need to sync back up with the
325 char echo_packet[32];
326 int echo_packet_len = 0;
327 RegularExpression response_regex;
329 if (m_supports_qEcho == eLazyBoolYes) {
330 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
331 "qEcho:%u", ++m_echo_number);
332 std::string regex_str = "^";
333 regex_str += echo_packet;
335 response_regex.Compile(regex_str);
338 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
339 response_regex.Compile(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
342 PacketResult echo_packet_result =
343 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
344 if (echo_packet_result == PacketResult::Success) {
345 const uint32_t max_retries = 3;
346 uint32_t successful_responses = 0;
347 for (uint32_t i = 0; i < max_retries; ++i) {
348 StringExtractorGDBRemote echo_response;
350 WaitForPacketNoLock(echo_response, timeout, false);
351 if (echo_packet_result == PacketResult::Success) {
352 ++successful_responses;
353 if (response_regex.Execute(echo_response.GetStringRef())) {
356 } else if (successful_responses == 1) {
357 // We got something else back as the first successful
358 // response, it probably is the response to the packet we
359 // actually wanted, so copy it over if this is the first
360 // success and continue to try to get the qEcho response
361 packet = echo_response;
362 got_actual_response = true;
364 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
365 continue; // Packet timed out, continue waiting for a response
367 break; // Something else went wrong getting the packet back, we
368 // failed and are done trying
372 // We weren't able to sync back up with the server, we must abort
373 // otherwise all responses might not be from the right packets...
375 // We timed out, but were able to recover
376 if (got_actual_response) {
377 // We initially timed out, but we did get a response that came in
378 // before the successful reply to our qEcho packet, so lets say
379 // everything is fine...
380 return PacketResult::Success;
389 case eConnectionStatusSuccess:
390 // printf ("status = success but error = %s\n",
391 // error.AsCString("<invalid>"));
394 case eConnectionStatusEndOfFile:
395 case eConnectionStatusNoConnection:
396 case eConnectionStatusLostConnection:
397 case eConnectionStatusError:
406 return PacketResult::ErrorDisconnected;
408 return PacketResult::ErrorReplyTimeout;
410 return PacketResult::ErrorReplyFailed;
413 bool GDBRemoteCommunication::DecompressPacket() {
414 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
416 if (!CompressionIsEnabled())
419 size_t pkt_size = m_bytes.size();
421 // Smallest possible compressed packet is $N#00 - an uncompressed empty
422 // reply, most commonly indicating an unsupported packet. Anything less than
423 // 5 characters, it's definitely not a compressed packet.
427 if (m_bytes[0] != '$' && m_bytes[0] != '%')
429 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
432 size_t hash_mark_idx = m_bytes.find('#');
433 if (hash_mark_idx == std::string::npos)
435 if (hash_mark_idx + 2 >= m_bytes.size())
438 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
439 !::isxdigit(m_bytes[hash_mark_idx + 2]))
442 size_t content_length =
444 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
445 size_t content_start = 2; // The first character of the
446 // compressed/not-compressed text of the packet
447 size_t checksum_idx =
449 1; // The first character of the two hex checksum characters
451 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
452 // multiple packets. size_of_first_packet is the size of the initial packet
453 // which we'll replace with the decompressed version of, leaving the rest of
454 // m_bytes unmodified.
455 size_t size_of_first_packet = hash_mark_idx + 3;
457 // Compressed packets ("$C") start with a base10 number which is the size of
458 // the uncompressed payload, then a : and then the compressed data. e.g.
459 // $C1024:<binary>#00 Update content_start and content_length to only include
460 // the <binary> part of the packet.
462 uint64_t decompressed_bufsize = ULONG_MAX;
463 if (m_bytes[1] == 'C') {
464 size_t i = content_start;
465 while (i < hash_mark_idx && isdigit(m_bytes[i]))
467 if (i < hash_mark_idx && m_bytes[i] == ':') {
470 content_length = hash_mark_idx - content_start;
471 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
473 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), nullptr, 10);
474 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
475 m_bytes.erase(0, size_of_first_packet);
482 char packet_checksum_cstr[3];
483 packet_checksum_cstr[0] = m_bytes[checksum_idx];
484 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
485 packet_checksum_cstr[2] = '\0';
486 long packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
488 long actual_checksum = CalculcateChecksum(
489 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
490 bool success = packet_checksum == actual_checksum;
494 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
495 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
496 (uint8_t)actual_checksum);
498 // Send the ack or nack if needed
501 m_bytes.erase(0, size_of_first_packet);
508 if (m_bytes[1] == 'N') {
509 // This packet was not compressed -- delete the 'N' character at the start
510 // and the packet may be processed as-is.
515 // Reverse the gdb-remote binary escaping that was done to the compressed
516 // text to guard characters like '$', '#', '}', etc.
517 std::vector<uint8_t> unescaped_content;
518 unescaped_content.reserve(content_length);
519 size_t i = content_start;
520 while (i < hash_mark_idx) {
521 if (m_bytes[i] == '}') {
523 unescaped_content.push_back(m_bytes[i] ^ 0x20);
525 unescaped_content.push_back(m_bytes[i]);
530 uint8_t *decompressed_buffer = nullptr;
531 size_t decompressed_bytes = 0;
533 if (decompressed_bufsize != ULONG_MAX) {
534 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
535 if (decompressed_buffer == nullptr) {
536 m_bytes.erase(0, size_of_first_packet);
541 #if defined(HAVE_LIBCOMPRESSION)
542 if (m_compression_type == CompressionType::ZlibDeflate ||
543 m_compression_type == CompressionType::LZFSE ||
544 m_compression_type == CompressionType::LZ4 ||
545 m_compression_type == CompressionType::LZMA) {
546 compression_algorithm compression_type;
547 if (m_compression_type == CompressionType::LZFSE)
548 compression_type = COMPRESSION_LZFSE;
549 else if (m_compression_type == CompressionType::ZlibDeflate)
550 compression_type = COMPRESSION_ZLIB;
551 else if (m_compression_type == CompressionType::LZ4)
552 compression_type = COMPRESSION_LZ4_RAW;
553 else if (m_compression_type == CompressionType::LZMA)
554 compression_type = COMPRESSION_LZMA;
556 if (m_decompression_scratch_type != m_compression_type) {
557 if (m_decompression_scratch) {
558 free (m_decompression_scratch);
559 m_decompression_scratch = nullptr;
561 size_t scratchbuf_size = 0;
562 if (m_compression_type == CompressionType::LZFSE)
563 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
564 else if (m_compression_type == CompressionType::LZ4)
565 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
566 else if (m_compression_type == CompressionType::ZlibDeflate)
567 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
568 else if (m_compression_type == CompressionType::LZMA)
569 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZMA);
570 else if (m_compression_type == CompressionType::LZFSE)
571 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
572 if (scratchbuf_size > 0) {
573 m_decompression_scratch = (void*) malloc (scratchbuf_size);
574 m_decompression_scratch_type = m_compression_type;
578 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
579 decompressed_bytes = compression_decode_buffer(
580 decompressed_buffer, decompressed_bufsize,
581 (uint8_t *)unescaped_content.data(), unescaped_content.size(),
582 m_decompression_scratch, compression_type);
587 #if defined(HAVE_LIBZ)
588 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
589 decompressed_buffer != nullptr &&
590 m_compression_type == CompressionType::ZlibDeflate) {
592 memset(&stream, 0, sizeof(z_stream));
593 stream.next_in = (Bytef *)unescaped_content.data();
594 stream.avail_in = (uInt)unescaped_content.size();
596 stream.next_out = (Bytef *)decompressed_buffer;
597 stream.avail_out = decompressed_bufsize;
598 stream.total_out = 0;
599 stream.zalloc = Z_NULL;
600 stream.zfree = Z_NULL;
601 stream.opaque = Z_NULL;
603 if (inflateInit2(&stream, -15) == Z_OK) {
604 int status = inflate(&stream, Z_NO_FLUSH);
606 if (status == Z_STREAM_END) {
607 decompressed_bytes = stream.total_out;
613 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
614 if (decompressed_buffer)
615 free(decompressed_buffer);
616 m_bytes.erase(0, size_of_first_packet);
620 std::string new_packet;
621 new_packet.reserve(decompressed_bytes + 6);
622 new_packet.push_back(m_bytes[0]);
623 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
624 new_packet.push_back('#');
626 uint8_t decompressed_checksum = CalculcateChecksum(
627 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
628 char decompressed_checksum_str[3];
629 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
630 new_packet.append(decompressed_checksum_str);
632 new_packet.push_back('0');
633 new_packet.push_back('0');
636 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
639 free(decompressed_buffer);
643 GDBRemoteCommunication::PacketType
644 GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
645 StringExtractorGDBRemote &packet) {
646 // Put the packet data into the buffer in a thread safe fashion
647 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
649 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
651 if (src && src_len > 0) {
652 if (log && log->GetVerbose()) {
654 log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s",
655 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
657 m_bytes.append((const char *)src, src_len);
660 bool isNotifyPacket = false;
662 // Parse up the packets into gdb remote packets
663 if (!m_bytes.empty()) {
664 // end_idx must be one past the last valid packet byte. Start it off with
665 // an invalid value that is the same as the current index.
666 size_t content_start = 0;
667 size_t content_length = 0;
668 size_t total_length = 0;
669 size_t checksum_idx = std::string::npos;
671 // Size of packet before it is decompressed, for logging purposes
672 size_t original_packet_size = m_bytes.size();
673 if (CompressionIsEnabled()) {
674 if (!DecompressPacket()) {
676 return GDBRemoteCommunication::PacketType::Standard;
680 switch (m_bytes[0]) {
681 case '+': // Look for ack
682 case '-': // Look for cancel
683 case '\x03': // ^C to halt target
684 content_length = total_length = 1; // The command is one byte long...
687 case '%': // Async notify packet
688 isNotifyPacket = true;
692 // Look for a standard gdb packet?
694 size_t hash_pos = m_bytes.find('#');
695 if (hash_pos != std::string::npos) {
696 if (hash_pos + 2 < m_bytes.size()) {
697 checksum_idx = hash_pos + 1;
698 // Skip the dollar sign
700 // Don't include the # in the content or the $ in the content
702 content_length = hash_pos - 1;
705 hash_pos + 3; // Skip the # and the two hex checksum bytes
707 // Checksum bytes aren't all here yet
708 content_length = std::string::npos;
715 // We have an unexpected byte and we need to flush all bad data that is
716 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
717 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
718 // header) or of course, the end of the data in m_bytes...
719 const size_t bytes_len = m_bytes.size();
722 for (idx = 1; !done && idx < bytes_len; ++idx) {
723 switch (m_bytes[idx]) {
737 log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
738 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
739 m_bytes.erase(0, idx - 1);
743 if (content_length == std::string::npos) {
745 return GDBRemoteCommunication::PacketType::Invalid;
746 } else if (total_length > 0) {
748 // We have a valid packet...
749 assert(content_length <= m_bytes.size());
750 assert(total_length <= m_bytes.size());
751 assert(content_length <= total_length);
752 size_t content_end = content_start + content_length;
755 std::string &packet_str = packet.GetStringRef();
757 // If logging was just enabled and we have history, then dump out what
758 // we have to the log so we get the historical context. The Dump() call
759 // that logs all of the packet will set a boolean so that we don't dump
760 // this more than once
761 if (!m_history.DidDumpToLog())
765 // Only detect binary for packets that start with a '$' and have a
767 if (m_bytes[0] == '$' && total_length > 4) {
768 for (size_t i = 0; !binary && i < total_length; ++i) {
769 unsigned char c = m_bytes[i];
770 if (isprint(c) == 0 && isspace(c) == 0) {
778 if (CompressionIsEnabled())
779 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
780 (uint64_t)original_packet_size, (uint64_t)total_length,
783 strm.Printf("<%4" PRIu64 "> read packet: %c",
784 (uint64_t)total_length, m_bytes[0]);
785 for (size_t i = content_start; i < content_end; ++i) {
786 // Remove binary escaped bytes when displaying the packet...
787 const char ch = m_bytes[i];
789 // 0x7d is the escape character. The next character is to be
791 const char escapee = m_bytes[++i] ^ 0x20;
792 strm.Printf("%2.2x", escapee);
794 strm.Printf("%2.2x", (uint8_t)ch);
798 strm.Printf("%c%c%c", m_bytes[total_length - 3],
799 m_bytes[total_length - 2], m_bytes[total_length - 1]);
800 log->PutString(strm.GetString());
802 if (CompressionIsEnabled())
803 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
804 (uint64_t)original_packet_size, (uint64_t)total_length,
805 (int)(total_length), m_bytes.c_str());
807 log->Printf("<%4" PRIu64 "> read packet: %.*s",
808 (uint64_t)total_length, (int)(total_length),
813 m_history.AddPacket(m_bytes, total_length,
814 GDBRemoteCommunicationHistory::ePacketTypeRecv,
817 // Clear packet_str in case there is some existing data in it.
819 // Copy the packet from m_bytes to packet_str expanding the run-length
820 // encoding in the process. Reserve enough byte for the most common case
822 packet_str.reserve(m_bytes.length());
823 for (std::string::const_iterator c = m_bytes.begin() + content_start;
824 c != m_bytes.begin() + content_end; ++c) {
826 // '*' indicates RLE. Next character will give us the repeat count
827 // and previous character is what is to be repeated.
828 char char_to_repeat = packet_str.back();
829 // Number of time the previous character is repeated
830 int repeat_count = *++c + 3 - ' ';
831 // We have the char_to_repeat and repeat_count. Now push it in the
833 for (int i = 0; i < repeat_count; ++i)
834 packet_str.push_back(char_to_repeat);
835 } else if (*c == 0x7d) {
836 // 0x7d is the escape character. The next character is to be XOR'd
838 char escapee = *++c ^ 0x20;
839 packet_str.push_back(escapee);
841 packet_str.push_back(*c);
845 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
846 assert(checksum_idx < m_bytes.size());
847 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
848 ::isxdigit(m_bytes[checksum_idx + 1])) {
850 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
851 char packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
852 char actual_checksum = CalculcateChecksum(
853 llvm::StringRef(m_bytes).slice(content_start, content_end));
854 success = packet_checksum == actual_checksum;
857 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
859 (int)(total_length), m_bytes.c_str(),
860 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
862 // Send the ack or nack if needed
871 log->Printf("error: invalid checksum in packet: '%s'\n",
876 m_bytes.erase(0, total_length);
877 packet.SetFilePos(0);
880 return GDBRemoteCommunication::PacketType::Notify;
882 return GDBRemoteCommunication::PacketType::Standard;
886 return GDBRemoteCommunication::PacketType::Invalid;
889 Status GDBRemoteCommunication::StartListenThread(const char *hostname,
891 if (m_listen_thread.IsJoinable())
892 return Status("listen thread already running");
894 char listen_url[512];
895 if (hostname && hostname[0])
896 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
898 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
899 m_listen_url = listen_url;
900 SetConnection(new ConnectionFileDescriptor());
901 llvm::Expected<HostThread> listen_thread = ThreadLauncher::LaunchThread(
902 listen_url, GDBRemoteCommunication::ListenThread, this);
904 return Status(listen_thread.takeError());
905 m_listen_thread = *listen_thread;
910 bool GDBRemoteCommunication::JoinListenThread() {
911 if (m_listen_thread.IsJoinable())
912 m_listen_thread.Join(nullptr);
916 lldb::thread_result_t
917 GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
918 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
920 ConnectionFileDescriptor *connection =
921 (ConnectionFileDescriptor *)comm->GetConnection();
924 // Do the listen on another thread so we can continue on...
925 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
926 eConnectionStatusSuccess)
927 comm->SetConnection(nullptr);
932 Status GDBRemoteCommunication::StartDebugserverProcess(
933 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
934 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
935 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
937 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
938 __FUNCTION__, url ? url : "<empty>",
939 port ? *port : uint16_t(0));
942 // If we locate debugserver, keep that located version around
943 static FileSpec g_debugserver_file_spec;
945 char debugserver_path[PATH_MAX];
946 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
948 Environment host_env = Host::GetEnvironment();
950 // Always check to see if we have an environment override for the path to the
951 // debugserver to use and use it if we do.
952 std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
953 if (!env_debugserver_path.empty()) {
954 debugserver_file_spec.SetFile(env_debugserver_path,
955 FileSpec::Style::native);
957 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
958 "from environment variable: %s",
959 __FUNCTION__, env_debugserver_path.c_str());
961 debugserver_file_spec = g_debugserver_file_spec;
962 bool debugserver_exists =
963 FileSystem::Instance().Exists(debugserver_file_spec);
964 if (!debugserver_exists) {
965 // The debugserver binary is in the LLDB.framework/Resources directory.
966 debugserver_file_spec = HostInfo::GetSupportExeDir();
967 if (debugserver_file_spec) {
968 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
969 debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
970 if (debugserver_exists) {
973 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
974 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
976 g_debugserver_file_spec = debugserver_file_spec;
979 debugserver_file_spec =
980 platform->LocateExecutable(DEBUGSERVER_BASENAME);
982 debugserver_file_spec.Clear();
983 if (debugserver_file_spec) {
984 // Platform::LocateExecutable() wouldn't return a path if it doesn't
986 debugserver_exists = true;
989 log->Printf("GDBRemoteCommunication::%s() could not find "
990 "gdb-remote stub exe '%s'",
991 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
993 // Don't cache the platform specific GDB server binary as it could
994 // change from platform to platform
995 g_debugserver_file_spec.Clear();
1000 if (debugserver_exists) {
1001 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
1003 Args &debugserver_args = launch_info.GetArguments();
1004 debugserver_args.Clear();
1006 // Start args with "debugserver /file/path -r --"
1007 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
1009 #if !defined(__APPLE__)
1010 // First argument to lldb-server must be mode in which to run.
1011 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
1014 // If a url is supplied then use it
1016 debugserver_args.AppendArgument(llvm::StringRef(url));
1018 if (pass_comm_fd >= 0) {
1019 StreamString fd_arg;
1020 fd_arg.Printf("--fd=%i", pass_comm_fd);
1021 debugserver_args.AppendArgument(fd_arg.GetString());
1022 // Send "pass_comm_fd" down to the inferior so it can use it to
1023 // communicate back with this process
1024 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1027 // use native registers, not the GDB registers
1028 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
1030 if (launch_info.GetLaunchInSeparateProcessGroup()) {
1031 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
1034 llvm::SmallString<128> named_pipe_path;
1035 // socket_pipe is used by debug server to communicate back either
1036 // TCP port or domain socket name which it listens on.
1037 // The second purpose of the pipe to serve as a synchronization point -
1038 // once data is written to the pipe, debug server is up and running.
1041 // port is null when debug server should listen on domain socket - we're
1042 // not interested in port value but rather waiting for debug server to
1043 // become available.
1044 if (pass_comm_fd == -1) {
1046 // Create a temporary file to get the stdout/stderr and redirect the output of
1047 // the command into this file. We will later read this file if all goes well
1048 // and fill the data into "command_output_ptr"
1049 #if defined(__APPLE__)
1050 // Binding to port zero, we need to figure out what port it ends up
1051 // using using a named pipe...
1052 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1053 false, named_pipe_path);
1056 log->Printf("GDBRemoteCommunication::%s() "
1057 "named pipe creation failed: %s",
1058 __FUNCTION__, error.AsCString());
1061 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
1062 debugserver_args.AppendArgument(named_pipe_path);
1064 // Binding to port zero, we need to figure out what port it ends up
1065 // using using an unnamed pipe...
1066 error = socket_pipe.CreateNew(true);
1069 log->Printf("GDBRemoteCommunication::%s() "
1070 "unnamed pipe creation failed: %s",
1071 __FUNCTION__, error.AsCString());
1074 pipe_t write = socket_pipe.GetWritePipe();
1075 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1076 debugserver_args.AppendArgument(llvm::to_string(write));
1077 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
1080 // No host and port given, so lets listen on our end and make the
1081 // debugserver connect to us..
1082 error = StartListenThread("127.0.0.1", 0);
1085 log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1087 __FUNCTION__, error.AsCString());
1091 ConnectionFileDescriptor *connection =
1092 (ConnectionFileDescriptor *)GetConnection();
1093 // Wait for 10 seconds to resolve the bound port
1094 uint16_t port_ = connection->GetListeningPort(std::chrono::seconds(10));
1097 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1098 // Send the host and port down that debugserver and specify an option
1099 // so that it connects back to the port we are listening to in this
1101 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1102 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
1106 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1108 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1114 std::string env_debugserver_log_file =
1115 host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
1116 if (!env_debugserver_log_file.empty()) {
1117 debugserver_args.AppendArgument(
1118 llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
1121 #if defined(__APPLE__)
1122 const char *env_debugserver_log_flags =
1123 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1124 if (env_debugserver_log_flags) {
1125 debugserver_args.AppendArgument(
1126 llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
1129 std::string env_debugserver_log_channels =
1130 host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
1131 if (!env_debugserver_log_channels.empty()) {
1132 debugserver_args.AppendArgument(
1133 llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
1138 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1139 // env var doesn't come back.
1140 uint32_t env_var_index = 1;
1143 char env_var_name[64];
1144 snprintf(env_var_name, sizeof(env_var_name),
1145 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1146 std::string extra_arg = host_env.lookup(env_var_name);
1147 has_env_var = !extra_arg.empty();
1150 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
1152 log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1153 "to stub command line (%s)",
1154 __FUNCTION__, env_var_name, extra_arg.c_str());
1156 } while (has_env_var);
1158 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
1159 debugserver_args.AppendArgument(llvm::StringRef("--"));
1160 debugserver_args.AppendArguments(*inferior_args);
1163 // Copy the current environment to the gdbserver/debugserver instance
1164 launch_info.GetEnvironment() = host_env;
1166 // Close STDIN, STDOUT and STDERR.
1167 launch_info.AppendCloseFileAction(STDIN_FILENO);
1168 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1169 launch_info.AppendCloseFileAction(STDERR_FILENO);
1171 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1172 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1173 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1174 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1177 StreamString string_stream;
1178 Platform *const platform = nullptr;
1179 launch_info.Dump(string_stream, platform);
1180 log->Printf("launch info for gdb-remote stub:\n%s",
1181 string_stream.GetData());
1183 error = Host::LaunchProcess(launch_info);
1185 if (error.Success() &&
1186 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1187 pass_comm_fd == -1) {
1188 if (named_pipe_path.size() > 0) {
1189 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1192 log->Printf("GDBRemoteCommunication::%s() "
1193 "failed to open named pipe %s for reading: %s",
1194 __FUNCTION__, named_pipe_path.c_str(),
1198 if (socket_pipe.CanWrite())
1199 socket_pipe.CloseWriteFileDescriptor();
1200 if (socket_pipe.CanRead()) {
1201 char port_cstr[PATH_MAX] = {0};
1202 port_cstr[0] = '\0';
1203 size_t num_bytes = sizeof(port_cstr);
1204 // Read port from pipe with 10 second timeout.
1205 error = socket_pipe.ReadWithTimeout(
1206 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1207 if (error.Success() && (port != nullptr)) {
1208 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
1209 uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1210 if (*port == 0 || *port == child_port) {
1213 log->Printf("GDBRemoteCommunication::%s() "
1214 "debugserver listens %u port",
1215 __FUNCTION__, *port);
1218 log->Printf("GDBRemoteCommunication::%s() "
1219 "debugserver listening on port "
1220 "%d but requested port was %d",
1221 __FUNCTION__, (uint32_t)child_port,
1226 log->Printf("GDBRemoteCommunication::%s() "
1227 "failed to read a port value from pipe %s: %s",
1228 __FUNCTION__, named_pipe_path.c_str(),
1231 socket_pipe.Close();
1234 if (named_pipe_path.size() > 0) {
1235 const auto err = socket_pipe.Delete(named_pipe_path);
1239 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1240 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
1244 // Make sure we actually connect with the debugserver...
1248 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1253 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1260 void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1262 void GDBRemoteCommunication::SetHistoryStream(llvm::raw_ostream *strm) {
1263 m_history.SetStream(strm);
1267 GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1268 GDBRemoteCommunication &server) {
1269 const bool child_processes_inherit = false;
1270 const int backlog = 5;
1271 TCPSocket listen_socket(true, child_processes_inherit);
1272 if (llvm::Error error =
1273 listen_socket.Listen("127.0.0.1:0", backlog).ToError())
1276 Socket *accept_socket;
1277 std::future<Status> accept_status = std::async(
1278 std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1280 llvm::SmallString<32> remote_addr;
1281 llvm::raw_svector_ostream(remote_addr)
1282 << "connect://127.0.0.1:" << listen_socket.GetLocalPortNumber();
1284 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1285 new ConnectionFileDescriptor());
1287 if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)
1288 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1289 "Unable to connect: %s", status.AsCString());
1291 client.SetConnection(conn_up.release());
1292 if (llvm::Error error = accept_status.get().ToError())
1295 server.SetConnection(new ConnectionFileDescriptor(accept_socket));
1296 return llvm::Error::success();
1299 GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
1300 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
1301 : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1302 auto curr_timeout = gdb_comm.GetPacketTimeout();
1303 // Only update the timeout if the timeout is greater than the current
1304 // timeout. If the current timeout is larger, then just use that.
1305 if (curr_timeout < timeout) {
1306 m_timeout_modified = true;
1307 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1311 GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
1312 // Only restore the timeout if we set it in the constructor.
1313 if (m_timeout_modified)
1314 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1317 // This function is called via the Communications class read thread when bytes
1318 // become available for this connection. This function will consume all
1319 // incoming bytes and try to parse whole packets as they become available. Full
1320 // packets are placed in a queue, so that all packet requests can simply pop
1321 // from this queue. Async notification packets will be dispatched immediately
1322 // to the ProcessGDBRemote Async thread via an event.
1323 void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1324 size_t len, bool broadcast,
1325 lldb::ConnectionStatus status) {
1326 StringExtractorGDBRemote packet;
1329 PacketType type = CheckForPacket(bytes, len, packet);
1331 // scrub the data so we do not pass it back to CheckForPacket on future
1332 // passes of the loop
1336 // we may have received no packet so lets bail out
1337 if (type == PacketType::Invalid)
1340 if (type == PacketType::Standard) {
1341 // scope for the mutex
1343 // lock down the packet queue
1344 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1345 // push a new packet into the queue
1346 m_packet_queue.push(packet);
1347 // Signal condition variable that we have a packet
1348 m_condition_queue_not_empty.notify_one();
1352 if (type == PacketType::Notify) {
1353 // put this packet into an event
1354 const char *pdata = packet.GetStringRef().c_str();
1356 // as the communication class, we are a broadcaster and the async thread
1357 // is tuned to listen to us
1358 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1359 new EventDataBytes(pdata));
1364 void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1365 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1367 using PacketResult = GDBRemoteCommunication::PacketResult;
1370 case PacketResult::Success:
1371 Stream << "Success";
1373 case PacketResult::ErrorSendFailed:
1374 Stream << "ErrorSendFailed";
1376 case PacketResult::ErrorSendAck:
1377 Stream << "ErrorSendAck";
1379 case PacketResult::ErrorReplyFailed:
1380 Stream << "ErrorReplyFailed";
1382 case PacketResult::ErrorReplyTimeout:
1383 Stream << "ErrorReplyTimeout";
1385 case PacketResult::ErrorReplyInvalid:
1386 Stream << "ErrorReplyInvalid";
1388 case PacketResult::ErrorReplyAck:
1389 Stream << "ErrorReplyAck";
1391 case PacketResult::ErrorDisconnected:
1392 Stream << "ErrorDisconnected";
1394 case PacketResult::ErrorNoSequenceLock:
1395 Stream << "ErrorNoSequenceLock";