1 //===-- GDBRemoteCommunication.cpp ----------------------------------------===//
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/Host/Config.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/ThreadLauncher.h"
25 #include "lldb/Host/common/TCPSocket.h"
26 #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
27 #include "lldb/Target/Platform.h"
28 #include "lldb/Utility/Event.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/Config/llvm-config.h" // for LLVM_ENABLE_ZLIB
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.exe"
44 #define DEBUGSERVER_BASENAME "lldb-server"
47 #if defined(HAVE_LIBCOMPRESSION)
48 #include <compression.h>
56 using namespace lldb_private
;
57 using namespace lldb_private::process_gdb_remote
;
59 // GDBRemoteCommunication constructor
60 GDBRemoteCommunication::GDBRemoteCommunication()
62 #ifdef LLDB_CONFIGURATION_DEBUG
63 m_packet_timeout(1000),
67 m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate
), m_history(512),
68 m_send_acks(true), m_is_platform(false),
69 m_compression_type(CompressionType::None
), m_listen_url() {
73 GDBRemoteCommunication::~GDBRemoteCommunication() {
78 #if defined(HAVE_LIBCOMPRESSION)
79 if (m_decompression_scratch
)
80 free (m_decompression_scratch
);
84 char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload
) {
87 for (char c
: payload
)
90 return checksum
& 255;
93 size_t GDBRemoteCommunication::SendAck() {
94 Log
*log
= GetLog(GDBRLog::Packets
);
95 ConnectionStatus status
= eConnectionStatusSuccess
;
97 const size_t bytes_written
= WriteAll(&ch
, 1, status
, nullptr);
98 LLDB_LOGF(log
, "<%4" PRIu64
"> send packet: %c", (uint64_t)bytes_written
, ch
);
99 m_history
.AddPacket(ch
, GDBRemotePacket::ePacketTypeSend
, bytes_written
);
100 return bytes_written
;
103 size_t GDBRemoteCommunication::SendNack() {
104 Log
*log
= GetLog(GDBRLog::Packets
);
105 ConnectionStatus status
= eConnectionStatusSuccess
;
107 const size_t bytes_written
= WriteAll(&ch
, 1, status
, nullptr);
108 LLDB_LOGF(log
, "<%4" PRIu64
"> send packet: %c", (uint64_t)bytes_written
, ch
);
109 m_history
.AddPacket(ch
, GDBRemotePacket::ePacketTypeSend
, bytes_written
);
110 return bytes_written
;
113 GDBRemoteCommunication::PacketResult
114 GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload
) {
115 StreamString
packet(0, 4, eByteOrderBig
);
117 packet
.Write(payload
.data(), payload
.size());
119 packet
.PutHex8(CalculcateChecksum(payload
));
120 std::string packet_str
= std::string(packet
.GetString());
122 return SendRawPacketNoLock(packet_str
);
125 GDBRemoteCommunication::PacketResult
126 GDBRemoteCommunication::SendNotificationPacketNoLock(
127 llvm::StringRef notify_type
, std::deque
<std::string
> &queue
,
128 llvm::StringRef payload
) {
129 PacketResult ret
= PacketResult::Success
;
131 // If there are no notification in the queue, send the notification
134 StreamString
packet(0, 4, eByteOrderBig
);
136 packet
.Write(notify_type
.data(), notify_type
.size());
138 packet
.Write(payload
.data(), payload
.size());
140 packet
.PutHex8(CalculcateChecksum(payload
));
141 ret
= SendRawPacketNoLock(packet
.GetString(), true);
144 queue
.push_back(payload
.str());
148 GDBRemoteCommunication::PacketResult
149 GDBRemoteCommunication::SendRawPacketNoLock(llvm::StringRef packet
,
152 Log
*log
= GetLog(GDBRLog::Packets
);
153 ConnectionStatus status
= eConnectionStatusSuccess
;
154 const char *packet_data
= packet
.data();
155 const size_t packet_length
= packet
.size();
156 size_t bytes_written
= WriteAll(packet_data
, packet_length
, status
, nullptr);
158 size_t binary_start_offset
= 0;
159 if (strncmp(packet_data
, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
161 const char *first_comma
= strchr(packet_data
, ',');
163 const char *second_comma
= strchr(first_comma
+ 1, ',');
165 binary_start_offset
= second_comma
- packet_data
+ 1;
169 // If logging was just enabled and we have history, then dump out what we
170 // have to the log so we get the historical context. The Dump() call that
171 // logs all of the packet will set a boolean so that we don't dump this
173 if (!m_history
.DidDumpToLog())
176 if (binary_start_offset
) {
178 // Print non binary data header
179 strm
.Printf("<%4" PRIu64
"> send packet: %.*s", (uint64_t)bytes_written
,
180 (int)binary_start_offset
, packet_data
);
182 // Print binary data exactly as sent
183 for (p
= (const uint8_t *)packet_data
+ binary_start_offset
; *p
!= '#';
185 strm
.Printf("\\x%2.2x", *p
);
186 // Print the checksum
187 strm
.Printf("%*s", (int)3, p
);
188 log
->PutString(strm
.GetString());
190 LLDB_LOGF(log
, "<%4" PRIu64
"> send packet: %.*s",
191 (uint64_t)bytes_written
, (int)packet_length
, packet_data
);
194 m_history
.AddPacket(packet
.str(), packet_length
,
195 GDBRemotePacket::ePacketTypeSend
, bytes_written
);
197 if (bytes_written
== packet_length
) {
198 if (!skip_ack
&& GetSendAcks())
201 return PacketResult::Success
;
203 LLDB_LOGF(log
, "error: failed to send packet: %.*s", (int)packet_length
,
207 return PacketResult::ErrorSendFailed
;
210 GDBRemoteCommunication::PacketResult
GDBRemoteCommunication::GetAck() {
211 StringExtractorGDBRemote packet
;
212 PacketResult result
= WaitForPacketNoLock(packet
, GetPacketTimeout(), false);
213 if (result
== PacketResult::Success
) {
214 if (packet
.GetResponseType() ==
215 StringExtractorGDBRemote::ResponseType::eAck
)
216 return PacketResult::Success
;
218 return PacketResult::ErrorSendAck
;
223 GDBRemoteCommunication::PacketResult
224 GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote
&response
,
225 Timeout
<std::micro
> timeout
,
226 bool sync_on_timeout
) {
227 using ResponseType
= StringExtractorGDBRemote::ResponseType
;
229 Log
*log
= GetLog(GDBRLog::Packets
);
231 PacketResult result
=
232 WaitForPacketNoLock(response
, timeout
, sync_on_timeout
);
233 if (result
!= PacketResult::Success
||
234 (response
.GetResponseType() != ResponseType::eAck
&&
235 response
.GetResponseType() != ResponseType::eNack
))
237 LLDB_LOG(log
, "discarding spurious `{0}` packet", response
.GetStringRef());
241 GDBRemoteCommunication::PacketResult
242 GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote
&packet
,
243 Timeout
<std::micro
> timeout
,
244 bool sync_on_timeout
) {
245 uint8_t buffer
[8192];
248 Log
*log
= GetLog(GDBRLog::Packets
);
250 // Check for a packet from our cache first without trying any reading...
251 if (CheckForPacket(nullptr, 0, packet
) != PacketType::Invalid
)
252 return PacketResult::Success
;
254 bool timed_out
= false;
255 bool disconnected
= false;
256 while (IsConnected() && !timed_out
) {
257 lldb::ConnectionStatus status
= eConnectionStatusNoConnection
;
258 size_t bytes_read
= Read(buffer
, sizeof(buffer
), timeout
, status
, &error
);
261 "Read(buffer, sizeof(buffer), timeout = {0}, "
262 "status = {1}, error = {2}) => bytes_read = {3}",
263 timeout
, Communication::ConnectionStatusAsString(status
), error
,
266 if (bytes_read
> 0) {
267 if (CheckForPacket(buffer
, bytes_read
, packet
) != PacketType::Invalid
)
268 return PacketResult::Success
;
271 case eConnectionStatusTimedOut
:
272 case eConnectionStatusInterrupted
:
273 if (sync_on_timeout
) {
274 /// Sync the remote GDB server and make sure we get a response that
275 /// corresponds to what we send.
277 /// Sends a "qEcho" packet and makes sure it gets the exact packet
278 /// echoed back. If the qEcho packet isn't supported, we send a qC
279 /// packet and make sure we get a valid thread ID back. We use the
280 /// "qC" packet since its response if very unique: is responds with
281 /// "QC%x" where %x is the thread ID of the current thread. This
282 /// makes the response unique enough from other packet responses to
283 /// ensure we are back on track.
285 /// This packet is needed after we time out sending a packet so we
286 /// can ensure that we are getting the response for the packet we
287 /// are sending. There are no sequence IDs in the GDB remote
288 /// protocol (there used to be, but they are not supported anymore)
289 /// so if you timeout sending packet "abc", you might then send
290 /// packet "cde" and get the response for the previous "abc" packet.
291 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
292 /// many responses for packets can look like responses for other
293 /// packets. So if we timeout, we need to ensure that we can get
294 /// back on track. If we can't get back on track, we must
296 bool sync_success
= false;
297 bool got_actual_response
= false;
298 // We timed out, we need to sync back up with the
299 char echo_packet
[32];
300 int echo_packet_len
= 0;
301 RegularExpression response_regex
;
303 if (m_supports_qEcho
== eLazyBoolYes
) {
304 echo_packet_len
= ::snprintf(echo_packet
, sizeof(echo_packet
),
305 "qEcho:%u", ++m_echo_number
);
306 std::string regex_str
= "^";
307 regex_str
+= echo_packet
;
309 response_regex
= RegularExpression(regex_str
);
312 ::snprintf(echo_packet
, sizeof(echo_packet
), "qC");
314 RegularExpression(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
317 PacketResult echo_packet_result
=
318 SendPacketNoLock(llvm::StringRef(echo_packet
, echo_packet_len
));
319 if (echo_packet_result
== PacketResult::Success
) {
320 const uint32_t max_retries
= 3;
321 uint32_t successful_responses
= 0;
322 for (uint32_t i
= 0; i
< max_retries
; ++i
) {
323 StringExtractorGDBRemote echo_response
;
325 WaitForPacketNoLock(echo_response
, timeout
, false);
326 if (echo_packet_result
== PacketResult::Success
) {
327 ++successful_responses
;
328 if (response_regex
.Execute(echo_response
.GetStringRef())) {
331 } else if (successful_responses
== 1) {
332 // We got something else back as the first successful
333 // response, it probably is the response to the packet we
334 // actually wanted, so copy it over if this is the first
335 // success and continue to try to get the qEcho response
336 packet
= echo_response
;
337 got_actual_response
= true;
339 } else if (echo_packet_result
== PacketResult::ErrorReplyTimeout
)
340 continue; // Packet timed out, continue waiting for a response
342 break; // Something else went wrong getting the packet back, we
343 // failed and are done trying
347 // We weren't able to sync back up with the server, we must abort
348 // otherwise all responses might not be from the right packets...
350 // We timed out, but were able to recover
351 if (got_actual_response
) {
352 // We initially timed out, but we did get a response that came in
353 // before the successful reply to our qEcho packet, so lets say
354 // everything is fine...
355 return PacketResult::Success
;
364 case eConnectionStatusSuccess
:
365 // printf ("status = success but error = %s\n",
366 // error.AsCString("<invalid>"));
369 case eConnectionStatusEndOfFile
:
370 case eConnectionStatusNoConnection
:
371 case eConnectionStatusLostConnection
:
372 case eConnectionStatusError
:
381 return PacketResult::ErrorDisconnected
;
383 return PacketResult::ErrorReplyTimeout
;
385 return PacketResult::ErrorReplyFailed
;
388 bool GDBRemoteCommunication::DecompressPacket() {
389 Log
*log
= GetLog(GDBRLog::Packets
);
391 if (!CompressionIsEnabled())
394 size_t pkt_size
= m_bytes
.size();
396 // Smallest possible compressed packet is $N#00 - an uncompressed empty
397 // reply, most commonly indicating an unsupported packet. Anything less than
398 // 5 characters, it's definitely not a compressed packet.
402 if (m_bytes
[0] != '$' && m_bytes
[0] != '%')
404 if (m_bytes
[1] != 'C' && m_bytes
[1] != 'N')
407 size_t hash_mark_idx
= m_bytes
.find('#');
408 if (hash_mark_idx
== std::string::npos
)
410 if (hash_mark_idx
+ 2 >= m_bytes
.size())
413 if (!::isxdigit(m_bytes
[hash_mark_idx
+ 1]) ||
414 !::isxdigit(m_bytes
[hash_mark_idx
+ 2]))
417 size_t content_length
=
419 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
420 size_t content_start
= 2; // The first character of the
421 // compressed/not-compressed text of the packet
422 size_t checksum_idx
=
424 1; // The first character of the two hex checksum characters
426 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
427 // multiple packets. size_of_first_packet is the size of the initial packet
428 // which we'll replace with the decompressed version of, leaving the rest of
429 // m_bytes unmodified.
430 size_t size_of_first_packet
= hash_mark_idx
+ 3;
432 // Compressed packets ("$C") start with a base10 number which is the size of
433 // the uncompressed payload, then a : and then the compressed data. e.g.
434 // $C1024:<binary>#00 Update content_start and content_length to only include
435 // the <binary> part of the packet.
437 uint64_t decompressed_bufsize
= ULONG_MAX
;
438 if (m_bytes
[1] == 'C') {
439 size_t i
= content_start
;
440 while (i
< hash_mark_idx
&& isdigit(m_bytes
[i
]))
442 if (i
< hash_mark_idx
&& m_bytes
[i
] == ':') {
445 content_length
= hash_mark_idx
- content_start
;
446 std::string
bufsize_str(m_bytes
.data() + 2, i
- 2 - 1);
448 decompressed_bufsize
= ::strtoul(bufsize_str
.c_str(), nullptr, 10);
449 if (errno
!= 0 || decompressed_bufsize
== ULONG_MAX
) {
450 m_bytes
.erase(0, size_of_first_packet
);
457 char packet_checksum_cstr
[3];
458 packet_checksum_cstr
[0] = m_bytes
[checksum_idx
];
459 packet_checksum_cstr
[1] = m_bytes
[checksum_idx
+ 1];
460 packet_checksum_cstr
[2] = '\0';
461 long packet_checksum
= strtol(packet_checksum_cstr
, nullptr, 16);
463 long actual_checksum
= CalculcateChecksum(
464 llvm::StringRef(m_bytes
).substr(1, hash_mark_idx
- 1));
465 bool success
= packet_checksum
== actual_checksum
;
468 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
469 (int)(pkt_size
), m_bytes
.c_str(), (uint8_t)packet_checksum
,
470 (uint8_t)actual_checksum
);
472 // Send the ack or nack if needed
475 m_bytes
.erase(0, size_of_first_packet
);
482 if (m_bytes
[1] == 'N') {
483 // This packet was not compressed -- delete the 'N' character at the start
484 // and the packet may be processed as-is.
489 // Reverse the gdb-remote binary escaping that was done to the compressed
490 // text to guard characters like '$', '#', '}', etc.
491 std::vector
<uint8_t> unescaped_content
;
492 unescaped_content
.reserve(content_length
);
493 size_t i
= content_start
;
494 while (i
< hash_mark_idx
) {
495 if (m_bytes
[i
] == '}') {
497 unescaped_content
.push_back(m_bytes
[i
] ^ 0x20);
499 unescaped_content
.push_back(m_bytes
[i
]);
504 uint8_t *decompressed_buffer
= nullptr;
505 size_t decompressed_bytes
= 0;
507 if (decompressed_bufsize
!= ULONG_MAX
) {
508 decompressed_buffer
= (uint8_t *)malloc(decompressed_bufsize
);
509 if (decompressed_buffer
== nullptr) {
510 m_bytes
.erase(0, size_of_first_packet
);
515 #if defined(HAVE_LIBCOMPRESSION)
516 if (m_compression_type
== CompressionType::ZlibDeflate
||
517 m_compression_type
== CompressionType::LZFSE
||
518 m_compression_type
== CompressionType::LZ4
||
519 m_compression_type
== CompressionType::LZMA
) {
520 compression_algorithm compression_type
;
521 if (m_compression_type
== CompressionType::LZFSE
)
522 compression_type
= COMPRESSION_LZFSE
;
523 else if (m_compression_type
== CompressionType::ZlibDeflate
)
524 compression_type
= COMPRESSION_ZLIB
;
525 else if (m_compression_type
== CompressionType::LZ4
)
526 compression_type
= COMPRESSION_LZ4_RAW
;
527 else if (m_compression_type
== CompressionType::LZMA
)
528 compression_type
= COMPRESSION_LZMA
;
530 if (m_decompression_scratch_type
!= m_compression_type
) {
531 if (m_decompression_scratch
) {
532 free (m_decompression_scratch
);
533 m_decompression_scratch
= nullptr;
535 size_t scratchbuf_size
= 0;
536 if (m_compression_type
== CompressionType::LZFSE
)
537 scratchbuf_size
= compression_decode_scratch_buffer_size (COMPRESSION_LZFSE
);
538 else if (m_compression_type
== CompressionType::LZ4
)
539 scratchbuf_size
= compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW
);
540 else if (m_compression_type
== CompressionType::ZlibDeflate
)
541 scratchbuf_size
= compression_decode_scratch_buffer_size (COMPRESSION_ZLIB
);
542 else if (m_compression_type
== CompressionType::LZMA
)
544 compression_decode_scratch_buffer_size(COMPRESSION_LZMA
);
545 if (scratchbuf_size
> 0) {
546 m_decompression_scratch
= (void*) malloc (scratchbuf_size
);
547 m_decompression_scratch_type
= m_compression_type
;
551 if (decompressed_bufsize
!= ULONG_MAX
&& decompressed_buffer
!= nullptr) {
552 decompressed_bytes
= compression_decode_buffer(
553 decompressed_buffer
, decompressed_bufsize
,
554 (uint8_t *)unescaped_content
.data(), unescaped_content
.size(),
555 m_decompression_scratch
, compression_type
);
561 if (decompressed_bytes
== 0 && decompressed_bufsize
!= ULONG_MAX
&&
562 decompressed_buffer
!= nullptr &&
563 m_compression_type
== CompressionType::ZlibDeflate
) {
565 memset(&stream
, 0, sizeof(z_stream
));
566 stream
.next_in
= (Bytef
*)unescaped_content
.data();
567 stream
.avail_in
= (uInt
)unescaped_content
.size();
569 stream
.next_out
= (Bytef
*)decompressed_buffer
;
570 stream
.avail_out
= decompressed_bufsize
;
571 stream
.total_out
= 0;
572 stream
.zalloc
= Z_NULL
;
573 stream
.zfree
= Z_NULL
;
574 stream
.opaque
= Z_NULL
;
576 if (inflateInit2(&stream
, -15) == Z_OK
) {
577 int status
= inflate(&stream
, Z_NO_FLUSH
);
579 if (status
== Z_STREAM_END
) {
580 decompressed_bytes
= stream
.total_out
;
586 if (decompressed_bytes
== 0 || decompressed_buffer
== nullptr) {
587 if (decompressed_buffer
)
588 free(decompressed_buffer
);
589 m_bytes
.erase(0, size_of_first_packet
);
593 std::string new_packet
;
594 new_packet
.reserve(decompressed_bytes
+ 6);
595 new_packet
.push_back(m_bytes
[0]);
596 new_packet
.append((const char *)decompressed_buffer
, decompressed_bytes
);
597 new_packet
.push_back('#');
599 uint8_t decompressed_checksum
= CalculcateChecksum(
600 llvm::StringRef((const char *)decompressed_buffer
, decompressed_bytes
));
601 char decompressed_checksum_str
[3];
602 snprintf(decompressed_checksum_str
, 3, "%02x", decompressed_checksum
);
603 new_packet
.append(decompressed_checksum_str
);
605 new_packet
.push_back('0');
606 new_packet
.push_back('0');
609 m_bytes
.replace(0, size_of_first_packet
, new_packet
.data(),
612 free(decompressed_buffer
);
616 GDBRemoteCommunication::PacketType
617 GDBRemoteCommunication::CheckForPacket(const uint8_t *src
, size_t src_len
,
618 StringExtractorGDBRemote
&packet
) {
619 // Put the packet data into the buffer in a thread safe fashion
620 std::lock_guard
<std::recursive_mutex
> guard(m_bytes_mutex
);
622 Log
*log
= GetLog(GDBRLog::Packets
);
624 if (src
&& src_len
> 0) {
625 if (log
&& log
->GetVerbose()) {
627 LLDB_LOGF(log
, "GDBRemoteCommunication::%s adding %u bytes: %.*s",
628 __FUNCTION__
, (uint32_t)src_len
, (uint32_t)src_len
, src
);
630 m_bytes
.append((const char *)src
, src_len
);
633 bool isNotifyPacket
= false;
635 // Parse up the packets into gdb remote packets
636 if (!m_bytes
.empty()) {
637 // end_idx must be one past the last valid packet byte. Start it off with
638 // an invalid value that is the same as the current index.
639 size_t content_start
= 0;
640 size_t content_length
= 0;
641 size_t total_length
= 0;
642 size_t checksum_idx
= std::string::npos
;
644 // Size of packet before it is decompressed, for logging purposes
645 size_t original_packet_size
= m_bytes
.size();
646 if (CompressionIsEnabled()) {
647 if (!DecompressPacket()) {
649 return GDBRemoteCommunication::PacketType::Standard
;
653 switch (m_bytes
[0]) {
654 case '+': // Look for ack
655 case '-': // Look for cancel
656 case '\x03': // ^C to halt target
657 content_length
= total_length
= 1; // The command is one byte long...
660 case '%': // Async notify packet
661 isNotifyPacket
= true;
665 // Look for a standard gdb packet?
667 size_t hash_pos
= m_bytes
.find('#');
668 if (hash_pos
!= std::string::npos
) {
669 if (hash_pos
+ 2 < m_bytes
.size()) {
670 checksum_idx
= hash_pos
+ 1;
671 // Skip the dollar sign
673 // Don't include the # in the content or the $ in the content
675 content_length
= hash_pos
- 1;
678 hash_pos
+ 3; // Skip the # and the two hex checksum bytes
680 // Checksum bytes aren't all here yet
681 content_length
= std::string::npos
;
688 // We have an unexpected byte and we need to flush all bad data that is
689 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
690 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
691 // header) or of course, the end of the data in m_bytes...
692 const size_t bytes_len
= m_bytes
.size();
695 for (idx
= 1; !done
&& idx
< bytes_len
; ++idx
) {
696 switch (m_bytes
[idx
]) {
709 LLDB_LOGF(log
, "GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
710 __FUNCTION__
, idx
- 1, idx
- 1, m_bytes
.c_str());
711 m_bytes
.erase(0, idx
- 1);
715 if (content_length
== std::string::npos
) {
717 return GDBRemoteCommunication::PacketType::Invalid
;
718 } else if (total_length
> 0) {
720 // We have a valid packet...
721 assert(content_length
<= m_bytes
.size());
722 assert(total_length
<= m_bytes
.size());
723 assert(content_length
<= total_length
);
724 size_t content_end
= content_start
+ content_length
;
728 // If logging was just enabled and we have history, then dump out what
729 // we have to the log so we get the historical context. The Dump() call
730 // that logs all of the packet will set a boolean so that we don't dump
731 // this more than once
732 if (!m_history
.DidDumpToLog())
736 // Only detect binary for packets that start with a '$' and have a
738 if (m_bytes
[0] == '$' && total_length
> 4) {
739 for (size_t i
= 0; !binary
&& i
< total_length
; ++i
) {
740 unsigned char c
= m_bytes
[i
];
741 if (!llvm::isPrint(c
) && !llvm::isSpace(c
)) {
749 if (CompressionIsEnabled())
750 strm
.Printf("<%4" PRIu64
":%" PRIu64
"> read packet: %c",
751 (uint64_t)original_packet_size
, (uint64_t)total_length
,
754 strm
.Printf("<%4" PRIu64
"> read packet: %c",
755 (uint64_t)total_length
, m_bytes
[0]);
756 for (size_t i
= content_start
; i
< content_end
; ++i
) {
757 // Remove binary escaped bytes when displaying the packet...
758 const char ch
= m_bytes
[i
];
760 // 0x7d is the escape character. The next character is to be
762 const char escapee
= m_bytes
[++i
] ^ 0x20;
763 strm
.Printf("%2.2x", escapee
);
765 strm
.Printf("%2.2x", (uint8_t)ch
);
769 strm
.Printf("%c%c%c", m_bytes
[total_length
- 3],
770 m_bytes
[total_length
- 2], m_bytes
[total_length
- 1]);
771 log
->PutString(strm
.GetString());
773 if (CompressionIsEnabled())
774 LLDB_LOGF(log
, "<%4" PRIu64
":%" PRIu64
"> read packet: %.*s",
775 (uint64_t)original_packet_size
, (uint64_t)total_length
,
776 (int)(total_length
), m_bytes
.c_str());
778 LLDB_LOGF(log
, "<%4" PRIu64
"> read packet: %.*s",
779 (uint64_t)total_length
, (int)(total_length
),
784 m_history
.AddPacket(m_bytes
, total_length
,
785 GDBRemotePacket::ePacketTypeRecv
, total_length
);
787 // Copy the packet from m_bytes to packet_str expanding the run-length
788 // encoding in the process.
789 std ::string packet_str
=
790 ExpandRLE(m_bytes
.substr(content_start
, content_end
- content_start
));
791 packet
= StringExtractorGDBRemote(packet_str
);
793 if (m_bytes
[0] == '$' || m_bytes
[0] == '%') {
794 assert(checksum_idx
< m_bytes
.size());
795 if (::isxdigit(m_bytes
[checksum_idx
+ 0]) ||
796 ::isxdigit(m_bytes
[checksum_idx
+ 1])) {
798 const char *packet_checksum_cstr
= &m_bytes
[checksum_idx
];
799 char packet_checksum
= strtol(packet_checksum_cstr
, nullptr, 16);
800 char actual_checksum
= CalculcateChecksum(
801 llvm::StringRef(m_bytes
).slice(content_start
, content_end
));
802 success
= packet_checksum
== actual_checksum
;
805 "error: checksum mismatch: %.*s expected 0x%2.2x, "
807 (int)(total_length
), m_bytes
.c_str(),
808 (uint8_t)packet_checksum
, (uint8_t)actual_checksum
);
810 // Send the ack or nack if needed
818 LLDB_LOGF(log
, "error: invalid checksum in packet: '%s'\n",
823 m_bytes
.erase(0, total_length
);
824 packet
.SetFilePos(0);
827 return GDBRemoteCommunication::PacketType::Notify
;
829 return GDBRemoteCommunication::PacketType::Standard
;
833 return GDBRemoteCommunication::PacketType::Invalid
;
836 Status
GDBRemoteCommunication::StartListenThread(const char *hostname
,
838 if (m_listen_thread
.IsJoinable())
839 return Status::FromErrorString("listen thread already running");
841 char listen_url
[512];
842 if (hostname
&& hostname
[0])
843 snprintf(listen_url
, sizeof(listen_url
), "listen://%s:%i", hostname
, port
);
845 snprintf(listen_url
, sizeof(listen_url
), "listen://%i", port
);
846 m_listen_url
= listen_url
;
847 SetConnection(std::make_unique
<ConnectionFileDescriptor
>());
848 llvm::Expected
<HostThread
> listen_thread
= ThreadLauncher::LaunchThread(
849 listen_url
, [this] { return GDBRemoteCommunication::ListenThread(); });
851 return Status::FromError(listen_thread
.takeError());
852 m_listen_thread
= *listen_thread
;
857 bool GDBRemoteCommunication::JoinListenThread() {
858 if (m_listen_thread
.IsJoinable())
859 m_listen_thread
.Join(nullptr);
863 lldb::thread_result_t
GDBRemoteCommunication::ListenThread() {
865 ConnectionFileDescriptor
*connection
=
866 (ConnectionFileDescriptor
*)GetConnection();
869 // Do the listen on another thread so we can continue on...
870 if (connection
->Connect(
871 m_listen_url
.c_str(),
872 [this](llvm::StringRef port_str
) {
874 llvm::to_integer(port_str
, port
, 10);
875 m_port_promise
.set_value(port
);
877 &error
) != eConnectionStatusSuccess
)
878 SetConnection(nullptr);
883 FileSpec
GDBRemoteCommunication::GetDebugserverPath(Platform
*platform
) {
884 Log
*log
= GetLog(GDBRLog::Process
);
885 // If we locate debugserver, keep that located version around
886 static FileSpec g_debugserver_file_spec
;
887 FileSpec debugserver_file_spec
;
889 Environment host_env
= Host::GetEnvironment();
891 // Always check to see if we have an environment override for the path to the
892 // debugserver to use and use it if we do.
893 std::string env_debugserver_path
= host_env
.lookup("LLDB_DEBUGSERVER_PATH");
894 if (!env_debugserver_path
.empty()) {
895 debugserver_file_spec
.SetFile(env_debugserver_path
,
896 FileSpec::Style::native
);
898 "GDBRemoteCommunication::%s() gdb-remote stub exe path set "
899 "from environment variable: %s",
900 __FUNCTION__
, env_debugserver_path
.c_str());
902 debugserver_file_spec
= g_debugserver_file_spec
;
903 bool debugserver_exists
=
904 FileSystem::Instance().Exists(debugserver_file_spec
);
905 if (!debugserver_exists
) {
906 // The debugserver binary is in the LLDB.framework/Resources directory.
907 debugserver_file_spec
= HostInfo::GetSupportExeDir();
908 if (debugserver_file_spec
) {
909 debugserver_file_spec
.AppendPathComponent(DEBUGSERVER_BASENAME
);
910 debugserver_exists
= FileSystem::Instance().Exists(debugserver_file_spec
);
911 if (debugserver_exists
) {
913 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
914 __FUNCTION__
, debugserver_file_spec
.GetPath().c_str());
916 g_debugserver_file_spec
= debugserver_file_spec
;
919 debugserver_file_spec
=
920 platform
->LocateExecutable(DEBUGSERVER_BASENAME
);
922 debugserver_file_spec
.Clear();
923 if (debugserver_file_spec
) {
924 // Platform::LocateExecutable() wouldn't return a path if it doesn't
926 debugserver_exists
= true;
929 "GDBRemoteCommunication::%s() could not find "
930 "gdb-remote stub exe '%s'",
931 __FUNCTION__
, debugserver_file_spec
.GetPath().c_str());
933 // Don't cache the platform specific GDB server binary as it could
934 // change from platform to platform
935 g_debugserver_file_spec
.Clear();
939 return debugserver_file_spec
;
942 Status
GDBRemoteCommunication::StartDebugserverProcess(
943 const char *url
, Platform
*platform
, ProcessLaunchInfo
&launch_info
,
944 uint16_t *port
, const Args
*inferior_args
, shared_fd_t pass_comm_fd
) {
945 Log
*log
= GetLog(GDBRLog::Process
);
946 LLDB_LOGF(log
, "GDBRemoteCommunication::%s(url=%s, port=%" PRIu16
")",
947 __FUNCTION__
, url
? url
: "<empty>", port
? *port
: uint16_t(0));
950 FileSpec
&debugserver_file_spec
= launch_info
.GetExecutableFile();
951 if ((debugserver_file_spec
= GetDebugserverPath(platform
))) {
952 std::string debugserver_path
= debugserver_file_spec
.GetPath();
954 Args
&debugserver_args
= launch_info
.GetArguments();
955 debugserver_args
.Clear();
957 // Start args with "debugserver /file/path -r --"
958 debugserver_args
.AppendArgument(llvm::StringRef(debugserver_path
));
960 #if !defined(__APPLE__)
961 // First argument to lldb-server must be mode in which to run.
962 debugserver_args
.AppendArgument(llvm::StringRef("gdbserver"));
965 // If a url is supplied then use it
967 debugserver_args
.AppendArgument(llvm::StringRef(url
));
969 if (pass_comm_fd
!= SharedSocket::kInvalidFD
) {
971 fd_arg
.Printf("--fd=%" PRIi64
, (int64_t)pass_comm_fd
);
972 debugserver_args
.AppendArgument(fd_arg
.GetString());
973 // Send "pass_comm_fd" down to the inferior so it can use it to
974 // communicate back with this process. Ignored on Windows.
976 launch_info
.AppendDuplicateFileAction((int)pass_comm_fd
,
981 // use native registers, not the GDB registers
982 debugserver_args
.AppendArgument(llvm::StringRef("--native-regs"));
984 if (launch_info
.GetLaunchInSeparateProcessGroup()) {
985 debugserver_args
.AppendArgument(llvm::StringRef("--setsid"));
988 llvm::SmallString
<128> named_pipe_path
;
989 // socket_pipe is used by debug server to communicate back either
990 // TCP port or domain socket name which it listens on.
991 // The second purpose of the pipe to serve as a synchronization point -
992 // once data is written to the pipe, debug server is up and running.
995 // port is null when debug server should listen on domain socket - we're
996 // not interested in port value but rather waiting for debug server to
998 if (pass_comm_fd
== SharedSocket::kInvalidFD
) {
1000 // Create a temporary file to get the stdout/stderr and redirect the output of
1001 // the command into this file. We will later read this file if all goes well
1002 // and fill the data into "command_output_ptr"
1003 #if defined(__APPLE__)
1004 // Binding to port zero, we need to figure out what port it ends up
1005 // using using a named pipe...
1006 error
= socket_pipe
.CreateWithUniqueName("debugserver-named-pipe",
1007 false, named_pipe_path
);
1010 "GDBRemoteCommunication::%s() "
1011 "named pipe creation failed: %s",
1012 __FUNCTION__
, error
.AsCString());
1015 debugserver_args
.AppendArgument(llvm::StringRef("--named-pipe"));
1016 debugserver_args
.AppendArgument(named_pipe_path
);
1018 // Binding to port zero, we need to figure out what port it ends up
1019 // using using an unnamed pipe...
1020 error
= socket_pipe
.CreateNew(true);
1023 "GDBRemoteCommunication::%s() "
1024 "unnamed pipe creation failed: %s",
1025 __FUNCTION__
, error
.AsCString());
1028 pipe_t write
= socket_pipe
.GetWritePipe();
1029 debugserver_args
.AppendArgument(llvm::StringRef("--pipe"));
1030 debugserver_args
.AppendArgument(llvm::to_string(write
));
1031 launch_info
.AppendCloseFileAction(socket_pipe
.GetReadFileDescriptor());
1034 // No host and port given, so lets listen on our end and make the
1035 // debugserver connect to us..
1036 error
= StartListenThread("127.0.0.1", 0);
1039 "GDBRemoteCommunication::%s() unable to start listen "
1041 __FUNCTION__
, error
.AsCString());
1045 // Wait for 10 seconds to resolve the bound port
1046 std::future
<uint16_t> port_future
= m_port_promise
.get_future();
1047 uint16_t port_
= port_future
.wait_for(std::chrono::seconds(10)) ==
1048 std::future_status::ready
1053 snprintf(port_cstr
, sizeof(port_cstr
), "127.0.0.1:%i", port_
);
1054 // Send the host and port down that debugserver and specify an option
1055 // so that it connects back to the port we are listening to in this
1057 debugserver_args
.AppendArgument(llvm::StringRef("--reverse-connect"));
1058 debugserver_args
.AppendArgument(llvm::StringRef(port_cstr
));
1062 LLDB_LOGF(log
, "GDBRemoteCommunication::%s() failed: %s",
1063 __FUNCTION__
, error
.AsCString());
1064 return Status::FromErrorString(
1065 "failed to bind to port 0 on 127.0.0.1");
1070 Environment host_env
= Host::GetEnvironment();
1071 std::string env_debugserver_log_file
=
1072 host_env
.lookup("LLDB_DEBUGSERVER_LOG_FILE");
1073 if (!env_debugserver_log_file
.empty()) {
1074 debugserver_args
.AppendArgument(
1075 llvm::formatv("--log-file={0}", env_debugserver_log_file
).str());
1078 #if defined(__APPLE__)
1079 const char *env_debugserver_log_flags
=
1080 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1081 if (env_debugserver_log_flags
) {
1082 debugserver_args
.AppendArgument(
1083 llvm::formatv("--log-flags={0}", env_debugserver_log_flags
).str());
1086 std::string env_debugserver_log_channels
=
1087 host_env
.lookup("LLDB_SERVER_LOG_CHANNELS");
1088 if (!env_debugserver_log_channels
.empty()) {
1089 debugserver_args
.AppendArgument(
1090 llvm::formatv("--log-channels={0}", env_debugserver_log_channels
)
1095 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1096 // env var doesn't come back.
1097 uint32_t env_var_index
= 1;
1100 char env_var_name
[64];
1101 snprintf(env_var_name
, sizeof(env_var_name
),
1102 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32
, env_var_index
++);
1103 std::string extra_arg
= host_env
.lookup(env_var_name
);
1104 has_env_var
= !extra_arg
.empty();
1107 debugserver_args
.AppendArgument(llvm::StringRef(extra_arg
));
1109 "GDBRemoteCommunication::%s adding env var %s contents "
1110 "to stub command line (%s)",
1111 __FUNCTION__
, env_var_name
, extra_arg
.c_str());
1113 } while (has_env_var
);
1115 if (inferior_args
&& inferior_args
->GetArgumentCount() > 0) {
1116 debugserver_args
.AppendArgument(llvm::StringRef("--"));
1117 debugserver_args
.AppendArguments(*inferior_args
);
1120 // Copy the current environment to the gdbserver/debugserver instance
1121 launch_info
.GetEnvironment() = host_env
;
1123 // Close STDIN, STDOUT and STDERR.
1124 launch_info
.AppendCloseFileAction(STDIN_FILENO
);
1125 launch_info
.AppendCloseFileAction(STDOUT_FILENO
);
1126 launch_info
.AppendCloseFileAction(STDERR_FILENO
);
1128 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1129 launch_info
.AppendSuppressFileAction(STDIN_FILENO
, true, false);
1130 launch_info
.AppendSuppressFileAction(STDOUT_FILENO
, false, true);
1131 launch_info
.AppendSuppressFileAction(STDERR_FILENO
, false, true);
1134 StreamString string_stream
;
1135 Platform
*const platform
= nullptr;
1136 launch_info
.Dump(string_stream
, platform
);
1137 LLDB_LOGF(log
, "launch info for gdb-remote stub:\n%s",
1138 string_stream
.GetData());
1140 error
= Host::LaunchProcess(launch_info
);
1142 if (error
.Success() &&
1143 (launch_info
.GetProcessID() != LLDB_INVALID_PROCESS_ID
) &&
1144 pass_comm_fd
== SharedSocket::kInvalidFD
) {
1145 if (named_pipe_path
.size() > 0) {
1146 error
= socket_pipe
.OpenAsReader(named_pipe_path
, false);
1149 "GDBRemoteCommunication::%s() "
1150 "failed to open named pipe %s for reading: %s",
1151 __FUNCTION__
, named_pipe_path
.c_str(), error
.AsCString());
1154 if (socket_pipe
.CanWrite())
1155 socket_pipe
.CloseWriteFileDescriptor();
1156 if (socket_pipe
.CanRead()) {
1157 // The port number may be up to "65535\0".
1158 char port_cstr
[6] = {0};
1159 size_t num_bytes
= sizeof(port_cstr
);
1160 // Read port from pipe with 10 second timeout.
1161 error
= socket_pipe
.ReadWithTimeout(
1162 port_cstr
, num_bytes
, std::chrono::seconds
{10}, num_bytes
);
1163 if (error
.Success() && (port
!= nullptr)) {
1164 assert(num_bytes
> 0 && port_cstr
[num_bytes
- 1] == '\0');
1165 uint16_t child_port
= 0;
1166 // FIXME: improve error handling
1167 llvm::to_integer(port_cstr
, child_port
);
1168 if (*port
== 0 || *port
== child_port
) {
1171 "GDBRemoteCommunication::%s() "
1172 "debugserver listens %u port",
1173 __FUNCTION__
, *port
);
1176 "GDBRemoteCommunication::%s() "
1177 "debugserver listening on port "
1178 "%d but requested port was %d",
1179 __FUNCTION__
, (uint32_t)child_port
, (uint32_t)(*port
));
1183 "GDBRemoteCommunication::%s() "
1184 "failed to read a port value from pipe %s: %s",
1185 __FUNCTION__
, named_pipe_path
.c_str(), error
.AsCString());
1187 socket_pipe
.Close();
1190 if (named_pipe_path
.size() > 0) {
1191 const auto err
= socket_pipe
.Delete(named_pipe_path
);
1194 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1195 __FUNCTION__
, named_pipe_path
.c_str(), err
.AsCString());
1199 // Make sure we actually connect with the debugserver...
1203 error
= Status::FromErrorString("unable to locate " DEBUGSERVER_BASENAME
);
1207 LLDB_LOGF(log
, "GDBRemoteCommunication::%s() failed: %s", __FUNCTION__
,
1214 void GDBRemoteCommunication::DumpHistory(Stream
&strm
) { m_history
.Dump(strm
); }
1217 GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication
&client
,
1218 GDBRemoteCommunication
&server
) {
1219 const int backlog
= 5;
1220 TCPSocket
listen_socket(true);
1221 if (llvm::Error error
=
1222 listen_socket
.Listen("localhost:0", backlog
).ToError())
1225 llvm::SmallString
<32> remote_addr
;
1226 llvm::raw_svector_ostream(remote_addr
)
1227 << "connect://localhost:" << listen_socket
.GetLocalPortNumber();
1229 std::unique_ptr
<ConnectionFileDescriptor
> conn_up(
1230 new ConnectionFileDescriptor());
1232 if (conn_up
->Connect(remote_addr
, &status
) != lldb::eConnectionStatusSuccess
)
1233 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1234 "Unable to connect: %s", status
.AsCString());
1236 // The connection was already established above, so a short timeout is
1238 Socket
*accept_socket
= nullptr;
1239 if (Status accept_status
=
1240 listen_socket
.Accept(std::chrono::seconds(1), accept_socket
);
1241 accept_status
.Fail())
1242 return accept_status
.takeError();
1244 client
.SetConnection(std::move(conn_up
));
1245 server
.SetConnection(
1246 std::make_unique
<ConnectionFileDescriptor
>(accept_socket
));
1247 return llvm::Error::success();
1250 GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
1251 GDBRemoteCommunication
&gdb_comm
, std::chrono::seconds timeout
)
1252 : m_gdb_comm(gdb_comm
), m_saved_timeout(0), m_timeout_modified(false) {
1253 auto curr_timeout
= gdb_comm
.GetPacketTimeout();
1254 // Only update the timeout if the timeout is greater than the current
1255 // timeout. If the current timeout is larger, then just use that.
1256 if (curr_timeout
< timeout
) {
1257 m_timeout_modified
= true;
1258 m_saved_timeout
= m_gdb_comm
.SetPacketTimeout(timeout
);
1262 GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
1263 // Only restore the timeout if we set it in the constructor.
1264 if (m_timeout_modified
)
1265 m_gdb_comm
.SetPacketTimeout(m_saved_timeout
);
1268 void llvm::format_provider
<GDBRemoteCommunication::PacketResult
>::format(
1269 const GDBRemoteCommunication::PacketResult
&result
, raw_ostream
&Stream
,
1271 using PacketResult
= GDBRemoteCommunication::PacketResult
;
1274 case PacketResult::Success
:
1275 Stream
<< "Success";
1277 case PacketResult::ErrorSendFailed
:
1278 Stream
<< "ErrorSendFailed";
1280 case PacketResult::ErrorSendAck
:
1281 Stream
<< "ErrorSendAck";
1283 case PacketResult::ErrorReplyFailed
:
1284 Stream
<< "ErrorReplyFailed";
1286 case PacketResult::ErrorReplyTimeout
:
1287 Stream
<< "ErrorReplyTimeout";
1289 case PacketResult::ErrorReplyInvalid
:
1290 Stream
<< "ErrorReplyInvalid";
1292 case PacketResult::ErrorReplyAck
:
1293 Stream
<< "ErrorReplyAck";
1295 case PacketResult::ErrorDisconnected
:
1296 Stream
<< "ErrorDisconnected";
1298 case PacketResult::ErrorNoSequenceLock
:
1299 Stream
<< "ErrorNoSequenceLock";
1304 std::string
GDBRemoteCommunication::ExpandRLE(std::string packet
) {
1305 // Reserve enough byte for the most common case (no RLE used).
1306 std::string decoded
;
1307 decoded
.reserve(packet
.size());
1308 for (std::string::const_iterator c
= packet
.begin(); c
!= packet
.end(); ++c
) {
1310 // '*' indicates RLE. Next character will give us the repeat count and
1311 // previous character is what is to be repeated.
1312 char char_to_repeat
= decoded
.back();
1313 // Number of time the previous character is repeated.
1314 int repeat_count
= *++c
+ 3 - ' ';
1315 // We have the char_to_repeat and repeat_count. Now push it in the
1317 for (int i
= 0; i
< repeat_count
; ++i
)
1318 decoded
.push_back(char_to_repeat
);
1319 } else if (*c
== 0x7d) {
1320 // 0x7d is the escape character. The next character is to be XOR'd with
1322 char escapee
= *++c
^ 0x20;
1323 decoded
.push_back(escapee
);
1325 decoded
.push_back(*c
);