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"
18 // Other libraries and framework includes
19 #include "lldb/Core/StreamFile.h"
20 #include "lldb/Host/ConnectionFileDescriptor.h"
21 #include "lldb/Host/Host.h"
22 #include "lldb/Host/HostInfo.h"
23 #include "lldb/Host/Pipe.h"
24 #include "lldb/Host/Socket.h"
25 #include "lldb/Host/StringConvert.h"
26 #include "lldb/Host/ThreadLauncher.h"
27 #include "lldb/Target/Platform.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Utility/FileSpec.h"
30 #include "lldb/Utility/Log.h"
31 #include "lldb/Utility/RegularExpression.h"
32 #include "lldb/Utility/StreamString.h"
33 #include "llvm/ADT/SmallString.h"
34 #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::History::History(uint32_t size)
58 : m_packets(), m_curr_idx(0), m_total_packet_count(0),
59 m_dumped_to_log(false) {
60 m_packets.resize(size);
63 GDBRemoteCommunication::History::~History() {}
65 void GDBRemoteCommunication::History::AddPacket(char packet_char,
67 uint32_t bytes_transmitted) {
68 const size_t size = m_packets.size();
70 const uint32_t idx = GetNextIndex();
71 m_packets[idx].packet.assign(1, packet_char);
72 m_packets[idx].type = type;
73 m_packets[idx].bytes_transmitted = bytes_transmitted;
74 m_packets[idx].packet_idx = m_total_packet_count;
75 m_packets[idx].tid = llvm::get_threadid();
79 void GDBRemoteCommunication::History::AddPacket(const std::string &src,
82 uint32_t bytes_transmitted) {
83 const size_t size = m_packets.size();
85 const uint32_t idx = GetNextIndex();
86 m_packets[idx].packet.assign(src, 0, src_len);
87 m_packets[idx].type = type;
88 m_packets[idx].bytes_transmitted = bytes_transmitted;
89 m_packets[idx].packet_idx = m_total_packet_count;
90 m_packets[idx].tid = llvm::get_threadid();
94 void GDBRemoteCommunication::History::Dump(Stream &strm) const {
95 const uint32_t size = GetNumPacketsInHistory();
96 const uint32_t first_idx = GetFirstSavedPacketIndex();
97 const uint32_t stop_idx = m_curr_idx + size;
98 for (uint32_t i = first_idx; i < stop_idx; ++i) {
99 const uint32_t idx = NormalizeIndex(i);
100 const Entry &entry = m_packets[idx];
101 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
103 strm.Printf("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s\n",
104 entry.packet_idx, entry.tid, entry.bytes_transmitted,
105 (entry.type == ePacketTypeSend) ? "send" : "read",
106 entry.packet.c_str());
110 void GDBRemoteCommunication::History::Dump(Log *log) const {
111 if (log && !m_dumped_to_log) {
112 m_dumped_to_log = true;
113 const uint32_t size = GetNumPacketsInHistory();
114 const uint32_t first_idx = GetFirstSavedPacketIndex();
115 const uint32_t stop_idx = m_curr_idx + size;
116 for (uint32_t i = first_idx; i < stop_idx; ++i) {
117 const uint32_t idx = NormalizeIndex(i);
118 const Entry &entry = m_packets[idx];
119 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
121 log->Printf("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s",
122 entry.packet_idx, entry.tid, entry.bytes_transmitted,
123 (entry.type == ePacketTypeSend) ? "send" : "read",
124 entry.packet.c_str());
129 //----------------------------------------------------------------------
130 // GDBRemoteCommunication constructor
131 //----------------------------------------------------------------------
132 GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
133 const char *listener_name)
134 : Communication(comm_name),
135 #ifdef LLDB_CONFIGURATION_DEBUG
136 m_packet_timeout(1000),
140 m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
141 m_send_acks(true), m_compression_type(CompressionType::None),
145 //----------------------------------------------------------------------
147 //----------------------------------------------------------------------
148 GDBRemoteCommunication::~GDBRemoteCommunication() {
153 // Stop the communications read thread which is used to parse all incoming
154 // packets. This function will block until the read thread returns.
155 if (m_read_thread_enabled)
159 char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
162 for (char c : payload)
165 return checksum & 255;
168 size_t GDBRemoteCommunication::SendAck() {
169 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
170 ConnectionStatus status = eConnectionStatusSuccess;
172 const size_t bytes_written = Write(&ch, 1, status, NULL);
174 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
175 m_history.AddPacket(ch, History::ePacketTypeSend, bytes_written);
176 return bytes_written;
179 size_t GDBRemoteCommunication::SendNack() {
180 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
181 ConnectionStatus status = eConnectionStatusSuccess;
183 const size_t bytes_written = Write(&ch, 1, status, NULL);
185 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
186 m_history.AddPacket(ch, History::ePacketTypeSend, bytes_written);
187 return bytes_written;
190 GDBRemoteCommunication::PacketResult
191 GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
193 StreamString packet(0, 4, eByteOrderBig);
196 packet.Write(payload.data(), payload.size());
198 packet.PutHex8(CalculcateChecksum(payload));
200 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
201 ConnectionStatus status = eConnectionStatusSuccess;
202 // TODO: Don't shimmy through a std::string, just use StringRef.
203 std::string packet_str = packet.GetString();
204 const char *packet_data = packet_str.c_str();
205 const size_t packet_length = packet.GetSize();
206 size_t bytes_written = Write(packet_data, packet_length, status, NULL);
208 size_t binary_start_offset = 0;
209 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
211 const char *first_comma = strchr(packet_data, ',');
213 const char *second_comma = strchr(first_comma + 1, ',');
215 binary_start_offset = second_comma - packet_data + 1;
219 // If logging was just enabled and we have history, then dump out what we
220 // have to the log so we get the historical context. The Dump() call that
221 // logs all of the packet will set a boolean so that we don't dump this
223 if (!m_history.DidDumpToLog())
226 if (binary_start_offset) {
228 // Print non binary data header
229 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
230 (int)binary_start_offset, packet_data);
232 // Print binary data exactly as sent
233 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
235 strm.Printf("\\x%2.2x", *p);
236 // Print the checksum
237 strm.Printf("%*s", (int)3, p);
238 log->PutString(strm.GetString());
240 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
241 (int)packet_length, packet_data);
244 m_history.AddPacket(packet.GetString(), packet_length,
245 History::ePacketTypeSend, bytes_written);
247 if (bytes_written == packet_length) {
251 return PacketResult::Success;
254 log->Printf("error: failed to send packet: %.*s", (int)packet_length,
258 return PacketResult::ErrorSendFailed;
261 GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
262 StringExtractorGDBRemote packet;
263 PacketResult result = ReadPacket(packet, GetPacketTimeout(), false);
264 if (result == PacketResult::Success) {
265 if (packet.GetResponseType() ==
266 StringExtractorGDBRemote::ResponseType::eAck)
267 return PacketResult::Success;
269 return PacketResult::ErrorSendAck;
274 GDBRemoteCommunication::PacketResult
275 GDBRemoteCommunication::ReadPacketWithOutputSupport(
276 StringExtractorGDBRemote &response, Timeout<std::micro> timeout,
277 bool sync_on_timeout,
278 llvm::function_ref<void(llvm::StringRef)> output_callback) {
279 auto result = ReadPacket(response, timeout, sync_on_timeout);
280 while (result == PacketResult::Success && response.IsNormalResponse() &&
281 response.PeekChar() == 'O') {
284 if (response.GetHexByteString(output))
285 output_callback(output);
286 result = ReadPacket(response, timeout, sync_on_timeout);
291 GDBRemoteCommunication::PacketResult
292 GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
293 Timeout<std::micro> timeout,
294 bool sync_on_timeout) {
295 if (m_read_thread_enabled)
296 return PopPacketFromQueue(response, timeout);
298 return WaitForPacketNoLock(response, timeout, sync_on_timeout);
301 // This function is called when a packet is requested.
302 // A whole packet is popped from the packet queue and returned to the caller.
303 // Packets are placed into this queue from the communication read thread. See
304 // GDBRemoteCommunication::AppendBytesToCache.
305 GDBRemoteCommunication::PacketResult
306 GDBRemoteCommunication::PopPacketFromQueue(StringExtractorGDBRemote &response,
307 Timeout<std::micro> timeout) {
308 auto pred = [&] { return !m_packet_queue.empty() && IsConnected(); };
309 // lock down the packet queue
310 std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
313 m_condition_queue_not_empty.wait(lock, pred);
315 if (!m_condition_queue_not_empty.wait_for(lock, *timeout, pred))
316 return PacketResult::ErrorReplyTimeout;
318 return PacketResult::ErrorDisconnected;
321 // get the front element of the queue
322 response = m_packet_queue.front();
324 // remove the front element
325 m_packet_queue.pop();
328 return PacketResult::Success;
331 GDBRemoteCommunication::PacketResult
332 GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
333 Timeout<std::micro> timeout,
334 bool sync_on_timeout) {
335 uint8_t buffer[8192];
338 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
340 // Check for a packet from our cache first without trying any reading...
341 if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
342 return PacketResult::Success;
344 bool timed_out = false;
345 bool disconnected = false;
346 while (IsConnected() && !timed_out) {
347 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
348 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
351 "Read(buffer, sizeof(buffer), timeout = {0}, "
352 "status = {1}, error = {2}) => bytes_read = {3}",
353 timeout, Communication::ConnectionStatusAsCString(status), error,
356 if (bytes_read > 0) {
357 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
358 return PacketResult::Success;
361 case eConnectionStatusTimedOut:
362 case eConnectionStatusInterrupted:
363 if (sync_on_timeout) {
364 //------------------------------------------------------------------
365 /// Sync the remote GDB server and make sure we get a response that
366 /// corresponds to what we send.
368 /// Sends a "qEcho" packet and makes sure it gets the exact packet
369 /// echoed back. If the qEcho packet isn't supported, we send a qC
370 /// packet and make sure we get a valid thread ID back. We use the
371 /// "qC" packet since its response if very unique: is responds with
372 /// "QC%x" where %x is the thread ID of the current thread. This
373 /// makes the response unique enough from other packet responses to
374 /// ensure we are back on track.
376 /// This packet is needed after we time out sending a packet so we
377 /// can ensure that we are getting the response for the packet we
378 /// are sending. There are no sequence IDs in the GDB remote
379 /// protocol (there used to be, but they are not supported anymore)
380 /// so if you timeout sending packet "abc", you might then send
381 /// packet "cde" and get the response for the previous "abc" packet.
382 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
383 /// many responses for packets can look like responses for other
384 /// packets. So if we timeout, we need to ensure that we can get
385 /// back on track. If we can't get back on track, we must
387 //------------------------------------------------------------------
388 bool sync_success = false;
389 bool got_actual_response = false;
390 // We timed out, we need to sync back up with the
391 char echo_packet[32];
392 int echo_packet_len = 0;
393 RegularExpression response_regex;
395 if (m_supports_qEcho == eLazyBoolYes) {
396 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
397 "qEcho:%u", ++m_echo_number);
398 std::string regex_str = "^";
399 regex_str += echo_packet;
401 response_regex.Compile(regex_str);
404 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
405 response_regex.Compile(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
408 PacketResult echo_packet_result =
409 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
410 if (echo_packet_result == PacketResult::Success) {
411 const uint32_t max_retries = 3;
412 uint32_t successful_responses = 0;
413 for (uint32_t i = 0; i < max_retries; ++i) {
414 StringExtractorGDBRemote echo_response;
416 WaitForPacketNoLock(echo_response, timeout, false);
417 if (echo_packet_result == PacketResult::Success) {
418 ++successful_responses;
419 if (response_regex.Execute(echo_response.GetStringRef())) {
422 } else if (successful_responses == 1) {
423 // We got something else back as the first successful
424 // response, it probably is the response to the packet we
425 // actually wanted, so copy it over if this is the first
426 // success and continue to try to get the qEcho response
427 packet = echo_response;
428 got_actual_response = true;
430 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
431 continue; // Packet timed out, continue waiting for a response
433 break; // Something else went wrong getting the packet back, we
434 // failed and are done trying
438 // We weren't able to sync back up with the server, we must abort
439 // otherwise all responses might not be from the right packets...
441 // We timed out, but were able to recover
442 if (got_actual_response) {
443 // We initially timed out, but we did get a response that came in
444 // before the successful reply to our qEcho packet, so lets say
445 // everything is fine...
446 return PacketResult::Success;
455 case eConnectionStatusSuccess:
456 // printf ("status = success but error = %s\n",
457 // error.AsCString("<invalid>"));
460 case eConnectionStatusEndOfFile:
461 case eConnectionStatusNoConnection:
462 case eConnectionStatusLostConnection:
463 case eConnectionStatusError:
472 return PacketResult::ErrorDisconnected;
474 return PacketResult::ErrorReplyTimeout;
476 return PacketResult::ErrorReplyFailed;
479 bool GDBRemoteCommunication::DecompressPacket() {
480 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
482 if (!CompressionIsEnabled())
485 size_t pkt_size = m_bytes.size();
487 // Smallest possible compressed packet is $N#00 - an uncompressed empty
488 // reply, most commonly indicating an unsupported packet. Anything less than
489 // 5 characters, it's definitely not a compressed packet.
493 if (m_bytes[0] != '$' && m_bytes[0] != '%')
495 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
498 size_t hash_mark_idx = m_bytes.find('#');
499 if (hash_mark_idx == std::string::npos)
501 if (hash_mark_idx + 2 >= m_bytes.size())
504 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
505 !::isxdigit(m_bytes[hash_mark_idx + 2]))
508 size_t content_length =
510 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
511 size_t content_start = 2; // The first character of the
512 // compressed/not-compressed text of the packet
513 size_t checksum_idx =
515 1; // The first character of the two hex checksum characters
517 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
518 // multiple packets. size_of_first_packet is the size of the initial packet
519 // which we'll replace with the decompressed version of, leaving the rest of
520 // m_bytes unmodified.
521 size_t size_of_first_packet = hash_mark_idx + 3;
523 // Compressed packets ("$C") start with a base10 number which is the size of
524 // the uncompressed payload, then a : and then the compressed data. e.g.
525 // $C1024:<binary>#00 Update content_start and content_length to only include
526 // the <binary> part of the packet.
528 uint64_t decompressed_bufsize = ULONG_MAX;
529 if (m_bytes[1] == 'C') {
530 size_t i = content_start;
531 while (i < hash_mark_idx && isdigit(m_bytes[i]))
533 if (i < hash_mark_idx && m_bytes[i] == ':') {
536 content_length = hash_mark_idx - content_start;
537 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
539 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), NULL, 10);
540 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
541 m_bytes.erase(0, size_of_first_packet);
548 char packet_checksum_cstr[3];
549 packet_checksum_cstr[0] = m_bytes[checksum_idx];
550 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
551 packet_checksum_cstr[2] = '\0';
552 long packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
554 long actual_checksum = CalculcateChecksum(
555 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
556 bool success = packet_checksum == actual_checksum;
560 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
561 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
562 (uint8_t)actual_checksum);
564 // Send the ack or nack if needed
567 m_bytes.erase(0, size_of_first_packet);
574 if (m_bytes[1] == 'N') {
575 // This packet was not compressed -- delete the 'N' character at the start
576 // and the packet may be processed as-is.
581 // Reverse the gdb-remote binary escaping that was done to the compressed
582 // text to guard characters like '$', '#', '}', etc.
583 std::vector<uint8_t> unescaped_content;
584 unescaped_content.reserve(content_length);
585 size_t i = content_start;
586 while (i < hash_mark_idx) {
587 if (m_bytes[i] == '}') {
589 unescaped_content.push_back(m_bytes[i] ^ 0x20);
591 unescaped_content.push_back(m_bytes[i]);
596 uint8_t *decompressed_buffer = nullptr;
597 size_t decompressed_bytes = 0;
599 if (decompressed_bufsize != ULONG_MAX) {
600 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize + 1);
601 if (decompressed_buffer == nullptr) {
602 m_bytes.erase(0, size_of_first_packet);
607 #if defined(HAVE_LIBCOMPRESSION)
608 // libcompression is weak linked so check that compression_decode_buffer() is
610 if (m_compression_type == CompressionType::ZlibDeflate ||
611 m_compression_type == CompressionType::LZFSE ||
612 m_compression_type == CompressionType::LZ4) {
613 compression_algorithm compression_type;
614 if (m_compression_type == CompressionType::LZFSE)
615 compression_type = COMPRESSION_LZFSE;
616 else if (m_compression_type == CompressionType::ZlibDeflate)
617 compression_type = COMPRESSION_ZLIB;
618 else if (m_compression_type == CompressionType::LZ4)
619 compression_type = COMPRESSION_LZ4_RAW;
620 else if (m_compression_type == CompressionType::LZMA)
621 compression_type = COMPRESSION_LZMA;
623 // If we have the expected size of the decompressed payload, we can
624 // allocate the right-sized buffer and do it. If we don't have that
625 // information, we'll need to try decoding into a big buffer and if the
626 // buffer wasn't big enough, increase it and try again.
628 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
629 decompressed_bytes = compression_decode_buffer(
630 decompressed_buffer, decompressed_bufsize + 10,
631 (uint8_t *)unescaped_content.data(), unescaped_content.size(), NULL,
637 #if defined(HAVE_LIBZ)
638 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
639 decompressed_buffer != nullptr &&
640 m_compression_type == CompressionType::ZlibDeflate) {
642 memset(&stream, 0, sizeof(z_stream));
643 stream.next_in = (Bytef *)unescaped_content.data();
644 stream.avail_in = (uInt)unescaped_content.size();
646 stream.next_out = (Bytef *)decompressed_buffer;
647 stream.avail_out = decompressed_bufsize;
648 stream.total_out = 0;
649 stream.zalloc = Z_NULL;
650 stream.zfree = Z_NULL;
651 stream.opaque = Z_NULL;
653 if (inflateInit2(&stream, -15) == Z_OK) {
654 int status = inflate(&stream, Z_NO_FLUSH);
656 if (status == Z_STREAM_END) {
657 decompressed_bytes = stream.total_out;
663 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
664 if (decompressed_buffer)
665 free(decompressed_buffer);
666 m_bytes.erase(0, size_of_first_packet);
670 std::string new_packet;
671 new_packet.reserve(decompressed_bytes + 6);
672 new_packet.push_back(m_bytes[0]);
673 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
674 new_packet.push_back('#');
676 uint8_t decompressed_checksum = CalculcateChecksum(
677 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
678 char decompressed_checksum_str[3];
679 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
680 new_packet.append(decompressed_checksum_str);
682 new_packet.push_back('0');
683 new_packet.push_back('0');
686 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
689 free(decompressed_buffer);
693 GDBRemoteCommunication::PacketType
694 GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
695 StringExtractorGDBRemote &packet) {
696 // Put the packet data into the buffer in a thread safe fashion
697 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
699 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
701 if (src && src_len > 0) {
702 if (log && log->GetVerbose()) {
704 log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s",
705 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
707 m_bytes.append((const char *)src, src_len);
710 bool isNotifyPacket = false;
712 // Parse up the packets into gdb remote packets
713 if (!m_bytes.empty()) {
714 // end_idx must be one past the last valid packet byte. Start it off with
715 // an invalid value that is the same as the current index.
716 size_t content_start = 0;
717 size_t content_length = 0;
718 size_t total_length = 0;
719 size_t checksum_idx = std::string::npos;
721 // Size of packet before it is decompressed, for logging purposes
722 size_t original_packet_size = m_bytes.size();
723 if (CompressionIsEnabled()) {
724 if (DecompressPacket() == false) {
726 return GDBRemoteCommunication::PacketType::Standard;
730 switch (m_bytes[0]) {
731 case '+': // Look for ack
732 case '-': // Look for cancel
733 case '\x03': // ^C to halt target
734 content_length = total_length = 1; // The command is one byte long...
737 case '%': // Async notify packet
738 isNotifyPacket = true;
742 // Look for a standard gdb packet?
744 size_t hash_pos = m_bytes.find('#');
745 if (hash_pos != std::string::npos) {
746 if (hash_pos + 2 < m_bytes.size()) {
747 checksum_idx = hash_pos + 1;
748 // Skip the dollar sign
750 // Don't include the # in the content or the $ in the content
752 content_length = hash_pos - 1;
755 hash_pos + 3; // Skip the # and the two hex checksum bytes
757 // Checksum bytes aren't all here yet
758 content_length = std::string::npos;
765 // We have an unexpected byte and we need to flush all bad data that is
766 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
767 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
768 // header) or of course, the end of the data in m_bytes...
769 const size_t bytes_len = m_bytes.size();
772 for (idx = 1; !done && idx < bytes_len; ++idx) {
773 switch (m_bytes[idx]) {
787 log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
788 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
789 m_bytes.erase(0, idx - 1);
793 if (content_length == std::string::npos) {
795 return GDBRemoteCommunication::PacketType::Invalid;
796 } else if (total_length > 0) {
798 // We have a valid packet...
799 assert(content_length <= m_bytes.size());
800 assert(total_length <= m_bytes.size());
801 assert(content_length <= total_length);
802 size_t content_end = content_start + content_length;
805 std::string &packet_str = packet.GetStringRef();
807 // If logging was just enabled and we have history, then dump out what
808 // we have to the log so we get the historical context. The Dump() call
809 // that logs all of the packet will set a boolean so that we don't dump
810 // this more than once
811 if (!m_history.DidDumpToLog())
815 // Only detect binary for packets that start with a '$' and have a
817 if (m_bytes[0] == '$' && total_length > 4) {
818 for (size_t i = 0; !binary && i < total_length; ++i) {
819 unsigned char c = m_bytes[i];
820 if (isprint(c) == 0 && isspace(c) == 0) {
828 if (CompressionIsEnabled())
829 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
830 (uint64_t)original_packet_size, (uint64_t)total_length,
833 strm.Printf("<%4" PRIu64 "> read packet: %c",
834 (uint64_t)total_length, m_bytes[0]);
835 for (size_t i = content_start; i < content_end; ++i) {
836 // Remove binary escaped bytes when displaying the packet...
837 const char ch = m_bytes[i];
839 // 0x7d is the escape character. The next character is to be
841 const char escapee = m_bytes[++i] ^ 0x20;
842 strm.Printf("%2.2x", escapee);
844 strm.Printf("%2.2x", (uint8_t)ch);
848 strm.Printf("%c%c%c", m_bytes[total_length - 3],
849 m_bytes[total_length - 2], m_bytes[total_length - 1]);
850 log->PutString(strm.GetString());
852 if (CompressionIsEnabled())
853 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
854 (uint64_t)original_packet_size, (uint64_t)total_length,
855 (int)(total_length), m_bytes.c_str());
857 log->Printf("<%4" PRIu64 "> read packet: %.*s",
858 (uint64_t)total_length, (int)(total_length),
863 m_history.AddPacket(m_bytes, total_length, History::ePacketTypeRecv,
866 // Clear packet_str in case there is some existing data in it.
868 // Copy the packet from m_bytes to packet_str expanding the run-length
869 // encoding in the process. Reserve enough byte for the most common case
871 packet_str.reserve(m_bytes.length());
872 for (std::string::const_iterator c = m_bytes.begin() + content_start;
873 c != m_bytes.begin() + content_end; ++c) {
875 // '*' indicates RLE. Next character will give us the repeat count
876 // and previous character is what is to be repeated.
877 char char_to_repeat = packet_str.back();
878 // Number of time the previous character is repeated
879 int repeat_count = *++c + 3 - ' ';
880 // We have the char_to_repeat and repeat_count. Now push it in the
882 for (int i = 0; i < repeat_count; ++i)
883 packet_str.push_back(char_to_repeat);
884 } else if (*c == 0x7d) {
885 // 0x7d is the escape character. The next character is to be XOR'd
887 char escapee = *++c ^ 0x20;
888 packet_str.push_back(escapee);
890 packet_str.push_back(*c);
894 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
895 assert(checksum_idx < m_bytes.size());
896 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
897 ::isxdigit(m_bytes[checksum_idx + 1])) {
899 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
900 char packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
901 char actual_checksum = CalculcateChecksum(
902 llvm::StringRef(m_bytes).slice(content_start, content_end));
903 success = packet_checksum == actual_checksum;
906 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
908 (int)(total_length), m_bytes.c_str(),
909 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
911 // Send the ack or nack if needed
920 log->Printf("error: invalid checksum in packet: '%s'\n",
925 m_bytes.erase(0, total_length);
926 packet.SetFilePos(0);
929 return GDBRemoteCommunication::PacketType::Notify;
931 return GDBRemoteCommunication::PacketType::Standard;
935 return GDBRemoteCommunication::PacketType::Invalid;
938 Status GDBRemoteCommunication::StartListenThread(const char *hostname,
941 if (m_listen_thread.IsJoinable()) {
942 error.SetErrorString("listen thread already running");
944 char listen_url[512];
945 if (hostname && hostname[0])
946 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname,
949 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
950 m_listen_url = listen_url;
951 SetConnection(new ConnectionFileDescriptor());
952 m_listen_thread = ThreadLauncher::LaunchThread(
953 listen_url, GDBRemoteCommunication::ListenThread, this, &error);
958 bool GDBRemoteCommunication::JoinListenThread() {
959 if (m_listen_thread.IsJoinable())
960 m_listen_thread.Join(nullptr);
964 lldb::thread_result_t
965 GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
966 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
968 ConnectionFileDescriptor *connection =
969 (ConnectionFileDescriptor *)comm->GetConnection();
972 // Do the listen on another thread so we can continue on...
973 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
974 eConnectionStatusSuccess)
975 comm->SetConnection(NULL);
980 Status GDBRemoteCommunication::StartDebugserverProcess(
981 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
982 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
983 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
985 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
986 __FUNCTION__, url ? url : "<empty>",
987 port ? *port : uint16_t(0));
990 // If we locate debugserver, keep that located version around
991 static FileSpec g_debugserver_file_spec;
993 char debugserver_path[PATH_MAX];
994 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
996 // Always check to see if we have an environment override for the path to the
997 // debugserver to use and use it if we do.
998 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
999 if (env_debugserver_path) {
1000 debugserver_file_spec.SetFile(env_debugserver_path, false,
1001 FileSpec::Style::native);
1003 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
1004 "from environment variable: %s",
1005 __FUNCTION__, env_debugserver_path);
1007 debugserver_file_spec = g_debugserver_file_spec;
1008 bool debugserver_exists = debugserver_file_spec.Exists();
1009 if (!debugserver_exists) {
1010 // The debugserver binary is in the LLDB.framework/Resources directory.
1011 debugserver_file_spec = HostInfo::GetSupportExeDir();
1012 if (debugserver_file_spec) {
1013 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
1014 debugserver_exists = debugserver_file_spec.Exists();
1015 if (debugserver_exists) {
1018 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
1019 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
1021 g_debugserver_file_spec = debugserver_file_spec;
1023 debugserver_file_spec =
1024 platform->LocateExecutable(DEBUGSERVER_BASENAME);
1025 if (debugserver_file_spec) {
1026 // Platform::LocateExecutable() wouldn't return a path if it doesn't
1028 debugserver_exists = true;
1031 log->Printf("GDBRemoteCommunication::%s() could not find "
1032 "gdb-remote stub exe '%s'",
1033 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
1035 // Don't cache the platform specific GDB server binary as it could
1036 // change from platform to platform
1037 g_debugserver_file_spec.Clear();
1042 if (debugserver_exists) {
1043 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
1045 Args &debugserver_args = launch_info.GetArguments();
1046 debugserver_args.Clear();
1047 char arg_cstr[PATH_MAX];
1049 // Start args with "debugserver /file/path -r --"
1050 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
1052 #if !defined(__APPLE__)
1053 // First argument to lldb-server must be mode in which to run.
1054 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
1057 // If a url is supplied then use it
1059 debugserver_args.AppendArgument(llvm::StringRef(url));
1061 if (pass_comm_fd >= 0) {
1062 StreamString fd_arg;
1063 fd_arg.Printf("--fd=%i", pass_comm_fd);
1064 debugserver_args.AppendArgument(fd_arg.GetString());
1065 // Send "pass_comm_fd" down to the inferior so it can use it to
1066 // communicate back with this process
1067 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1070 // use native registers, not the GDB registers
1071 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
1073 if (launch_info.GetLaunchInSeparateProcessGroup()) {
1074 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
1077 llvm::SmallString<PATH_MAX> named_pipe_path;
1078 // socket_pipe is used by debug server to communicate back either
1079 // TCP port or domain socket name which it listens on.
1080 // The second purpose of the pipe to serve as a synchronization point -
1081 // once data is written to the pipe, debug server is up and running.
1084 // port is null when debug server should listen on domain socket - we're
1085 // not interested in port value but rather waiting for debug server to
1086 // become available.
1087 if (pass_comm_fd == -1) {
1089 // Create a temporary file to get the stdout/stderr and redirect the output of
1090 // the command into this file. We will later read this file if all goes well
1091 // and fill the data into "command_output_ptr"
1092 #if defined(__APPLE__)
1093 // Binding to port zero, we need to figure out what port it ends up
1094 // using using a named pipe...
1095 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1096 false, named_pipe_path);
1099 log->Printf("GDBRemoteCommunication::%s() "
1100 "named pipe creation failed: %s",
1101 __FUNCTION__, error.AsCString());
1104 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
1105 debugserver_args.AppendArgument(named_pipe_path);
1107 // Binding to port zero, we need to figure out what port it ends up
1108 // using using an unnamed pipe...
1109 error = socket_pipe.CreateNew(true);
1112 log->Printf("GDBRemoteCommunication::%s() "
1113 "unnamed pipe creation failed: %s",
1114 __FUNCTION__, error.AsCString());
1117 int write_fd = socket_pipe.GetWriteFileDescriptor();
1118 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1119 debugserver_args.AppendArgument(llvm::to_string(write_fd));
1120 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
1123 // No host and port given, so lets listen on our end and make the
1124 // debugserver connect to us..
1125 error = StartListenThread("127.0.0.1", 0);
1128 log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1130 __FUNCTION__, error.AsCString());
1134 ConnectionFileDescriptor *connection =
1135 (ConnectionFileDescriptor *)GetConnection();
1136 // Wait for 10 seconds to resolve the bound port
1137 uint16_t port_ = connection->GetListeningPort(std::chrono::seconds(10));
1140 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1141 // Send the host and port down that debugserver and specify an option
1142 // so that it connects back to the port we are listening to in this
1144 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1145 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
1149 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1151 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1158 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1159 if (env_debugserver_log_file) {
1160 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-file=%s",
1161 env_debugserver_log_file);
1162 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
1165 #if defined(__APPLE__)
1166 const char *env_debugserver_log_flags =
1167 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1168 if (env_debugserver_log_flags) {
1169 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-flags=%s",
1170 env_debugserver_log_flags);
1171 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
1174 const char *env_debugserver_log_channels =
1175 getenv("LLDB_SERVER_LOG_CHANNELS");
1176 if (env_debugserver_log_channels) {
1177 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-channels=%s",
1178 env_debugserver_log_channels);
1179 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
1183 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1184 // env var doesn't come back.
1185 uint32_t env_var_index = 1;
1188 char env_var_name[64];
1189 snprintf(env_var_name, sizeof(env_var_name),
1190 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1191 const char *extra_arg = getenv(env_var_name);
1192 has_env_var = extra_arg != nullptr;
1195 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
1197 log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1198 "to stub command line (%s)",
1199 __FUNCTION__, env_var_name, extra_arg);
1201 } while (has_env_var);
1203 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
1204 debugserver_args.AppendArgument(llvm::StringRef("--"));
1205 debugserver_args.AppendArguments(*inferior_args);
1208 // Copy the current environment to the gdbserver/debugserver instance
1209 launch_info.GetEnvironment() = Host::GetEnvironment();
1211 // Close STDIN, STDOUT and STDERR.
1212 launch_info.AppendCloseFileAction(STDIN_FILENO);
1213 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1214 launch_info.AppendCloseFileAction(STDERR_FILENO);
1216 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1217 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1218 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1219 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1222 StreamString string_stream;
1223 Platform *const platform = nullptr;
1224 launch_info.Dump(string_stream, platform);
1225 log->Printf("launch info for gdb-remote stub:\n%s",
1226 string_stream.GetData());
1228 error = Host::LaunchProcess(launch_info);
1230 if (error.Success() &&
1231 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1232 pass_comm_fd == -1) {
1233 if (named_pipe_path.size() > 0) {
1234 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1237 log->Printf("GDBRemoteCommunication::%s() "
1238 "failed to open named pipe %s for reading: %s",
1239 __FUNCTION__, named_pipe_path.c_str(),
1243 if (socket_pipe.CanWrite())
1244 socket_pipe.CloseWriteFileDescriptor();
1245 if (socket_pipe.CanRead()) {
1246 char port_cstr[PATH_MAX] = {0};
1247 port_cstr[0] = '\0';
1248 size_t num_bytes = sizeof(port_cstr);
1249 // Read port from pipe with 10 second timeout.
1250 error = socket_pipe.ReadWithTimeout(
1251 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1252 if (error.Success() && (port != nullptr)) {
1253 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
1254 uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1255 if (*port == 0 || *port == child_port) {
1258 log->Printf("GDBRemoteCommunication::%s() "
1259 "debugserver listens %u port",
1260 __FUNCTION__, *port);
1263 log->Printf("GDBRemoteCommunication::%s() "
1264 "debugserver listening on port "
1265 "%d but requested port was %d",
1266 __FUNCTION__, (uint32_t)child_port,
1271 log->Printf("GDBRemoteCommunication::%s() "
1272 "failed to read a port value from pipe %s: %s",
1273 __FUNCTION__, named_pipe_path.c_str(),
1276 socket_pipe.Close();
1279 if (named_pipe_path.size() > 0) {
1280 const auto err = socket_pipe.Delete(named_pipe_path);
1284 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1285 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
1289 // Make sure we actually connect with the debugserver...
1293 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1298 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1305 void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1307 GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
1308 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
1309 : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1310 auto curr_timeout = gdb_comm.GetPacketTimeout();
1311 // Only update the timeout if the timeout is greater than the current
1312 // timeout. If the current timeout is larger, then just use that.
1313 if (curr_timeout < timeout) {
1314 m_timeout_modified = true;
1315 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1319 GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
1320 // Only restore the timeout if we set it in the constructor.
1321 if (m_timeout_modified)
1322 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1325 // This function is called via the Communications class read thread when bytes
1326 // become available for this connection. This function will consume all
1327 // incoming bytes and try to parse whole packets as they become available. Full
1328 // packets are placed in a queue, so that all packet requests can simply pop
1329 // from this queue. Async notification packets will be dispatched immediately
1330 // to the ProcessGDBRemote Async thread via an event.
1331 void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1332 size_t len, bool broadcast,
1333 lldb::ConnectionStatus status) {
1334 StringExtractorGDBRemote packet;
1337 PacketType type = CheckForPacket(bytes, len, packet);
1339 // scrub the data so we do not pass it back to CheckForPacket on future
1340 // passes of the loop
1344 // we may have received no packet so lets bail out
1345 if (type == PacketType::Invalid)
1348 if (type == PacketType::Standard) {
1349 // scope for the mutex
1351 // lock down the packet queue
1352 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1353 // push a new packet into the queue
1354 m_packet_queue.push(packet);
1355 // Signal condition variable that we have a packet
1356 m_condition_queue_not_empty.notify_one();
1360 if (type == PacketType::Notify) {
1361 // put this packet into an event
1362 const char *pdata = packet.GetStringRef().c_str();
1364 // as the communication class, we are a broadcaster and the async thread
1365 // is tuned to listen to us
1366 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1367 new EventDataBytes(pdata));
1372 void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1373 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1375 using PacketResult = GDBRemoteCommunication::PacketResult;
1378 case PacketResult::Success:
1379 Stream << "Success";
1381 case PacketResult::ErrorSendFailed:
1382 Stream << "ErrorSendFailed";
1384 case PacketResult::ErrorSendAck:
1385 Stream << "ErrorSendAck";
1387 case PacketResult::ErrorReplyFailed:
1388 Stream << "ErrorReplyFailed";
1390 case PacketResult::ErrorReplyTimeout:
1391 Stream << "ErrorReplyTimeout";
1393 case PacketResult::ErrorReplyInvalid:
1394 Stream << "ErrorReplyInvalid";
1396 case PacketResult::ErrorReplyAck:
1397 Stream << "ErrorReplyAck";
1399 case PacketResult::ErrorDisconnected:
1400 Stream << "ErrorDisconnected";
1402 case PacketResult::ErrorNoSequenceLock:
1403 Stream << "ErrorNoSequenceLock";