1 //===-- GDBRemoteCommunication.cpp ------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "GDBRemoteCommunication.h"
17 #include "lldb/Core/StreamFile.h"
18 #include "lldb/Host/ConnectionFileDescriptor.h"
19 #include "lldb/Host/FileSystem.h"
20 #include "lldb/Host/Host.h"
21 #include "lldb/Host/HostInfo.h"
22 #include "lldb/Host/Pipe.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/Target/Process.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(__APPLE__)
46 #define HAVE_LIBCOMPRESSION
47 #include <compression.h>
50 #if defined(HAVE_LIBZ)
55 using namespace lldb_private;
56 using namespace lldb_private::process_gdb_remote;
58 //----------------------------------------------------------------------
59 // GDBRemoteCommunication constructor
60 //----------------------------------------------------------------------
61 GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
62 const char *listener_name)
63 : Communication(comm_name),
64 #ifdef LLDB_CONFIGURATION_DEBUG
65 m_packet_timeout(1000),
69 m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
70 m_send_acks(true), m_compression_type(CompressionType::None),
71 m_listen_url(), m_decompression_scratch_type(CompressionType::None),
72 m_decompression_scratch(nullptr) {
73 // Unused unless HAVE_LIBCOMPRESSION is defined.
74 (void)m_decompression_scratch_type;
77 //----------------------------------------------------------------------
79 //----------------------------------------------------------------------
80 GDBRemoteCommunication::~GDBRemoteCommunication() {
85 if (m_decompression_scratch)
86 free (m_decompression_scratch);
88 // Stop the communications read thread which is used to parse all incoming
89 // packets. This function will block until the read thread returns.
90 if (m_read_thread_enabled)
94 char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
97 for (char c : payload)
100 return checksum & 255;
103 size_t GDBRemoteCommunication::SendAck() {
104 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
105 ConnectionStatus status = eConnectionStatusSuccess;
107 const size_t bytes_written = Write(&ch, 1, status, NULL);
109 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
110 m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend,
112 return bytes_written;
115 size_t GDBRemoteCommunication::SendNack() {
116 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
117 ConnectionStatus status = eConnectionStatusSuccess;
119 const size_t bytes_written = Write(&ch, 1, status, NULL);
121 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
122 m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend,
124 return bytes_written;
127 GDBRemoteCommunication::PacketResult
128 GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
129 StreamString packet(0, 4, eByteOrderBig);
131 packet.Write(payload.data(), payload.size());
133 packet.PutHex8(CalculcateChecksum(payload));
134 std::string packet_str = packet.GetString();
136 return SendRawPacketNoLock(packet_str);
139 GDBRemoteCommunication::PacketResult
140 GDBRemoteCommunication::SendRawPacketNoLock(llvm::StringRef packet,
143 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
144 ConnectionStatus status = eConnectionStatusSuccess;
145 const char *packet_data = packet.data();
146 const size_t packet_length = packet.size();
147 size_t bytes_written = Write(packet_data, packet_length, status, NULL);
149 size_t binary_start_offset = 0;
150 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
152 const char *first_comma = strchr(packet_data, ',');
154 const char *second_comma = strchr(first_comma + 1, ',');
156 binary_start_offset = second_comma - packet_data + 1;
160 // If logging was just enabled and we have history, then dump out what we
161 // have to the log so we get the historical context. The Dump() call that
162 // logs all of the packet will set a boolean so that we don't dump this
164 if (!m_history.DidDumpToLog())
167 if (binary_start_offset) {
169 // Print non binary data header
170 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
171 (int)binary_start_offset, packet_data);
173 // Print binary data exactly as sent
174 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
176 strm.Printf("\\x%2.2x", *p);
177 // Print the checksum
178 strm.Printf("%*s", (int)3, p);
179 log->PutString(strm.GetString());
181 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
182 (int)packet_length, packet_data);
185 m_history.AddPacket(packet.str(), packet_length,
186 GDBRemoteCommunicationHistory::ePacketTypeSend,
189 if (bytes_written == packet_length) {
190 if (!skip_ack && GetSendAcks())
193 return PacketResult::Success;
196 log->Printf("error: failed to send packet: %.*s", (int)packet_length,
200 return PacketResult::ErrorSendFailed;
203 GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
204 StringExtractorGDBRemote packet;
205 PacketResult result = ReadPacket(packet, GetPacketTimeout(), false);
206 if (result == PacketResult::Success) {
207 if (packet.GetResponseType() ==
208 StringExtractorGDBRemote::ResponseType::eAck)
209 return PacketResult::Success;
211 return PacketResult::ErrorSendAck;
216 GDBRemoteCommunication::PacketResult
217 GDBRemoteCommunication::ReadPacketWithOutputSupport(
218 StringExtractorGDBRemote &response, Timeout<std::micro> timeout,
219 bool sync_on_timeout,
220 llvm::function_ref<void(llvm::StringRef)> output_callback) {
221 auto result = ReadPacket(response, timeout, sync_on_timeout);
222 while (result == PacketResult::Success && response.IsNormalResponse() &&
223 response.PeekChar() == 'O') {
226 if (response.GetHexByteString(output))
227 output_callback(output);
228 result = ReadPacket(response, timeout, sync_on_timeout);
233 GDBRemoteCommunication::PacketResult
234 GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
235 Timeout<std::micro> timeout,
236 bool sync_on_timeout) {
237 if (m_read_thread_enabled)
238 return PopPacketFromQueue(response, timeout);
240 return WaitForPacketNoLock(response, timeout, sync_on_timeout);
243 // This function is called when a packet is requested.
244 // A whole packet is popped from the packet queue and returned to the caller.
245 // Packets are placed into this queue from the communication read thread. See
246 // GDBRemoteCommunication::AppendBytesToCache.
247 GDBRemoteCommunication::PacketResult
248 GDBRemoteCommunication::PopPacketFromQueue(StringExtractorGDBRemote &response,
249 Timeout<std::micro> timeout) {
250 auto pred = [&] { return !m_packet_queue.empty() && IsConnected(); };
251 // lock down the packet queue
252 std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
255 m_condition_queue_not_empty.wait(lock, pred);
257 if (!m_condition_queue_not_empty.wait_for(lock, *timeout, pred))
258 return PacketResult::ErrorReplyTimeout;
260 return PacketResult::ErrorDisconnected;
263 // get the front element of the queue
264 response = m_packet_queue.front();
266 // remove the front element
267 m_packet_queue.pop();
270 return PacketResult::Success;
273 GDBRemoteCommunication::PacketResult
274 GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
275 Timeout<std::micro> timeout,
276 bool sync_on_timeout) {
277 uint8_t buffer[8192];
280 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
282 // Check for a packet from our cache first without trying any reading...
283 if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
284 return PacketResult::Success;
286 bool timed_out = false;
287 bool disconnected = false;
288 while (IsConnected() && !timed_out) {
289 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
290 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
293 "Read(buffer, sizeof(buffer), timeout = {0}, "
294 "status = {1}, error = {2}) => bytes_read = {3}",
295 timeout, Communication::ConnectionStatusAsCString(status), error,
298 if (bytes_read > 0) {
299 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
300 return PacketResult::Success;
303 case eConnectionStatusTimedOut:
304 case eConnectionStatusInterrupted:
305 if (sync_on_timeout) {
306 //------------------------------------------------------------------
307 /// Sync the remote GDB server and make sure we get a response that
308 /// corresponds to what we send.
310 /// Sends a "qEcho" packet and makes sure it gets the exact packet
311 /// echoed back. If the qEcho packet isn't supported, we send a qC
312 /// packet and make sure we get a valid thread ID back. We use the
313 /// "qC" packet since its response if very unique: is responds with
314 /// "QC%x" where %x is the thread ID of the current thread. This
315 /// makes the response unique enough from other packet responses to
316 /// ensure we are back on track.
318 /// This packet is needed after we time out sending a packet so we
319 /// can ensure that we are getting the response for the packet we
320 /// are sending. There are no sequence IDs in the GDB remote
321 /// protocol (there used to be, but they are not supported anymore)
322 /// so if you timeout sending packet "abc", you might then send
323 /// packet "cde" and get the response for the previous "abc" packet.
324 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
325 /// many responses for packets can look like responses for other
326 /// packets. So if we timeout, we need to ensure that we can get
327 /// back on track. If we can't get back on track, we must
329 //------------------------------------------------------------------
330 bool sync_success = false;
331 bool got_actual_response = false;
332 // We timed out, we need to sync back up with the
333 char echo_packet[32];
334 int echo_packet_len = 0;
335 RegularExpression response_regex;
337 if (m_supports_qEcho == eLazyBoolYes) {
338 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
339 "qEcho:%u", ++m_echo_number);
340 std::string regex_str = "^";
341 regex_str += echo_packet;
343 response_regex.Compile(regex_str);
346 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
347 response_regex.Compile(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
350 PacketResult echo_packet_result =
351 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
352 if (echo_packet_result == PacketResult::Success) {
353 const uint32_t max_retries = 3;
354 uint32_t successful_responses = 0;
355 for (uint32_t i = 0; i < max_retries; ++i) {
356 StringExtractorGDBRemote echo_response;
358 WaitForPacketNoLock(echo_response, timeout, false);
359 if (echo_packet_result == PacketResult::Success) {
360 ++successful_responses;
361 if (response_regex.Execute(echo_response.GetStringRef())) {
364 } else if (successful_responses == 1) {
365 // We got something else back as the first successful
366 // response, it probably is the response to the packet we
367 // actually wanted, so copy it over if this is the first
368 // success and continue to try to get the qEcho response
369 packet = echo_response;
370 got_actual_response = true;
372 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
373 continue; // Packet timed out, continue waiting for a response
375 break; // Something else went wrong getting the packet back, we
376 // failed and are done trying
380 // We weren't able to sync back up with the server, we must abort
381 // otherwise all responses might not be from the right packets...
383 // We timed out, but were able to recover
384 if (got_actual_response) {
385 // We initially timed out, but we did get a response that came in
386 // before the successful reply to our qEcho packet, so lets say
387 // everything is fine...
388 return PacketResult::Success;
397 case eConnectionStatusSuccess:
398 // printf ("status = success but error = %s\n",
399 // error.AsCString("<invalid>"));
402 case eConnectionStatusEndOfFile:
403 case eConnectionStatusNoConnection:
404 case eConnectionStatusLostConnection:
405 case eConnectionStatusError:
414 return PacketResult::ErrorDisconnected;
416 return PacketResult::ErrorReplyTimeout;
418 return PacketResult::ErrorReplyFailed;
421 bool GDBRemoteCommunication::DecompressPacket() {
422 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
424 if (!CompressionIsEnabled())
427 size_t pkt_size = m_bytes.size();
429 // Smallest possible compressed packet is $N#00 - an uncompressed empty
430 // reply, most commonly indicating an unsupported packet. Anything less than
431 // 5 characters, it's definitely not a compressed packet.
435 if (m_bytes[0] != '$' && m_bytes[0] != '%')
437 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
440 size_t hash_mark_idx = m_bytes.find('#');
441 if (hash_mark_idx == std::string::npos)
443 if (hash_mark_idx + 2 >= m_bytes.size())
446 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
447 !::isxdigit(m_bytes[hash_mark_idx + 2]))
450 size_t content_length =
452 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
453 size_t content_start = 2; // The first character of the
454 // compressed/not-compressed text of the packet
455 size_t checksum_idx =
457 1; // The first character of the two hex checksum characters
459 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
460 // multiple packets. size_of_first_packet is the size of the initial packet
461 // which we'll replace with the decompressed version of, leaving the rest of
462 // m_bytes unmodified.
463 size_t size_of_first_packet = hash_mark_idx + 3;
465 // Compressed packets ("$C") start with a base10 number which is the size of
466 // the uncompressed payload, then a : and then the compressed data. e.g.
467 // $C1024:<binary>#00 Update content_start and content_length to only include
468 // the <binary> part of the packet.
470 uint64_t decompressed_bufsize = ULONG_MAX;
471 if (m_bytes[1] == 'C') {
472 size_t i = content_start;
473 while (i < hash_mark_idx && isdigit(m_bytes[i]))
475 if (i < hash_mark_idx && m_bytes[i] == ':') {
478 content_length = hash_mark_idx - content_start;
479 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
481 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), NULL, 10);
482 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
483 m_bytes.erase(0, size_of_first_packet);
490 char packet_checksum_cstr[3];
491 packet_checksum_cstr[0] = m_bytes[checksum_idx];
492 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
493 packet_checksum_cstr[2] = '\0';
494 long packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
496 long actual_checksum = CalculcateChecksum(
497 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
498 bool success = packet_checksum == actual_checksum;
502 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
503 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
504 (uint8_t)actual_checksum);
506 // Send the ack or nack if needed
509 m_bytes.erase(0, size_of_first_packet);
516 if (m_bytes[1] == 'N') {
517 // This packet was not compressed -- delete the 'N' character at the start
518 // and the packet may be processed as-is.
523 // Reverse the gdb-remote binary escaping that was done to the compressed
524 // text to guard characters like '$', '#', '}', etc.
525 std::vector<uint8_t> unescaped_content;
526 unescaped_content.reserve(content_length);
527 size_t i = content_start;
528 while (i < hash_mark_idx) {
529 if (m_bytes[i] == '}') {
531 unescaped_content.push_back(m_bytes[i] ^ 0x20);
533 unescaped_content.push_back(m_bytes[i]);
538 uint8_t *decompressed_buffer = nullptr;
539 size_t decompressed_bytes = 0;
541 if (decompressed_bufsize != ULONG_MAX) {
542 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
543 if (decompressed_buffer == nullptr) {
544 m_bytes.erase(0, size_of_first_packet);
549 #if defined(HAVE_LIBCOMPRESSION)
550 if (m_compression_type == CompressionType::ZlibDeflate ||
551 m_compression_type == CompressionType::LZFSE ||
552 m_compression_type == CompressionType::LZ4 ||
553 m_compression_type == CompressionType::LZMA) {
554 compression_algorithm compression_type;
555 if (m_compression_type == CompressionType::LZFSE)
556 compression_type = COMPRESSION_LZFSE;
557 else if (m_compression_type == CompressionType::ZlibDeflate)
558 compression_type = COMPRESSION_ZLIB;
559 else if (m_compression_type == CompressionType::LZ4)
560 compression_type = COMPRESSION_LZ4_RAW;
561 else if (m_compression_type == CompressionType::LZMA)
562 compression_type = COMPRESSION_LZMA;
564 if (m_decompression_scratch_type != m_compression_type) {
565 if (m_decompression_scratch) {
566 free (m_decompression_scratch);
567 m_decompression_scratch = nullptr;
569 size_t scratchbuf_size = 0;
570 if (m_compression_type == CompressionType::LZFSE)
571 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
572 else if (m_compression_type == CompressionType::LZ4)
573 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
574 else if (m_compression_type == CompressionType::ZlibDeflate)
575 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
576 else if (m_compression_type == CompressionType::LZMA)
577 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZMA);
578 else if (m_compression_type == CompressionType::LZFSE)
579 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
580 if (scratchbuf_size > 0) {
581 m_decompression_scratch = (void*) malloc (scratchbuf_size);
582 m_decompression_scratch_type = m_compression_type;
586 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
587 decompressed_bytes = compression_decode_buffer(
588 decompressed_buffer, decompressed_bufsize,
589 (uint8_t *)unescaped_content.data(), unescaped_content.size(),
590 m_decompression_scratch, compression_type);
595 #if defined(HAVE_LIBZ)
596 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
597 decompressed_buffer != nullptr &&
598 m_compression_type == CompressionType::ZlibDeflate) {
600 memset(&stream, 0, sizeof(z_stream));
601 stream.next_in = (Bytef *)unescaped_content.data();
602 stream.avail_in = (uInt)unescaped_content.size();
604 stream.next_out = (Bytef *)decompressed_buffer;
605 stream.avail_out = decompressed_bufsize;
606 stream.total_out = 0;
607 stream.zalloc = Z_NULL;
608 stream.zfree = Z_NULL;
609 stream.opaque = Z_NULL;
611 if (inflateInit2(&stream, -15) == Z_OK) {
612 int status = inflate(&stream, Z_NO_FLUSH);
614 if (status == Z_STREAM_END) {
615 decompressed_bytes = stream.total_out;
621 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
622 if (decompressed_buffer)
623 free(decompressed_buffer);
624 m_bytes.erase(0, size_of_first_packet);
628 std::string new_packet;
629 new_packet.reserve(decompressed_bytes + 6);
630 new_packet.push_back(m_bytes[0]);
631 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
632 new_packet.push_back('#');
634 uint8_t decompressed_checksum = CalculcateChecksum(
635 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
636 char decompressed_checksum_str[3];
637 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
638 new_packet.append(decompressed_checksum_str);
640 new_packet.push_back('0');
641 new_packet.push_back('0');
644 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
647 free(decompressed_buffer);
651 GDBRemoteCommunication::PacketType
652 GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
653 StringExtractorGDBRemote &packet) {
654 // Put the packet data into the buffer in a thread safe fashion
655 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
657 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
659 if (src && src_len > 0) {
660 if (log && log->GetVerbose()) {
662 log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s",
663 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
665 m_bytes.append((const char *)src, src_len);
668 bool isNotifyPacket = false;
670 // Parse up the packets into gdb remote packets
671 if (!m_bytes.empty()) {
672 // end_idx must be one past the last valid packet byte. Start it off with
673 // an invalid value that is the same as the current index.
674 size_t content_start = 0;
675 size_t content_length = 0;
676 size_t total_length = 0;
677 size_t checksum_idx = std::string::npos;
679 // Size of packet before it is decompressed, for logging purposes
680 size_t original_packet_size = m_bytes.size();
681 if (CompressionIsEnabled()) {
682 if (!DecompressPacket()) {
684 return GDBRemoteCommunication::PacketType::Standard;
688 switch (m_bytes[0]) {
689 case '+': // Look for ack
690 case '-': // Look for cancel
691 case '\x03': // ^C to halt target
692 content_length = total_length = 1; // The command is one byte long...
695 case '%': // Async notify packet
696 isNotifyPacket = true;
700 // Look for a standard gdb packet?
702 size_t hash_pos = m_bytes.find('#');
703 if (hash_pos != std::string::npos) {
704 if (hash_pos + 2 < m_bytes.size()) {
705 checksum_idx = hash_pos + 1;
706 // Skip the dollar sign
708 // Don't include the # in the content or the $ in the content
710 content_length = hash_pos - 1;
713 hash_pos + 3; // Skip the # and the two hex checksum bytes
715 // Checksum bytes aren't all here yet
716 content_length = std::string::npos;
723 // We have an unexpected byte and we need to flush all bad data that is
724 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
725 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
726 // header) or of course, the end of the data in m_bytes...
727 const size_t bytes_len = m_bytes.size();
730 for (idx = 1; !done && idx < bytes_len; ++idx) {
731 switch (m_bytes[idx]) {
745 log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
746 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
747 m_bytes.erase(0, idx - 1);
751 if (content_length == std::string::npos) {
753 return GDBRemoteCommunication::PacketType::Invalid;
754 } else if (total_length > 0) {
756 // We have a valid packet...
757 assert(content_length <= m_bytes.size());
758 assert(total_length <= m_bytes.size());
759 assert(content_length <= total_length);
760 size_t content_end = content_start + content_length;
763 std::string &packet_str = packet.GetStringRef();
765 // If logging was just enabled and we have history, then dump out what
766 // we have to the log so we get the historical context. The Dump() call
767 // that logs all of the packet will set a boolean so that we don't dump
768 // this more than once
769 if (!m_history.DidDumpToLog())
773 // Only detect binary for packets that start with a '$' and have a
775 if (m_bytes[0] == '$' && total_length > 4) {
776 for (size_t i = 0; !binary && i < total_length; ++i) {
777 unsigned char c = m_bytes[i];
778 if (isprint(c) == 0 && isspace(c) == 0) {
786 if (CompressionIsEnabled())
787 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
788 (uint64_t)original_packet_size, (uint64_t)total_length,
791 strm.Printf("<%4" PRIu64 "> read packet: %c",
792 (uint64_t)total_length, m_bytes[0]);
793 for (size_t i = content_start; i < content_end; ++i) {
794 // Remove binary escaped bytes when displaying the packet...
795 const char ch = m_bytes[i];
797 // 0x7d is the escape character. The next character is to be
799 const char escapee = m_bytes[++i] ^ 0x20;
800 strm.Printf("%2.2x", escapee);
802 strm.Printf("%2.2x", (uint8_t)ch);
806 strm.Printf("%c%c%c", m_bytes[total_length - 3],
807 m_bytes[total_length - 2], m_bytes[total_length - 1]);
808 log->PutString(strm.GetString());
810 if (CompressionIsEnabled())
811 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
812 (uint64_t)original_packet_size, (uint64_t)total_length,
813 (int)(total_length), m_bytes.c_str());
815 log->Printf("<%4" PRIu64 "> read packet: %.*s",
816 (uint64_t)total_length, (int)(total_length),
821 m_history.AddPacket(m_bytes, total_length,
822 GDBRemoteCommunicationHistory::ePacketTypeRecv,
825 // Clear packet_str in case there is some existing data in it.
827 // Copy the packet from m_bytes to packet_str expanding the run-length
828 // encoding in the process. Reserve enough byte for the most common case
830 packet_str.reserve(m_bytes.length());
831 for (std::string::const_iterator c = m_bytes.begin() + content_start;
832 c != m_bytes.begin() + content_end; ++c) {
834 // '*' indicates RLE. Next character will give us the repeat count
835 // and previous character is what is to be repeated.
836 char char_to_repeat = packet_str.back();
837 // Number of time the previous character is repeated
838 int repeat_count = *++c + 3 - ' ';
839 // We have the char_to_repeat and repeat_count. Now push it in the
841 for (int i = 0; i < repeat_count; ++i)
842 packet_str.push_back(char_to_repeat);
843 } else if (*c == 0x7d) {
844 // 0x7d is the escape character. The next character is to be XOR'd
846 char escapee = *++c ^ 0x20;
847 packet_str.push_back(escapee);
849 packet_str.push_back(*c);
853 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
854 assert(checksum_idx < m_bytes.size());
855 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
856 ::isxdigit(m_bytes[checksum_idx + 1])) {
858 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
859 char packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
860 char actual_checksum = CalculcateChecksum(
861 llvm::StringRef(m_bytes).slice(content_start, content_end));
862 success = packet_checksum == actual_checksum;
865 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
867 (int)(total_length), m_bytes.c_str(),
868 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
870 // Send the ack or nack if needed
879 log->Printf("error: invalid checksum in packet: '%s'\n",
884 m_bytes.erase(0, total_length);
885 packet.SetFilePos(0);
888 return GDBRemoteCommunication::PacketType::Notify;
890 return GDBRemoteCommunication::PacketType::Standard;
894 return GDBRemoteCommunication::PacketType::Invalid;
897 Status GDBRemoteCommunication::StartListenThread(const char *hostname,
900 if (m_listen_thread.IsJoinable()) {
901 error.SetErrorString("listen thread already running");
903 char listen_url[512];
904 if (hostname && hostname[0])
905 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname,
908 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
909 m_listen_url = listen_url;
910 SetConnection(new ConnectionFileDescriptor());
911 m_listen_thread = ThreadLauncher::LaunchThread(
912 listen_url, GDBRemoteCommunication::ListenThread, this, &error);
917 bool GDBRemoteCommunication::JoinListenThread() {
918 if (m_listen_thread.IsJoinable())
919 m_listen_thread.Join(nullptr);
923 lldb::thread_result_t
924 GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
925 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
927 ConnectionFileDescriptor *connection =
928 (ConnectionFileDescriptor *)comm->GetConnection();
931 // Do the listen on another thread so we can continue on...
932 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
933 eConnectionStatusSuccess)
934 comm->SetConnection(NULL);
939 Status GDBRemoteCommunication::StartDebugserverProcess(
940 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
941 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
942 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
944 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
945 __FUNCTION__, url ? url : "<empty>",
946 port ? *port : uint16_t(0));
949 // If we locate debugserver, keep that located version around
950 static FileSpec g_debugserver_file_spec;
952 char debugserver_path[PATH_MAX];
953 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
955 // Always check to see if we have an environment override for the path to the
956 // debugserver to use and use it if we do.
957 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
958 if (env_debugserver_path) {
959 debugserver_file_spec.SetFile(env_debugserver_path,
960 FileSpec::Style::native);
962 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
963 "from environment variable: %s",
964 __FUNCTION__, env_debugserver_path);
966 debugserver_file_spec = g_debugserver_file_spec;
967 bool debugserver_exists =
968 FileSystem::Instance().Exists(debugserver_file_spec);
969 if (!debugserver_exists) {
970 // The debugserver binary is in the LLDB.framework/Resources directory.
971 debugserver_file_spec = HostInfo::GetSupportExeDir();
972 if (debugserver_file_spec) {
973 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
974 debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
975 if (debugserver_exists) {
978 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
979 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
981 g_debugserver_file_spec = debugserver_file_spec;
983 debugserver_file_spec =
984 platform->LocateExecutable(DEBUGSERVER_BASENAME);
985 if (debugserver_file_spec) {
986 // Platform::LocateExecutable() wouldn't return a path if it doesn't
988 debugserver_exists = true;
991 log->Printf("GDBRemoteCommunication::%s() could not find "
992 "gdb-remote stub exe '%s'",
993 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
995 // Don't cache the platform specific GDB server binary as it could
996 // change from platform to platform
997 g_debugserver_file_spec.Clear();
1002 if (debugserver_exists) {
1003 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
1005 Args &debugserver_args = launch_info.GetArguments();
1006 debugserver_args.Clear();
1007 char arg_cstr[PATH_MAX];
1009 // Start args with "debugserver /file/path -r --"
1010 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
1012 #if !defined(__APPLE__)
1013 // First argument to lldb-server must be mode in which to run.
1014 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
1017 // If a url is supplied then use it
1019 debugserver_args.AppendArgument(llvm::StringRef(url));
1021 if (pass_comm_fd >= 0) {
1022 StreamString fd_arg;
1023 fd_arg.Printf("--fd=%i", pass_comm_fd);
1024 debugserver_args.AppendArgument(fd_arg.GetString());
1025 // Send "pass_comm_fd" down to the inferior so it can use it to
1026 // communicate back with this process
1027 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1030 // use native registers, not the GDB registers
1031 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
1033 if (launch_info.GetLaunchInSeparateProcessGroup()) {
1034 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
1037 llvm::SmallString<128> named_pipe_path;
1038 // socket_pipe is used by debug server to communicate back either
1039 // TCP port or domain socket name which it listens on.
1040 // The second purpose of the pipe to serve as a synchronization point -
1041 // once data is written to the pipe, debug server is up and running.
1044 // port is null when debug server should listen on domain socket - we're
1045 // not interested in port value but rather waiting for debug server to
1046 // become available.
1047 if (pass_comm_fd == -1) {
1049 // Create a temporary file to get the stdout/stderr and redirect the output of
1050 // the command into this file. We will later read this file if all goes well
1051 // and fill the data into "command_output_ptr"
1052 #if defined(__APPLE__)
1053 // Binding to port zero, we need to figure out what port it ends up
1054 // using using a named pipe...
1055 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1056 false, named_pipe_path);
1059 log->Printf("GDBRemoteCommunication::%s() "
1060 "named pipe creation failed: %s",
1061 __FUNCTION__, error.AsCString());
1064 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
1065 debugserver_args.AppendArgument(named_pipe_path);
1067 // Binding to port zero, we need to figure out what port it ends up
1068 // using using an unnamed pipe...
1069 error = socket_pipe.CreateNew(true);
1072 log->Printf("GDBRemoteCommunication::%s() "
1073 "unnamed pipe creation failed: %s",
1074 __FUNCTION__, error.AsCString());
1077 pipe_t write = socket_pipe.GetWritePipe();
1078 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1079 debugserver_args.AppendArgument(llvm::to_string(write));
1080 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
1083 // No host and port given, so lets listen on our end and make the
1084 // debugserver connect to us..
1085 error = StartListenThread("127.0.0.1", 0);
1088 log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1090 __FUNCTION__, error.AsCString());
1094 ConnectionFileDescriptor *connection =
1095 (ConnectionFileDescriptor *)GetConnection();
1096 // Wait for 10 seconds to resolve the bound port
1097 uint16_t port_ = connection->GetListeningPort(std::chrono::seconds(10));
1100 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1101 // Send the host and port down that debugserver and specify an option
1102 // so that it connects back to the port we are listening to in this
1104 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1105 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
1109 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1111 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1118 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1119 if (env_debugserver_log_file) {
1120 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-file=%s",
1121 env_debugserver_log_file);
1122 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
1125 #if defined(__APPLE__)
1126 const char *env_debugserver_log_flags =
1127 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1128 if (env_debugserver_log_flags) {
1129 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-flags=%s",
1130 env_debugserver_log_flags);
1131 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
1134 const char *env_debugserver_log_channels =
1135 getenv("LLDB_SERVER_LOG_CHANNELS");
1136 if (env_debugserver_log_channels) {
1137 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-channels=%s",
1138 env_debugserver_log_channels);
1139 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
1143 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1144 // env var doesn't come back.
1145 uint32_t env_var_index = 1;
1148 char env_var_name[64];
1149 snprintf(env_var_name, sizeof(env_var_name),
1150 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1151 const char *extra_arg = getenv(env_var_name);
1152 has_env_var = extra_arg != nullptr;
1155 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
1157 log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1158 "to stub command line (%s)",
1159 __FUNCTION__, env_var_name, extra_arg);
1161 } while (has_env_var);
1163 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
1164 debugserver_args.AppendArgument(llvm::StringRef("--"));
1165 debugserver_args.AppendArguments(*inferior_args);
1168 // Copy the current environment to the gdbserver/debugserver instance
1169 launch_info.GetEnvironment() = Host::GetEnvironment();
1171 // Close STDIN, STDOUT and STDERR.
1172 launch_info.AppendCloseFileAction(STDIN_FILENO);
1173 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1174 launch_info.AppendCloseFileAction(STDERR_FILENO);
1176 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1177 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1178 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1179 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1182 StreamString string_stream;
1183 Platform *const platform = nullptr;
1184 launch_info.Dump(string_stream, platform);
1185 log->Printf("launch info for gdb-remote stub:\n%s",
1186 string_stream.GetData());
1188 error = Host::LaunchProcess(launch_info);
1190 if (error.Success() &&
1191 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1192 pass_comm_fd == -1) {
1193 if (named_pipe_path.size() > 0) {
1194 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1197 log->Printf("GDBRemoteCommunication::%s() "
1198 "failed to open named pipe %s for reading: %s",
1199 __FUNCTION__, named_pipe_path.c_str(),
1203 if (socket_pipe.CanWrite())
1204 socket_pipe.CloseWriteFileDescriptor();
1205 if (socket_pipe.CanRead()) {
1206 char port_cstr[PATH_MAX] = {0};
1207 port_cstr[0] = '\0';
1208 size_t num_bytes = sizeof(port_cstr);
1209 // Read port from pipe with 10 second timeout.
1210 error = socket_pipe.ReadWithTimeout(
1211 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1212 if (error.Success() && (port != nullptr)) {
1213 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
1214 uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1215 if (*port == 0 || *port == child_port) {
1218 log->Printf("GDBRemoteCommunication::%s() "
1219 "debugserver listens %u port",
1220 __FUNCTION__, *port);
1223 log->Printf("GDBRemoteCommunication::%s() "
1224 "debugserver listening on port "
1225 "%d but requested port was %d",
1226 __FUNCTION__, (uint32_t)child_port,
1231 log->Printf("GDBRemoteCommunication::%s() "
1232 "failed to read a port value from pipe %s: %s",
1233 __FUNCTION__, named_pipe_path.c_str(),
1236 socket_pipe.Close();
1239 if (named_pipe_path.size() > 0) {
1240 const auto err = socket_pipe.Delete(named_pipe_path);
1244 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1245 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
1249 // Make sure we actually connect with the debugserver...
1253 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1258 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1265 void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1267 void GDBRemoteCommunication::SetHistoryStream(llvm::raw_ostream *strm) {
1268 m_history.SetStream(strm);
1272 GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1273 GDBRemoteCommunication &server) {
1274 const bool child_processes_inherit = false;
1275 const int backlog = 5;
1276 TCPSocket listen_socket(true, child_processes_inherit);
1277 if (llvm::Error error =
1278 listen_socket.Listen("127.0.0.1:0", backlog).ToError())
1281 Socket *accept_socket;
1282 std::future<Status> accept_status = std::async(
1283 std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1285 llvm::SmallString<32> remote_addr;
1286 llvm::raw_svector_ostream(remote_addr)
1287 << "connect://localhost:" << listen_socket.GetLocalPortNumber();
1289 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1290 new ConnectionFileDescriptor());
1291 if (conn_up->Connect(remote_addr, nullptr) != lldb::eConnectionStatusSuccess)
1292 return llvm::make_error<llvm::StringError>("Unable to connect",
1293 llvm::inconvertibleErrorCode());
1295 client.SetConnection(conn_up.release());
1296 if (llvm::Error error = accept_status.get().ToError())
1299 server.SetConnection(new ConnectionFileDescriptor(accept_socket));
1300 return llvm::Error::success();
1303 GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
1304 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
1305 : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1306 auto curr_timeout = gdb_comm.GetPacketTimeout();
1307 // Only update the timeout if the timeout is greater than the current
1308 // timeout. If the current timeout is larger, then just use that.
1309 if (curr_timeout < timeout) {
1310 m_timeout_modified = true;
1311 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1315 GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
1316 // Only restore the timeout if we set it in the constructor.
1317 if (m_timeout_modified)
1318 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1321 // This function is called via the Communications class read thread when bytes
1322 // become available for this connection. This function will consume all
1323 // incoming bytes and try to parse whole packets as they become available. Full
1324 // packets are placed in a queue, so that all packet requests can simply pop
1325 // from this queue. Async notification packets will be dispatched immediately
1326 // to the ProcessGDBRemote Async thread via an event.
1327 void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1328 size_t len, bool broadcast,
1329 lldb::ConnectionStatus status) {
1330 StringExtractorGDBRemote packet;
1333 PacketType type = CheckForPacket(bytes, len, packet);
1335 // scrub the data so we do not pass it back to CheckForPacket on future
1336 // passes of the loop
1340 // we may have received no packet so lets bail out
1341 if (type == PacketType::Invalid)
1344 if (type == PacketType::Standard) {
1345 // scope for the mutex
1347 // lock down the packet queue
1348 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1349 // push a new packet into the queue
1350 m_packet_queue.push(packet);
1351 // Signal condition variable that we have a packet
1352 m_condition_queue_not_empty.notify_one();
1356 if (type == PacketType::Notify) {
1357 // put this packet into an event
1358 const char *pdata = packet.GetStringRef().c_str();
1360 // as the communication class, we are a broadcaster and the async thread
1361 // is tuned to listen to us
1362 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1363 new EventDataBytes(pdata));
1368 void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1369 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1371 using PacketResult = GDBRemoteCommunication::PacketResult;
1374 case PacketResult::Success:
1375 Stream << "Success";
1377 case PacketResult::ErrorSendFailed:
1378 Stream << "ErrorSendFailed";
1380 case PacketResult::ErrorSendAck:
1381 Stream << "ErrorSendAck";
1383 case PacketResult::ErrorReplyFailed:
1384 Stream << "ErrorReplyFailed";
1386 case PacketResult::ErrorReplyTimeout:
1387 Stream << "ErrorReplyTimeout";
1389 case PacketResult::ErrorReplyInvalid:
1390 Stream << "ErrorReplyInvalid";
1392 case PacketResult::ErrorReplyAck:
1393 Stream << "ErrorReplyAck";
1395 case PacketResult::ErrorDisconnected:
1396 Stream << "ErrorDisconnected";
1398 case PacketResult::ErrorNoSequenceLock:
1399 Stream << "ErrorNoSequenceLock";