LLDB mainline
GDBRemoteCommunication.cpp
Go to the documentation of this file.
1//===-- GDBRemoteCommunication.cpp ----------------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
10
11#include <climits>
12#include <cstring>
13#include <future>
14#include <sys/stat.h>
15
16#include "lldb/Host/Config.h"
19#include "lldb/Host/Host.h"
20#include "lldb/Host/HostInfo.h"
21#include "lldb/Host/Pipe.h"
23#include "lldb/Host/Socket.h"
28#include "lldb/Utility/Event.h"
30#include "lldb/Utility/Log.h"
33#include "llvm/ADT/SmallString.h"
34#include "llvm/Config/llvm-config.h" // for LLVM_ENABLE_ZLIB
35#include "llvm/Support/ScopedPrinter.h"
36
37#include "ProcessGDBRemoteLog.h"
38
39#if defined(__APPLE__)
40#define DEBUGSERVER_BASENAME "debugserver"
41#elif defined(_WIN32)
42#define DEBUGSERVER_BASENAME "lldb-server.exe"
43#else
44#define DEBUGSERVER_BASENAME "lldb-server"
45#endif
46
47#if defined(HAVE_LIBCOMPRESSION)
48#include <compression.h>
49#endif
50
51#if LLVM_ENABLE_ZLIB
52#include <zlib.h>
53#endif
54
55using namespace lldb;
56using namespace lldb_private;
58
59// GDBRemoteCommunication constructor
61 : Communication(),
62#ifdef LLDB_CONFIGURATION_DEBUG
63 m_packet_timeout(1000),
64#else
65 m_packet_timeout(1),
66#endif
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() {
70}
71
72// Destructor
74 if (IsConnected()) {
75 Disconnect();
76 }
77
78#if defined(HAVE_LIBCOMPRESSION)
79 if (m_decompression_scratch)
80 free (m_decompression_scratch);
81#endif
82}
83
84char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
85 int checksum = 0;
86
87 for (char c : payload)
88 checksum += c;
89
90 return checksum & 255;
91}
92
96 char ch = '+';
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);
100 return bytes_written;
101}
102
106 char ch = '-';
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);
110 return bytes_written;
111}
112
115 StreamString packet(0, 4, eByteOrderBig);
116 packet.PutChar('$');
117 packet.Write(payload.data(), payload.size());
118 packet.PutChar('#');
119 packet.PutHex8(CalculcateChecksum(payload));
120 std::string packet_str = std::string(packet.GetString());
121
122 return SendRawPacketNoLock(packet_str);
123}
124
127 llvm::StringRef notify_type, std::deque<std::string> &queue,
128 llvm::StringRef payload) {
130
131 // If there are no notification in the queue, send the notification
132 // packet.
133 if (queue.empty()) {
134 StreamString packet(0, 4, eByteOrderBig);
135 packet.PutChar('%');
136 packet.Write(notify_type.data(), notify_type.size());
137 packet.PutChar(':');
138 packet.Write(payload.data(), payload.size());
139 packet.PutChar('#');
140 packet.PutHex8(CalculcateChecksum(payload));
141 ret = SendRawPacketNoLock(packet.GetString(), true);
142 }
143
144 queue.push_back(payload.str());
145 return ret;
146}
147
150 bool skip_ack) {
151 if (IsConnected()) {
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);
157 if (log) {
158 size_t binary_start_offset = 0;
159 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
160 0) {
161 const char *first_comma = strchr(packet_data, ',');
162 if (first_comma) {
163 const char *second_comma = strchr(first_comma + 1, ',');
164 if (second_comma)
165 binary_start_offset = second_comma - packet_data + 1;
166 }
167 }
168
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
172 // more than once
173 if (!m_history.DidDumpToLog())
174 m_history.Dump(log);
175
176 if (binary_start_offset) {
177 StreamString strm;
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);
181 const uint8_t *p;
182 // Print binary data exactly as sent
183 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
184 ++p)
185 strm.Printf("\\x%2.2x", *p);
186 // Print the checksum
187 strm.Printf("%*s", (int)3, p);
188 log->PutString(strm.GetString());
189 } else
190 LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %.*s",
191 (uint64_t)bytes_written, (int)packet_length, packet_data);
192 }
193
194 m_history.AddPacket(packet.str(), packet_length,
195 GDBRemotePacket::ePacketTypeSend, bytes_written);
196
197 if (bytes_written == packet_length) {
198 if (!skip_ack && GetSendAcks())
199 return GetAck();
200 else
202 } else {
203 LLDB_LOGF(log, "error: failed to send packet: %.*s", (int)packet_length,
204 packet_data);
205 }
206 }
208}
209
212 PacketResult result = WaitForPacketNoLock(packet, GetPacketTimeout(), false);
213 if (result == PacketResult::Success) {
214 if (packet.GetResponseType() ==
217 else
219 }
220 return result;
221}
222
225 Timeout<std::micro> timeout,
226 bool sync_on_timeout) {
227 using ResponseType = StringExtractorGDBRemote::ResponseType;
228
230 for (;;) {
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))
236 return result;
237 LLDB_LOG(log, "discarding spurious `{0}` packet", response.GetStringRef());
238 }
239}
240
243 Timeout<std::micro> timeout,
244 bool sync_on_timeout) {
245 uint8_t buffer[8192];
247
249
250 // Check for a packet from our cache first without trying any reading...
251 if (CheckForPacket(nullptr, 0, packet) != PacketType::Invalid)
253
254 bool timed_out = false;
255 bool disconnected = false;
256 while (IsConnected() && !timed_out) {
258 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
259
260 LLDB_LOGV(log,
261 "Read(buffer, sizeof(buffer), timeout = {0}, "
262 "status = {1}, error = {2}) => bytes_read = {3}",
264 bytes_read);
265
266 if (bytes_read > 0) {
267 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
269 } else {
270 switch (status) {
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.
276 ///
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.
284 ///
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
295 /// disconnect.
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;
302
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;
308 regex_str += "$";
309 response_regex = RegularExpression(regex_str);
310 } else {
311 echo_packet_len =
312 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
313 response_regex =
314 RegularExpression(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
315 }
316
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;
324 echo_packet_result =
325 WaitForPacketNoLock(echo_response, timeout, false);
326 if (echo_packet_result == PacketResult::Success) {
327 ++successful_responses;
328 if (response_regex.Execute(echo_response.GetStringRef())) {
329 sync_success = true;
330 break;
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;
338 }
339 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
340 continue; // Packet timed out, continue waiting for a response
341 else
342 break; // Something else went wrong getting the packet back, we
343 // failed and are done trying
344 }
345 }
346
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...
349 if (sync_success) {
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...
356 }
357 } else {
358 disconnected = true;
359 Disconnect();
360 }
361 }
362 timed_out = true;
363 break;
365 // printf ("status = success but error = %s\n",
366 // error.AsCString("<invalid>"));
367 break;
368
373 disconnected = true;
374 Disconnect();
375 break;
376 }
377 }
378 }
379 packet.Clear();
380 if (disconnected)
382 if (timed_out)
384 else
386}
387
390
392 return true;
393
394 size_t pkt_size = m_bytes.size();
395
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.
399 if (pkt_size < 5)
400 return true;
401
402 if (m_bytes[0] != '$' && m_bytes[0] != '%')
403 return true;
404 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
405 return true;
406
407 size_t hash_mark_idx = m_bytes.find('#');
408 if (hash_mark_idx == std::string::npos)
409 return true;
410 if (hash_mark_idx + 2 >= m_bytes.size())
411 return true;
412
413 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
414 !::isxdigit(m_bytes[hash_mark_idx + 2]))
415 return true;
416
417 size_t content_length =
418 pkt_size -
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 =
423 hash_mark_idx +
424 1; // The first character of the two hex checksum characters
425
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;
431
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.
436
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]))
441 i++;
442 if (i < hash_mark_idx && m_bytes[i] == ':') {
443 i++;
444 content_start = i;
445 content_length = hash_mark_idx - content_start;
446 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
447 errno = 0;
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);
451 return false;
452 }
453 }
454 }
455
456 if (GetSendAcks()) {
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);
462
463 long actual_checksum = CalculcateChecksum(
464 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
465 bool success = packet_checksum == actual_checksum;
466 if (!success) {
467 LLDB_LOGF(log,
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);
471 }
472 // Send the ack or nack if needed
473 if (!success) {
474 SendNack();
475 m_bytes.erase(0, size_of_first_packet);
476 return false;
477 } else {
478 SendAck();
479 }
480 }
481
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.
485 m_bytes.erase(1, 1);
486 return true;
487 }
488
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] == '}') {
496 i++;
497 unescaped_content.push_back(m_bytes[i] ^ 0x20);
498 } else {
499 unescaped_content.push_back(m_bytes[i]);
500 }
501 i++;
502 }
503
504 uint8_t *decompressed_buffer = nullptr;
505 size_t decompressed_bytes = 0;
506
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);
511 return false;
512 }
513 }
514
515#if defined(HAVE_LIBCOMPRESSION)
520 compression_algorithm compression_type;
522 compression_type = COMPRESSION_LZFSE;
524 compression_type = COMPRESSION_ZLIB;
526 compression_type = COMPRESSION_LZ4_RAW;
528 compression_type = COMPRESSION_LZMA;
529
530 if (m_decompression_scratch_type != m_compression_type) {
531 if (m_decompression_scratch) {
532 free (m_decompression_scratch);
533 m_decompression_scratch = nullptr;
534 }
535 size_t scratchbuf_size = 0;
537 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
539 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
541 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
543 scratchbuf_size =
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;
548 }
549 }
550
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);
556 }
557 }
558#endif
559
560#if LLVM_ENABLE_ZLIB
561 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
562 decompressed_buffer != nullptr &&
564 z_stream stream;
565 memset(&stream, 0, sizeof(z_stream));
566 stream.next_in = (Bytef *)unescaped_content.data();
567 stream.avail_in = (uInt)unescaped_content.size();
568 stream.total_in = 0;
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;
575
576 if (inflateInit2(&stream, -15) == Z_OK) {
577 int status = inflate(&stream, Z_NO_FLUSH);
578 inflateEnd(&stream);
579 if (status == Z_STREAM_END) {
580 decompressed_bytes = stream.total_out;
581 }
582 }
583 }
584#endif
585
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);
590 return false;
591 }
592
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('#');
598 if (GetSendAcks()) {
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);
604 } else {
605 new_packet.push_back('0');
606 new_packet.push_back('0');
607 }
608
609 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
610 new_packet.size());
611
612 free(decompressed_buffer);
613 return true;
614}
615
617GDBRemoteCommunication::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);
621
623
624 if (src && src_len > 0) {
625 if (log && log->GetVerbose()) {
626 StreamString s;
627 LLDB_LOGF(log, "GDBRemoteCommunication::%s adding %u bytes: %.*s",
628 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
629 }
630 m_bytes.append((const char *)src, src_len);
631 }
632
633 bool isNotifyPacket = false;
634
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;
643
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()) {
648 packet.Clear();
650 }
651 }
652
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...
658 break;
659
660 case '%': // Async notify packet
661 isNotifyPacket = true;
662 [[fallthrough]];
663
664 case '$':
665 // Look for a standard gdb packet?
666 {
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
672 content_start = 1;
673 // Don't include the # in the content or the $ in the content
674 // length
675 content_length = hash_pos - 1;
676
677 total_length =
678 hash_pos + 3; // Skip the # and the two hex checksum bytes
679 } else {
680 // Checksum bytes aren't all here yet
681 content_length = std::string::npos;
682 }
683 }
684 }
685 break;
686
687 default: {
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();
693 bool done = false;
694 uint32_t idx;
695 for (idx = 1; !done && idx < bytes_len; ++idx) {
696 switch (m_bytes[idx]) {
697 case '+':
698 case '-':
699 case '\x03':
700 case '%':
701 case '$':
702 done = true;
703 break;
704
705 default:
706 break;
707 }
708 }
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);
712 } break;
713 }
714
715 if (content_length == std::string::npos) {
716 packet.Clear();
718 } else if (total_length > 0) {
719
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;
725
726 bool success = true;
727 if (log) {
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())
733 m_history.Dump(log);
734
735 bool binary = false;
736 // Only detect binary for packets that start with a '$' and have a
737 // '#CC' checksum
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)) {
742 binary = true;
743 }
744 }
745 }
746 if (binary) {
747 StreamString strm;
748 // Packet header...
750 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
751 (uint64_t)original_packet_size, (uint64_t)total_length,
752 m_bytes[0]);
753 else
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];
759 if (ch == 0x7d) {
760 // 0x7d is the escape character. The next character is to be
761 // XOR'd with 0x20.
762 const char escapee = m_bytes[++i] ^ 0x20;
763 strm.Printf("%2.2x", escapee);
764 } else {
765 strm.Printf("%2.2x", (uint8_t)ch);
766 }
767 }
768 // Packet footer...
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());
772 } else {
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());
777 else
778 LLDB_LOGF(log, "<%4" PRIu64 "> read packet: %.*s",
779 (uint64_t)total_length, (int)(total_length),
780 m_bytes.c_str());
781 }
782 }
783
784 m_history.AddPacket(m_bytes, total_length,
786
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);
792
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])) {
797 if (GetSendAcks()) {
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;
803 if (!success) {
804 LLDB_LOGF(log,
805 "error: checksum mismatch: %.*s expected 0x%2.2x, "
806 "got 0x%2.2x",
807 (int)(total_length), m_bytes.c_str(),
808 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
809 }
810 // Send the ack or nack if needed
811 if (!success)
812 SendNack();
813 else
814 SendAck();
815 }
816 } else {
817 success = false;
818 LLDB_LOGF(log, "error: invalid checksum in packet: '%s'\n",
819 m_bytes.c_str());
820 }
821 }
822
823 m_bytes.erase(0, total_length);
824 packet.SetFilePos(0);
825
826 if (isNotifyPacket)
828 else
830 }
831 }
832 packet.Clear();
834}
835
837 uint16_t port) {
839 return Status::FromErrorString("listen thread already running");
840
841 char listen_url[512];
842 if (hostname && hostname[0])
843 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
844 else
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(); });
850 if (!listen_thread)
851 return Status::FromError(listen_thread.takeError());
852 m_listen_thread = *listen_thread;
853
854 return Status();
855}
856
859 m_listen_thread.Join(nullptr);
860 return true;
861}
862
865 ConnectionFileDescriptor *connection =
867
868 if (connection) {
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) {
873 uint16_t port = 0;
874 llvm::to_integer(port_str, port, 10);
875 m_port_promise.set_value(port);
876 },
878 SetConnection(nullptr);
879 }
880 return {};
881}
882
885 // If we locate debugserver, keep that located version around
886 static FileSpec g_debugserver_file_spec;
887 FileSpec debugserver_file_spec;
888
890
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);
897 LLDB_LOGF(log,
898 "GDBRemoteCommunication::%s() gdb-remote stub exe path set "
899 "from environment variable: %s",
900 __FUNCTION__, env_debugserver_path.c_str());
901 } else
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) {
912 LLDB_LOGF(log,
913 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
914 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
915
916 g_debugserver_file_spec = debugserver_file_spec;
917 } else {
918 if (platform)
919 debugserver_file_spec =
921 else
922 debugserver_file_spec.Clear();
923 if (debugserver_file_spec) {
924 // Platform::LocateExecutable() wouldn't return a path if it doesn't
925 // exist
926 debugserver_exists = true;
927 } else {
928 LLDB_LOGF(log,
929 "GDBRemoteCommunication::%s() could not find "
930 "gdb-remote stub exe '%s'",
931 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
932 }
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();
936 }
937 }
938 }
939 return debugserver_file_spec;
940}
941
943 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
944 uint16_t *port, const Args *inferior_args, shared_fd_t pass_comm_fd) {
946 LLDB_LOGF(log, "GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
947 __FUNCTION__, url ? url : "<empty>", port ? *port : uint16_t(0));
948
950 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
951 if ((debugserver_file_spec = GetDebugserverPath(platform))) {
952 std::string debugserver_path = debugserver_file_spec.GetPath();
953
954 Args &debugserver_args = launch_info.GetArguments();
955 debugserver_args.Clear();
956
957 // Start args with "debugserver /file/path -r --"
958 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
959
960#if !defined(__APPLE__)
961 // First argument to lldb-server must be mode in which to run.
962 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
963#endif
964
965 // If a url is supplied then use it
966 if (url && url[0])
967 debugserver_args.AppendArgument(llvm::StringRef(url));
968
969 if (pass_comm_fd != SharedSocket::kInvalidFD) {
970 StreamString fd_arg;
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.
975#ifndef _WIN32
976 launch_info.AppendDuplicateFileAction((int)pass_comm_fd,
977 (int)pass_comm_fd);
978#endif
979 }
980
981 // use native registers, not the GDB registers
982 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
983
984 if (launch_info.GetLaunchInSeparateProcessGroup()) {
985 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
986 }
987
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.
993 Pipe socket_pipe;
994
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
997 // become available.
998 if (pass_comm_fd == SharedSocket::kInvalidFD) {
999 if (url) {
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);
1008 if (error.Fail()) {
1009 LLDB_LOGF(log,
1010 "GDBRemoteCommunication::%s() "
1011 "named pipe creation failed: %s",
1012 __FUNCTION__, error.AsCString());
1013 return error;
1014 }
1015 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
1016 debugserver_args.AppendArgument(named_pipe_path);
1017#else
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);
1021 if (error.Fail()) {
1022 LLDB_LOGF(log,
1023 "GDBRemoteCommunication::%s() "
1024 "unnamed pipe creation failed: %s",
1025 __FUNCTION__, error.AsCString());
1026 return error;
1027 }
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());
1032#endif
1033 } else {
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);
1037 if (error.Fail()) {
1038 LLDB_LOGF(log,
1039 "GDBRemoteCommunication::%s() unable to start listen "
1040 "thread: %s",
1041 __FUNCTION__, error.AsCString());
1042 return error;
1043 }
1044
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
1049 ? port_future.get()
1050 : 0;
1051 if (port_ > 0) {
1052 char port_cstr[32];
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
1056 // process
1057 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1058 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
1059 if (port)
1060 *port = port_;
1061 } else {
1062 LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s",
1063 __FUNCTION__, error.AsCString());
1065 "failed to bind to port 0 on 127.0.0.1");
1066 }
1067 }
1068 }
1069
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());
1076 }
1077
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());
1084 }
1085#else
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)
1091 .str());
1092 }
1093#endif
1094
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;
1098 bool has_env_var;
1099 do {
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();
1105
1106 if (has_env_var) {
1107 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
1108 LLDB_LOGF(log,
1109 "GDBRemoteCommunication::%s adding env var %s contents "
1110 "to stub command line (%s)",
1111 __FUNCTION__, env_var_name, extra_arg.c_str());
1112 }
1113 } while (has_env_var);
1114
1115 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
1116 debugserver_args.AppendArgument(llvm::StringRef("--"));
1117 debugserver_args.AppendArguments(*inferior_args);
1118 }
1119
1120 // Copy the current environment to the gdbserver/debugserver instance
1121 launch_info.GetEnvironment() = host_env;
1122
1123 // Close STDIN, STDOUT and STDERR.
1124 launch_info.AppendCloseFileAction(STDIN_FILENO);
1125 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1126 launch_info.AppendCloseFileAction(STDERR_FILENO);
1127
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);
1132
1133 if (log) {
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());
1139 }
1140 error = Host::LaunchProcess(launch_info);
1141
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);
1147 if (error.Fail())
1148 LLDB_LOGF(log,
1149 "GDBRemoteCommunication::%s() "
1150 "failed to open named pipe %s for reading: %s",
1151 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1152 }
1153
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) {
1169 *port = child_port;
1170 LLDB_LOGF(log,
1171 "GDBRemoteCommunication::%s() "
1172 "debugserver listens %u port",
1173 __FUNCTION__, *port);
1174 } else {
1175 LLDB_LOGF(log,
1176 "GDBRemoteCommunication::%s() "
1177 "debugserver listening on port "
1178 "%d but requested port was %d",
1179 __FUNCTION__, (uint32_t)child_port, (uint32_t)(*port));
1180 }
1181 } else {
1182 LLDB_LOGF(log,
1183 "GDBRemoteCommunication::%s() "
1184 "failed to read a port value from pipe %s: %s",
1185 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1186 }
1187 socket_pipe.Close();
1188 }
1189
1190 if (named_pipe_path.size() > 0) {
1191 const auto err = socket_pipe.Delete(named_pipe_path);
1192 if (err.Fail()) {
1193 LLDB_LOGF(log,
1194 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1195 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
1196 }
1197 }
1198
1199 // Make sure we actually connect with the debugserver...
1201 }
1202 } else {
1203 error = Status::FromErrorString("unable to locate " DEBUGSERVER_BASENAME);
1204 }
1205
1206 if (error.Fail()) {
1207 LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1208 error.AsCString());
1209 }
1210
1211 return error;
1212}
1213
1215
1216llvm::Error
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())
1223 return error;
1224
1225 llvm::SmallString<32> remote_addr;
1226 llvm::raw_svector_ostream(remote_addr)
1227 << "connect://localhost:" << listen_socket.GetLocalPortNumber();
1228
1229 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1231 Status status;
1232 if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)
1233 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1234 "Unable to connect: %s", status.AsCString());
1235
1236 // The connection was already established above, so a short timeout is
1237 // sufficient.
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();
1243
1244 client.SetConnection(std::move(conn_up));
1245 server.SetConnection(
1246 std::make_unique<ConnectionFileDescriptor>(accept_socket));
1247 return llvm::Error::success();
1248}
1249
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;
1259 }
1260}
1261
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);
1266}
1267
1268void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1269 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1270 StringRef Style) {
1272
1273 switch (result) {
1275 Stream << "Success";
1276 break;
1278 Stream << "ErrorSendFailed";
1279 break;
1281 Stream << "ErrorSendAck";
1282 break;
1284 Stream << "ErrorReplyFailed";
1285 break;
1287 Stream << "ErrorReplyTimeout";
1288 break;
1290 Stream << "ErrorReplyInvalid";
1291 break;
1293 Stream << "ErrorReplyAck";
1294 break;
1296 Stream << "ErrorDisconnected";
1297 break;
1299 Stream << "ErrorNoSequenceLock";
1300 break;
1301 }
1302}
1303
1304std::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) {
1309 if (*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
1316 // packet.
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
1321 // 0x20.
1322 char escapee = *++c ^ 0x20;
1323 decoded.push_back(escapee);
1324 } else {
1325 decoded.push_back(*c);
1326 }
1327 }
1328 return decoded;
1329}
static llvm::raw_ostream & error(Stream &strm)
#define DEBUGSERVER_BASENAME
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition: Log.h:369
#define LLDB_LOGF(log,...)
Definition: Log.h:376
#define LLDB_LOGV(log,...)
Definition: Log.h:383
ResponseType GetResponseType() const
void SetFilePos(uint32_t idx)
llvm::StringRef GetStringRef() const
A command line argument class.
Definition: Args.h:33
void AppendArguments(const Args &rhs)
Definition: Args.cpp:307
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition: Args.h:120
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition: Args.cpp:332
void Clear()
Clear the arguments.
Definition: Args.cpp:388
An abstract communications class.
Definition: Communication.h:39
virtual size_t Read(void *dst, size_t dst_len, const Timeout< std::micro > &timeout, lldb::ConnectionStatus &status, Status *error_ptr)
Read bytes from the current connection.
bool IsConnected() const
Check if the connection is valid.
virtual void SetConnection(std::unique_ptr< Connection > connection)
Sets the connection that it to be used by this class.
size_t WriteAll(const void *src, size_t src_len, lldb::ConnectionStatus &status, Status *error_ptr)
Repeatedly attempt writing until either src_len bytes are written or a permanent failure occurs.
virtual lldb::ConnectionStatus Disconnect(Status *error_ptr=nullptr)
Disconnect the communications connection if one is currently connected.
static std::string ConnectionStatusAsString(lldb::ConnectionStatus status)
lldb_private::Connection * GetConnection()
Definition: Communication.h:87
lldb::ConnectionStatus Connect(llvm::StringRef url, Status *error_ptr) override
Connect using the connect string url.
A file utility class.
Definition: FileSpec.h:56
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition: FileSpec.cpp:174
void AppendPathComponent(llvm::StringRef component)
Definition: FileSpec.cpp:447
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition: FileSpec.cpp:367
void Clear()
Clears the object state.
Definition: FileSpec.cpp:259
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
static FileSystem & Instance()
Status Join(lldb::thread_result_t *result)
Definition: HostThread.cpp:20
static Status LaunchProcess(ProcessLaunchInfo &launch_info)
Launch the process specified in launch_info.
static Environment GetEnvironment()
bool GetVerbose() const
Definition: Log.cpp:326
void PutString(llvm::StringRef str)
Definition: Log.cpp:147
A posix-based implementation of Pipe, a class that abtracts unix style pipes.
Definition: PipePosix.h:21
Status OpenAsReader(llvm::StringRef name, bool child_process_inherit) override
Definition: PipePosix.cpp:146
int GetReadFileDescriptor() const override
Definition: PipePosix.cpp:208
lldb::pipe_t GetWritePipe() const override
Definition: PipePosix.h:51
void CloseWriteFileDescriptor() override
Definition: PipePosix.cpp:291
bool CanWrite() const override
Definition: PipePosix.cpp:271
bool CanRead() const override
Definition: PipePosix.cpp:262
void Close() override
Definition: PipePosix.cpp:248
Status ReadWithTimeout(void *buf, size_t size, const std::chrono::microseconds &timeout, size_t &bytes_read) override
Definition: PipePosix.cpp:303
Status Delete(llvm::StringRef name) override
Definition: PipePosix.cpp:258
Status CreateWithUniqueName(llvm::StringRef prefix, bool child_process_inherit, llvm::SmallVectorImpl< char > &name) override
Definition: PipePosix.cpp:121
Status CreateNew(bool child_process_inherit) override
Definition: PipePosix.cpp:80
A plug-in interface definition class for debug platform that includes many platform abilities such as...
Definition: Platform.h:76
virtual FileSpec LocateExecutable(const char *basename)
Find a support executable that may not live within in the standard locations related to LLDB.
Definition: Platform.h:808
void Dump(Stream &s, Platform *platform) const
Definition: ProcessInfo.cpp:53
lldb::pid_t GetProcessID() const
Definition: ProcessInfo.h:68
FileSpec & GetExecutableFile()
Definition: ProcessInfo.h:43
Environment & GetEnvironment()
Definition: ProcessInfo.h:88
bool AppendSuppressFileAction(int fd, bool read, bool write)
bool AppendDuplicateFileAction(int fd, int dup_fd)
bool Execute(llvm::StringRef string, llvm::SmallVectorImpl< llvm::StringRef > *matches=nullptr) const
Execute a regular expression match using the compiled regular expression that is already in this obje...
static const shared_fd_t kInvalidFD
Definition: Socket.h:50
An error handling class.
Definition: Status.h:118
llvm::Error ToError() const
FIXME: Replace all uses with takeError() instead.
Definition: Status.cpp:139
static Status FromErrorString(const char *str)
Definition: Status.h:141
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:195
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition: Status.cpp:137
const char * GetData() const
Definition: StreamString.h:45
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
Definition: Stream.h:112
size_t size_t PutHex8(uint8_t uvalue)
Append an uint8_t value in the hexadecimal format to the stream.
Definition: Stream.cpp:261
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:134
size_t PutChar(char ch)
Definition: Stream.cpp:131
Status Listen(llvm::StringRef name, int backlog) override
Definition: TCPSocket.cpp:176
llvm::Expected< std::vector< MainLoopBase::ReadHandleUP > > Accept(MainLoopBase &loop, std::function< void(std::unique_ptr< Socket > socket)> sock_cb) override
Definition: TCPSocket.cpp:240
uint16_t GetLocalPortNumber() const
Definition: TCPSocket.cpp:60
static llvm::Expected< HostThread > LaunchThread(llvm::StringRef name, std::function< lldb::thread_result_t()> thread_function, size_t min_stack_byte_size=0)
void AddPacket(char packet_char, GDBRemotePacket::Type type, uint32_t bytes_transmitted)
ScopedTimeout(GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
std::chrono::seconds SetPacketTimeout(std::chrono::seconds packet_timeout)
static llvm::Error ConnectLocally(GDBRemoteCommunication &client, GDBRemoteCommunication &server)
PacketResult ReadPacket(StringExtractorGDBRemote &response, Timeout< std::micro > timeout, bool sync_on_timeout)
PacketResult SendNotificationPacketNoLock(llvm::StringRef notify_type, std::deque< std::string > &queue, llvm::StringRef payload)
PacketResult WaitForPacketNoLock(StringExtractorGDBRemote &response, Timeout< std::micro > timeout, bool sync_on_timeout)
PacketResult SendRawPacketNoLock(llvm::StringRef payload, bool skip_ack=false)
Status StartListenThread(const char *hostname="127.0.0.1", uint16_t port=0)
Status StartDebugserverProcess(const char *url, Platform *platform, ProcessLaunchInfo &launch_info, uint16_t *port, const Args *inferior_args, shared_fd_t pass_comm_fd)
static std::string ExpandRLE(std::string)
Expand GDB run-length encoding.
PacketType CheckForPacket(const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
#define LLDB_INVALID_PROCESS_ID
Definition: lldb-defines.h:89
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:332
NativeSocket shared_fd_t
Definition: Socket.h:42
Definition: SBAddress.h:15
int pipe_t
Definition: lldb-types.h:64
void * thread_result_t
Definition: lldb-types.h:62
ConnectionStatus
Connection Status Types.
@ eConnectionStatusError
Check GetError() for details.
@ eConnectionStatusInterrupted
Interrupted read.
@ eConnectionStatusTimedOut
Request timed out.
@ eConnectionStatusEndOfFile
End-of-file encountered.
@ eConnectionStatusSuccess
Success.
@ eConnectionStatusLostConnection
Lost connection while connected to a valid connection.
@ eConnectionStatusNoConnection
No connection.