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/Core/StreamFile.h"
17 #include "lldb/Host/Config.h"
19 #include "lldb/Host/FileSystem.h"
20 #include "lldb/Host/Host.h"
21 #include "lldb/Host/HostInfo.h"
22 #include "lldb/Host/Pipe.h"
24 #include "lldb/Host/Socket.h"
28 #include "lldb/Target/Platform.h"
29 #include "lldb/Utility/Event.h"
30 #include "lldb/Utility/FileSpec.h"
31 #include "lldb/Utility/Log.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/Support/ScopedPrinter.h"
37 
38 #include "ProcessGDBRemoteLog.h"
39 
40 #if defined(__APPLE__)
41 #define DEBUGSERVER_BASENAME "debugserver"
42 #elif defined(_WIN32)
43 #define DEBUGSERVER_BASENAME "lldb-server.exe"
44 #else
45 #define DEBUGSERVER_BASENAME "lldb-server"
46 #endif
47 
48 #if defined(HAVE_LIBCOMPRESSION)
49 #include <compression.h>
50 #endif
51 
52 #if LLVM_ENABLE_ZLIB
53 #include <zlib.h>
54 #endif
55 
56 using namespace lldb;
57 using namespace lldb_private;
58 using namespace lldb_private::process_gdb_remote;
59 
60 // GDBRemoteCommunication constructor
61 GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
62  const char *listener_name)
63  : Communication(comm_name),
64 #ifdef LLDB_CONFIGURATION_DEBUG
65  m_packet_timeout(1000),
66 #else
67  m_packet_timeout(1),
68 #endif
69  m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
70  m_send_acks(true), m_compression_type(CompressionType::None),
71  m_listen_url() {
72 }
73 
74 // Destructor
76  if (IsConnected()) {
77  Disconnect();
78  }
79 
80 #if defined(HAVE_LIBCOMPRESSION)
81  if (m_decompression_scratch)
82  free (m_decompression_scratch);
83 #endif
84 }
85 
86 char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
87  int checksum = 0;
88 
89  for (char c : payload)
90  checksum += c;
91 
92  return checksum & 255;
93 }
94 
96  Log *log = GetLog(GDBRLog::Packets);
98  char ch = '+';
99  const size_t bytes_written = WriteAll(&ch, 1, status, nullptr);
100  LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
102  return bytes_written;
103 }
104 
106  Log *log = GetLog(GDBRLog::Packets);
108  char ch = '-';
109  const size_t bytes_written = WriteAll(&ch, 1, status, nullptr);
110  LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
112  return bytes_written;
113 }
114 
117  StreamString packet(0, 4, eByteOrderBig);
118  packet.PutChar('$');
119  packet.Write(payload.data(), payload.size());
120  packet.PutChar('#');
121  packet.PutHex8(CalculcateChecksum(payload));
122  std::string packet_str = std::string(packet.GetString());
123 
124  return SendRawPacketNoLock(packet_str);
125 }
126 
129  bool skip_ack) {
130  if (IsConnected()) {
131  Log *log = GetLog(GDBRLog::Packets);
133  const char *packet_data = packet.data();
134  const size_t packet_length = packet.size();
135  size_t bytes_written = WriteAll(packet_data, packet_length, status, nullptr);
136  if (log) {
137  size_t binary_start_offset = 0;
138  if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
139  0) {
140  const char *first_comma = strchr(packet_data, ',');
141  if (first_comma) {
142  const char *second_comma = strchr(first_comma + 1, ',');
143  if (second_comma)
144  binary_start_offset = second_comma - packet_data + 1;
145  }
146  }
147 
148  // If logging was just enabled and we have history, then dump out what we
149  // have to the log so we get the historical context. The Dump() call that
150  // logs all of the packet will set a boolean so that we don't dump this
151  // more than once
152  if (!m_history.DidDumpToLog())
153  m_history.Dump(log);
154 
155  if (binary_start_offset) {
156  StreamString strm;
157  // Print non binary data header
158  strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
159  (int)binary_start_offset, packet_data);
160  const uint8_t *p;
161  // Print binary data exactly as sent
162  for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
163  ++p)
164  strm.Printf("\\x%2.2x", *p);
165  // Print the checksum
166  strm.Printf("%*s", (int)3, p);
167  log->PutString(strm.GetString());
168  } else
169  LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %.*s",
170  (uint64_t)bytes_written, (int)packet_length, packet_data);
171  }
172 
173  m_history.AddPacket(packet.str(), packet_length,
174  GDBRemotePacket::ePacketTypeSend, bytes_written);
175 
176  if (bytes_written == packet_length) {
177  if (!skip_ack && GetSendAcks())
178  return GetAck();
179  else
180  return PacketResult::Success;
181  } else {
182  LLDB_LOGF(log, "error: failed to send packet: %.*s", (int)packet_length,
183  packet_data);
184  }
185  }
187 }
188 
191  PacketResult result = WaitForPacketNoLock(packet, GetPacketTimeout(), false);
192  if (result == PacketResult::Success) {
193  if (packet.GetResponseType() ==
194  StringExtractorGDBRemote::ResponseType::eAck)
195  return PacketResult::Success;
196  else
198  }
199  return result;
200 }
201 
205  bool sync_on_timeout,
206  llvm::function_ref<void(llvm::StringRef)> output_callback) {
207  auto result = ReadPacket(response, timeout, sync_on_timeout);
208  while (result == PacketResult::Success && response.IsNormalResponse() &&
209  response.PeekChar() == 'O') {
210  response.GetChar();
211  std::string output;
212  if (response.GetHexByteString(output))
213  output_callback(output);
214  result = ReadPacket(response, timeout, sync_on_timeout);
215  }
216  return result;
217 }
218 
221  Timeout<std::micro> timeout,
222  bool sync_on_timeout) {
223  using ResponseType = StringExtractorGDBRemote::ResponseType;
224 
225  Log *log = GetLog(GDBRLog::Packets);
226  for (;;) {
227  PacketResult result =
228  WaitForPacketNoLock(response, timeout, sync_on_timeout);
229  if (result != PacketResult::Success ||
230  (response.GetResponseType() != ResponseType::eAck &&
231  response.GetResponseType() != ResponseType::eNack))
232  return result;
233  LLDB_LOG(log, "discarding spurious `{0}` packet", response.GetStringRef());
234  }
235 }
236 
239  Timeout<std::micro> timeout,
240  bool sync_on_timeout) {
241  uint8_t buffer[8192];
242  Status error;
243 
244  Log *log = GetLog(GDBRLog::Packets);
245 
246  // Check for a packet from our cache first without trying any reading...
247  if (CheckForPacket(nullptr, 0, packet) != PacketType::Invalid)
248  return PacketResult::Success;
249 
250  bool timed_out = false;
251  bool disconnected = false;
252  while (IsConnected() && !timed_out) {
254  size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
255 
256  LLDB_LOGV(log,
257  "Read(buffer, sizeof(buffer), timeout = {0}, "
258  "status = {1}, error = {2}) => bytes_read = {3}",
260  bytes_read);
261 
262  if (bytes_read > 0) {
263  if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
264  return PacketResult::Success;
265  } else {
266  switch (status) {
269  if (sync_on_timeout) {
270  /// Sync the remote GDB server and make sure we get a response that
271  /// corresponds to what we send.
272  ///
273  /// Sends a "qEcho" packet and makes sure it gets the exact packet
274  /// echoed back. If the qEcho packet isn't supported, we send a qC
275  /// packet and make sure we get a valid thread ID back. We use the
276  /// "qC" packet since its response if very unique: is responds with
277  /// "QC%x" where %x is the thread ID of the current thread. This
278  /// makes the response unique enough from other packet responses to
279  /// ensure we are back on track.
280  ///
281  /// This packet is needed after we time out sending a packet so we
282  /// can ensure that we are getting the response for the packet we
283  /// are sending. There are no sequence IDs in the GDB remote
284  /// protocol (there used to be, but they are not supported anymore)
285  /// so if you timeout sending packet "abc", you might then send
286  /// packet "cde" and get the response for the previous "abc" packet.
287  /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
288  /// many responses for packets can look like responses for other
289  /// packets. So if we timeout, we need to ensure that we can get
290  /// back on track. If we can't get back on track, we must
291  /// disconnect.
292  bool sync_success = false;
293  bool got_actual_response = false;
294  // We timed out, we need to sync back up with the
295  char echo_packet[32];
296  int echo_packet_len = 0;
297  RegularExpression response_regex;
298 
300  echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
301  "qEcho:%u", ++m_echo_number);
302  std::string regex_str = "^";
303  regex_str += echo_packet;
304  regex_str += "$";
305  response_regex = RegularExpression(regex_str);
306  } else {
307  echo_packet_len =
308  ::snprintf(echo_packet, sizeof(echo_packet), "qC");
309  response_regex =
310  RegularExpression(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
311  }
312 
313  PacketResult echo_packet_result =
314  SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
315  if (echo_packet_result == PacketResult::Success) {
316  const uint32_t max_retries = 3;
317  uint32_t successful_responses = 0;
318  for (uint32_t i = 0; i < max_retries; ++i) {
319  StringExtractorGDBRemote echo_response;
320  echo_packet_result =
321  WaitForPacketNoLock(echo_response, timeout, false);
322  if (echo_packet_result == PacketResult::Success) {
323  ++successful_responses;
324  if (response_regex.Execute(echo_response.GetStringRef())) {
325  sync_success = true;
326  break;
327  } else if (successful_responses == 1) {
328  // We got something else back as the first successful
329  // response, it probably is the response to the packet we
330  // actually wanted, so copy it over if this is the first
331  // success and continue to try to get the qEcho response
332  packet = echo_response;
333  got_actual_response = true;
334  }
335  } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
336  continue; // Packet timed out, continue waiting for a response
337  else
338  break; // Something else went wrong getting the packet back, we
339  // failed and are done trying
340  }
341  }
342 
343  // We weren't able to sync back up with the server, we must abort
344  // otherwise all responses might not be from the right packets...
345  if (sync_success) {
346  // We timed out, but were able to recover
347  if (got_actual_response) {
348  // We initially timed out, but we did get a response that came in
349  // before the successful reply to our qEcho packet, so lets say
350  // everything is fine...
351  return PacketResult::Success;
352  }
353  } else {
354  disconnected = true;
355  Disconnect();
356  }
357  }
358  timed_out = true;
359  break;
361  // printf ("status = success but error = %s\n",
362  // error.AsCString("<invalid>"));
363  break;
364 
369  disconnected = true;
370  Disconnect();
371  break;
372  }
373  }
374  }
375  packet.Clear();
376  if (disconnected)
378  if (timed_out)
380  else
382 }
383 
385  Log *log = GetLog(GDBRLog::Packets);
386 
387  if (!CompressionIsEnabled())
388  return true;
389 
390  size_t pkt_size = m_bytes.size();
391 
392  // Smallest possible compressed packet is $N#00 - an uncompressed empty
393  // reply, most commonly indicating an unsupported packet. Anything less than
394  // 5 characters, it's definitely not a compressed packet.
395  if (pkt_size < 5)
396  return true;
397 
398  if (m_bytes[0] != '$' && m_bytes[0] != '%')
399  return true;
400  if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
401  return true;
402 
403  size_t hash_mark_idx = m_bytes.find('#');
404  if (hash_mark_idx == std::string::npos)
405  return true;
406  if (hash_mark_idx + 2 >= m_bytes.size())
407  return true;
408 
409  if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
410  !::isxdigit(m_bytes[hash_mark_idx + 2]))
411  return true;
412 
413  size_t content_length =
414  pkt_size -
415  5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
416  size_t content_start = 2; // The first character of the
417  // compressed/not-compressed text of the packet
418  size_t checksum_idx =
419  hash_mark_idx +
420  1; // The first character of the two hex checksum characters
421 
422  // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
423  // multiple packets. size_of_first_packet is the size of the initial packet
424  // which we'll replace with the decompressed version of, leaving the rest of
425  // m_bytes unmodified.
426  size_t size_of_first_packet = hash_mark_idx + 3;
427 
428  // Compressed packets ("$C") start with a base10 number which is the size of
429  // the uncompressed payload, then a : and then the compressed data. e.g.
430  // $C1024:<binary>#00 Update content_start and content_length to only include
431  // the <binary> part of the packet.
432 
433  uint64_t decompressed_bufsize = ULONG_MAX;
434  if (m_bytes[1] == 'C') {
435  size_t i = content_start;
436  while (i < hash_mark_idx && isdigit(m_bytes[i]))
437  i++;
438  if (i < hash_mark_idx && m_bytes[i] == ':') {
439  i++;
440  content_start = i;
441  content_length = hash_mark_idx - content_start;
442  std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
443  errno = 0;
444  decompressed_bufsize = ::strtoul(bufsize_str.c_str(), nullptr, 10);
445  if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
446  m_bytes.erase(0, size_of_first_packet);
447  return false;
448  }
449  }
450  }
451 
452  if (GetSendAcks()) {
453  char packet_checksum_cstr[3];
454  packet_checksum_cstr[0] = m_bytes[checksum_idx];
455  packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
456  packet_checksum_cstr[2] = '\0';
457  long packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
458 
459  long actual_checksum = CalculcateChecksum(
460  llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
461  bool success = packet_checksum == actual_checksum;
462  if (!success) {
463  LLDB_LOGF(log,
464  "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
465  (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
466  (uint8_t)actual_checksum);
467  }
468  // Send the ack or nack if needed
469  if (!success) {
470  SendNack();
471  m_bytes.erase(0, size_of_first_packet);
472  return false;
473  } else {
474  SendAck();
475  }
476  }
477 
478  if (m_bytes[1] == 'N') {
479  // This packet was not compressed -- delete the 'N' character at the start
480  // and the packet may be processed as-is.
481  m_bytes.erase(1, 1);
482  return true;
483  }
484 
485  // Reverse the gdb-remote binary escaping that was done to the compressed
486  // text to guard characters like '$', '#', '}', etc.
487  std::vector<uint8_t> unescaped_content;
488  unescaped_content.reserve(content_length);
489  size_t i = content_start;
490  while (i < hash_mark_idx) {
491  if (m_bytes[i] == '}') {
492  i++;
493  unescaped_content.push_back(m_bytes[i] ^ 0x20);
494  } else {
495  unescaped_content.push_back(m_bytes[i]);
496  }
497  i++;
498  }
499 
500  uint8_t *decompressed_buffer = nullptr;
501  size_t decompressed_bytes = 0;
502 
503  if (decompressed_bufsize != ULONG_MAX) {
504  decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
505  if (decompressed_buffer == nullptr) {
506  m_bytes.erase(0, size_of_first_packet);
507  return false;
508  }
509  }
510 
511 #if defined(HAVE_LIBCOMPRESSION)
516  compression_algorithm compression_type;
518  compression_type = COMPRESSION_LZFSE;
520  compression_type = COMPRESSION_ZLIB;
522  compression_type = COMPRESSION_LZ4_RAW;
524  compression_type = COMPRESSION_LZMA;
525 
526  if (m_decompression_scratch_type != m_compression_type) {
527  if (m_decompression_scratch) {
528  free (m_decompression_scratch);
529  m_decompression_scratch = nullptr;
530  }
531  size_t scratchbuf_size = 0;
533  scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
535  scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
537  scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
539  scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZMA);
541  scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
542  if (scratchbuf_size > 0) {
543  m_decompression_scratch = (void*) malloc (scratchbuf_size);
544  m_decompression_scratch_type = m_compression_type;
545  }
546  }
547 
548  if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
549  decompressed_bytes = compression_decode_buffer(
550  decompressed_buffer, decompressed_bufsize,
551  (uint8_t *)unescaped_content.data(), unescaped_content.size(),
552  m_decompression_scratch, compression_type);
553  }
554  }
555 #endif
556 
557 #if LLVM_ENABLE_ZLIB
558  if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
559  decompressed_buffer != nullptr &&
561  z_stream stream;
562  memset(&stream, 0, sizeof(z_stream));
563  stream.next_in = (Bytef *)unescaped_content.data();
564  stream.avail_in = (uInt)unescaped_content.size();
565  stream.total_in = 0;
566  stream.next_out = (Bytef *)decompressed_buffer;
567  stream.avail_out = decompressed_bufsize;
568  stream.total_out = 0;
569  stream.zalloc = Z_NULL;
570  stream.zfree = Z_NULL;
571  stream.opaque = Z_NULL;
572 
573  if (inflateInit2(&stream, -15) == Z_OK) {
574  int status = inflate(&stream, Z_NO_FLUSH);
575  inflateEnd(&stream);
576  if (status == Z_STREAM_END) {
577  decompressed_bytes = stream.total_out;
578  }
579  }
580  }
581 #endif
582 
583  if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
584  if (decompressed_buffer)
585  free(decompressed_buffer);
586  m_bytes.erase(0, size_of_first_packet);
587  return false;
588  }
589 
590  std::string new_packet;
591  new_packet.reserve(decompressed_bytes + 6);
592  new_packet.push_back(m_bytes[0]);
593  new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
594  new_packet.push_back('#');
595  if (GetSendAcks()) {
596  uint8_t decompressed_checksum = CalculcateChecksum(
597  llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
598  char decompressed_checksum_str[3];
599  snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
600  new_packet.append(decompressed_checksum_str);
601  } else {
602  new_packet.push_back('0');
603  new_packet.push_back('0');
604  }
605 
606  m_bytes.replace(0, size_of_first_packet, new_packet.data(),
607  new_packet.size());
608 
609  free(decompressed_buffer);
610  return true;
611 }
612 
614 GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
615  StringExtractorGDBRemote &packet) {
616  // Put the packet data into the buffer in a thread safe fashion
617  std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
618 
619  Log *log = GetLog(GDBRLog::Packets);
620 
621  if (src && src_len > 0) {
622  if (log && log->GetVerbose()) {
623  StreamString s;
624  LLDB_LOGF(log, "GDBRemoteCommunication::%s adding %u bytes: %.*s",
625  __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
626  }
627  m_bytes.append((const char *)src, src_len);
628  }
629 
630  bool isNotifyPacket = false;
631 
632  // Parse up the packets into gdb remote packets
633  if (!m_bytes.empty()) {
634  // end_idx must be one past the last valid packet byte. Start it off with
635  // an invalid value that is the same as the current index.
636  size_t content_start = 0;
637  size_t content_length = 0;
638  size_t total_length = 0;
639  size_t checksum_idx = std::string::npos;
640 
641  // Size of packet before it is decompressed, for logging purposes
642  size_t original_packet_size = m_bytes.size();
643  if (CompressionIsEnabled()) {
644  if (!DecompressPacket()) {
645  packet.Clear();
647  }
648  }
649 
650  switch (m_bytes[0]) {
651  case '+': // Look for ack
652  case '-': // Look for cancel
653  case '\x03': // ^C to halt target
654  content_length = total_length = 1; // The command is one byte long...
655  break;
656 
657  case '%': // Async notify packet
658  isNotifyPacket = true;
659  LLVM_FALLTHROUGH;
660 
661  case '$':
662  // Look for a standard gdb packet?
663  {
664  size_t hash_pos = m_bytes.find('#');
665  if (hash_pos != std::string::npos) {
666  if (hash_pos + 2 < m_bytes.size()) {
667  checksum_idx = hash_pos + 1;
668  // Skip the dollar sign
669  content_start = 1;
670  // Don't include the # in the content or the $ in the content
671  // length
672  content_length = hash_pos - 1;
673 
674  total_length =
675  hash_pos + 3; // Skip the # and the two hex checksum bytes
676  } else {
677  // Checksum bytes aren't all here yet
678  content_length = std::string::npos;
679  }
680  }
681  }
682  break;
683 
684  default: {
685  // We have an unexpected byte and we need to flush all bad data that is
686  // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
687  // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
688  // header) or of course, the end of the data in m_bytes...
689  const size_t bytes_len = m_bytes.size();
690  bool done = false;
691  uint32_t idx;
692  for (idx = 1; !done && idx < bytes_len; ++idx) {
693  switch (m_bytes[idx]) {
694  case '+':
695  case '-':
696  case '\x03':
697  case '%':
698  case '$':
699  done = true;
700  break;
701 
702  default:
703  break;
704  }
705  }
706  LLDB_LOGF(log, "GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
707  __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
708  m_bytes.erase(0, idx - 1);
709  } break;
710  }
711 
712  if (content_length == std::string::npos) {
713  packet.Clear();
715  } else if (total_length > 0) {
716 
717  // We have a valid packet...
718  assert(content_length <= m_bytes.size());
719  assert(total_length <= m_bytes.size());
720  assert(content_length <= total_length);
721  size_t content_end = content_start + content_length;
722 
723  bool success = true;
724  if (log) {
725  // If logging was just enabled and we have history, then dump out what
726  // we have to the log so we get the historical context. The Dump() call
727  // that logs all of the packet will set a boolean so that we don't dump
728  // this more than once
729  if (!m_history.DidDumpToLog())
730  m_history.Dump(log);
731 
732  bool binary = false;
733  // Only detect binary for packets that start with a '$' and have a
734  // '#CC' checksum
735  if (m_bytes[0] == '$' && total_length > 4) {
736  for (size_t i = 0; !binary && i < total_length; ++i) {
737  unsigned char c = m_bytes[i];
738  if (!llvm::isPrint(c) && !llvm::isSpace(c)) {
739  binary = true;
740  }
741  }
742  }
743  if (binary) {
744  StreamString strm;
745  // Packet header...
746  if (CompressionIsEnabled())
747  strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
748  (uint64_t)original_packet_size, (uint64_t)total_length,
749  m_bytes[0]);
750  else
751  strm.Printf("<%4" PRIu64 "> read packet: %c",
752  (uint64_t)total_length, m_bytes[0]);
753  for (size_t i = content_start; i < content_end; ++i) {
754  // Remove binary escaped bytes when displaying the packet...
755  const char ch = m_bytes[i];
756  if (ch == 0x7d) {
757  // 0x7d is the escape character. The next character is to be
758  // XOR'd with 0x20.
759  const char escapee = m_bytes[++i] ^ 0x20;
760  strm.Printf("%2.2x", escapee);
761  } else {
762  strm.Printf("%2.2x", (uint8_t)ch);
763  }
764  }
765  // Packet footer...
766  strm.Printf("%c%c%c", m_bytes[total_length - 3],
767  m_bytes[total_length - 2], m_bytes[total_length - 1]);
768  log->PutString(strm.GetString());
769  } else {
770  if (CompressionIsEnabled())
771  LLDB_LOGF(log, "<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
772  (uint64_t)original_packet_size, (uint64_t)total_length,
773  (int)(total_length), m_bytes.c_str());
774  else
775  LLDB_LOGF(log, "<%4" PRIu64 "> read packet: %.*s",
776  (uint64_t)total_length, (int)(total_length),
777  m_bytes.c_str());
778  }
779  }
780 
781  m_history.AddPacket(m_bytes, total_length,
782  GDBRemotePacket::ePacketTypeRecv, total_length);
783 
784  // Copy the packet from m_bytes to packet_str expanding the run-length
785  // encoding in the process.
786  std ::string packet_str =
787  ExpandRLE(m_bytes.substr(content_start, content_end - content_start));
788  packet = StringExtractorGDBRemote(packet_str);
789 
790  if (m_bytes[0] == '$' || m_bytes[0] == '%') {
791  assert(checksum_idx < m_bytes.size());
792  if (::isxdigit(m_bytes[checksum_idx + 0]) ||
793  ::isxdigit(m_bytes[checksum_idx + 1])) {
794  if (GetSendAcks()) {
795  const char *packet_checksum_cstr = &m_bytes[checksum_idx];
796  char packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
797  char actual_checksum = CalculcateChecksum(
798  llvm::StringRef(m_bytes).slice(content_start, content_end));
799  success = packet_checksum == actual_checksum;
800  if (!success) {
801  LLDB_LOGF(log,
802  "error: checksum mismatch: %.*s expected 0x%2.2x, "
803  "got 0x%2.2x",
804  (int)(total_length), m_bytes.c_str(),
805  (uint8_t)packet_checksum, (uint8_t)actual_checksum);
806  }
807  // Send the ack or nack if needed
808  if (!success)
809  SendNack();
810  else
811  SendAck();
812  }
813  } else {
814  success = false;
815  LLDB_LOGF(log, "error: invalid checksum in packet: '%s'\n",
816  m_bytes.c_str());
817  }
818  }
819 
820  m_bytes.erase(0, total_length);
821  packet.SetFilePos(0);
822 
823  if (isNotifyPacket)
825  else
827  }
828  }
829  packet.Clear();
831 }
832 
834  uint16_t port) {
836  return Status("listen thread already running");
837 
838  char listen_url[512];
839  if (hostname && hostname[0])
840  snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
841  else
842  snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
843  m_listen_url = listen_url;
844  SetConnection(std::make_unique<ConnectionFileDescriptor>());
845  llvm::Expected<HostThread> listen_thread = ThreadLauncher::LaunchThread(
846  listen_url, [this] { return GDBRemoteCommunication::ListenThread(); });
847  if (!listen_thread)
848  return Status(listen_thread.takeError());
849  m_listen_thread = *listen_thread;
850 
851  return Status();
852 }
853 
856  m_listen_thread.Join(nullptr);
857  return true;
858 }
859 
861  Status error;
862  ConnectionFileDescriptor *connection =
864 
865  if (connection) {
866  // Do the listen on another thread so we can continue on...
867  if (connection->Connect(
868  m_listen_url.c_str(),
869  [this](llvm::StringRef port_str) {
870  uint16_t port = 0;
871  llvm::to_integer(port_str, port, 10);
872  m_port_promise.set_value(port);
873  },
875  SetConnection(nullptr);
876  }
877  return {};
878 }
879 
881  const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
882  uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
883  Log *log = GetLog(GDBRLog::Process);
884  LLDB_LOGF(log, "GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
885  __FUNCTION__, url ? url : "<empty>", port ? *port : uint16_t(0));
886 
887  Status error;
888  // If we locate debugserver, keep that located version around
889  static FileSpec g_debugserver_file_spec;
890 
891  char debugserver_path[PATH_MAX];
892  FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
893 
894  Environment host_env = Host::GetEnvironment();
895 
896  // Always check to see if we have an environment override for the path to the
897  // debugserver to use and use it if we do.
898  std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
899  if (!env_debugserver_path.empty()) {
900  debugserver_file_spec.SetFile(env_debugserver_path,
901  FileSpec::Style::native);
902  LLDB_LOGF(log,
903  "GDBRemoteCommunication::%s() gdb-remote stub exe path set "
904  "from environment variable: %s",
905  __FUNCTION__, env_debugserver_path.c_str());
906  } else
907  debugserver_file_spec = g_debugserver_file_spec;
908  bool debugserver_exists =
909  FileSystem::Instance().Exists(debugserver_file_spec);
910  if (!debugserver_exists) {
911  // The debugserver binary is in the LLDB.framework/Resources directory.
912  debugserver_file_spec = HostInfo::GetSupportExeDir();
913  if (debugserver_file_spec) {
914  debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
915  debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
916  if (debugserver_exists) {
917  LLDB_LOGF(log,
918  "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
919  __FUNCTION__, debugserver_file_spec.GetPath().c_str());
920 
921  g_debugserver_file_spec = debugserver_file_spec;
922  } else {
923  if (platform)
924  debugserver_file_spec =
926  else
927  debugserver_file_spec.Clear();
928  if (debugserver_file_spec) {
929  // Platform::LocateExecutable() wouldn't return a path if it doesn't
930  // exist
931  debugserver_exists = true;
932  } else {
933  LLDB_LOGF(log,
934  "GDBRemoteCommunication::%s() could not find "
935  "gdb-remote stub exe '%s'",
936  __FUNCTION__, debugserver_file_spec.GetPath().c_str());
937  }
938  // Don't cache the platform specific GDB server binary as it could
939  // change from platform to platform
940  g_debugserver_file_spec.Clear();
941  }
942  }
943  }
944 
945  if (debugserver_exists) {
946  debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
947 
948  Args &debugserver_args = launch_info.GetArguments();
949  debugserver_args.Clear();
950 
951  // Start args with "debugserver /file/path -r --"
952  debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
953 
954 #if !defined(__APPLE__)
955  // First argument to lldb-server must be mode in which to run.
956  debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
957 #endif
958 
959  // If a url is supplied then use it
960  if (url)
961  debugserver_args.AppendArgument(llvm::StringRef(url));
962 
963  if (pass_comm_fd >= 0) {
964  StreamString fd_arg;
965  fd_arg.Printf("--fd=%i", pass_comm_fd);
966  debugserver_args.AppendArgument(fd_arg.GetString());
967  // Send "pass_comm_fd" down to the inferior so it can use it to
968  // communicate back with this process
969  launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
970  }
971 
972  // use native registers, not the GDB registers
973  debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
974 
975  if (launch_info.GetLaunchInSeparateProcessGroup()) {
976  debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
977  }
978 
979  llvm::SmallString<128> named_pipe_path;
980  // socket_pipe is used by debug server to communicate back either
981  // TCP port or domain socket name which it listens on.
982  // The second purpose of the pipe to serve as a synchronization point -
983  // once data is written to the pipe, debug server is up and running.
984  Pipe socket_pipe;
985 
986  // port is null when debug server should listen on domain socket - we're
987  // not interested in port value but rather waiting for debug server to
988  // become available.
989  if (pass_comm_fd == -1) {
990  if (url) {
991 // Create a temporary file to get the stdout/stderr and redirect the output of
992 // the command into this file. We will later read this file if all goes well
993 // and fill the data into "command_output_ptr"
994 #if defined(__APPLE__)
995  // Binding to port zero, we need to figure out what port it ends up
996  // using using a named pipe...
997  error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
998  false, named_pipe_path);
999  if (error.Fail()) {
1000  LLDB_LOGF(log,
1001  "GDBRemoteCommunication::%s() "
1002  "named pipe creation failed: %s",
1003  __FUNCTION__, error.AsCString());
1004  return error;
1005  }
1006  debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
1007  debugserver_args.AppendArgument(named_pipe_path);
1008 #else
1009  // Binding to port zero, we need to figure out what port it ends up
1010  // using using an unnamed pipe...
1011  error = socket_pipe.CreateNew(true);
1012  if (error.Fail()) {
1013  LLDB_LOGF(log,
1014  "GDBRemoteCommunication::%s() "
1015  "unnamed pipe creation failed: %s",
1016  __FUNCTION__, error.AsCString());
1017  return error;
1018  }
1019  pipe_t write = socket_pipe.GetWritePipe();
1020  debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1021  debugserver_args.AppendArgument(llvm::to_string(write));
1022  launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
1023 #endif
1024  } else {
1025  // No host and port given, so lets listen on our end and make the
1026  // debugserver connect to us..
1027  error = StartListenThread("127.0.0.1", 0);
1028  if (error.Fail()) {
1029  LLDB_LOGF(log,
1030  "GDBRemoteCommunication::%s() unable to start listen "
1031  "thread: %s",
1032  __FUNCTION__, error.AsCString());
1033  return error;
1034  }
1035 
1036  // Wait for 10 seconds to resolve the bound port
1037  std::future<uint16_t> port_future = m_port_promise.get_future();
1038  uint16_t port_ = port_future.wait_for(std::chrono::seconds(10)) ==
1039  std::future_status::ready
1040  ? port_future.get()
1041  : 0;
1042  if (port_ > 0) {
1043  char port_cstr[32];
1044  snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1045  // Send the host and port down that debugserver and specify an option
1046  // so that it connects back to the port we are listening to in this
1047  // process
1048  debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1049  debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
1050  if (port)
1051  *port = port_;
1052  } else {
1053  error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1054  LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s",
1055  __FUNCTION__, error.AsCString());
1056  return error;
1057  }
1058  }
1059  }
1060  std::string env_debugserver_log_file =
1061  host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
1062  if (!env_debugserver_log_file.empty()) {
1063  debugserver_args.AppendArgument(
1064  llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
1065  }
1066 
1067 #if defined(__APPLE__)
1068  const char *env_debugserver_log_flags =
1069  getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1070  if (env_debugserver_log_flags) {
1071  debugserver_args.AppendArgument(
1072  llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
1073  }
1074 #else
1075  std::string env_debugserver_log_channels =
1076  host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
1077  if (!env_debugserver_log_channels.empty()) {
1078  debugserver_args.AppendArgument(
1079  llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
1080  .str());
1081  }
1082 #endif
1083 
1084  // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1085  // env var doesn't come back.
1086  uint32_t env_var_index = 1;
1087  bool has_env_var;
1088  do {
1089  char env_var_name[64];
1090  snprintf(env_var_name, sizeof(env_var_name),
1091  "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1092  std::string extra_arg = host_env.lookup(env_var_name);
1093  has_env_var = !extra_arg.empty();
1094 
1095  if (has_env_var) {
1096  debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
1097  LLDB_LOGF(log,
1098  "GDBRemoteCommunication::%s adding env var %s contents "
1099  "to stub command line (%s)",
1100  __FUNCTION__, env_var_name, extra_arg.c_str());
1101  }
1102  } while (has_env_var);
1103 
1104  if (inferior_args && inferior_args->GetArgumentCount() > 0) {
1105  debugserver_args.AppendArgument(llvm::StringRef("--"));
1106  debugserver_args.AppendArguments(*inferior_args);
1107  }
1108 
1109  // Copy the current environment to the gdbserver/debugserver instance
1110  launch_info.GetEnvironment() = host_env;
1111 
1112  // Close STDIN, STDOUT and STDERR.
1113  launch_info.AppendCloseFileAction(STDIN_FILENO);
1114  launch_info.AppendCloseFileAction(STDOUT_FILENO);
1115  launch_info.AppendCloseFileAction(STDERR_FILENO);
1116 
1117  // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1118  launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1119  launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1120  launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1121 
1122  if (log) {
1123  StreamString string_stream;
1124  Platform *const platform = nullptr;
1125  launch_info.Dump(string_stream, platform);
1126  LLDB_LOGF(log, "launch info for gdb-remote stub:\n%s",
1127  string_stream.GetData());
1128  }
1129  error = Host::LaunchProcess(launch_info);
1130 
1131  if (error.Success() &&
1132  (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1133  pass_comm_fd == -1) {
1134  if (named_pipe_path.size() > 0) {
1135  error = socket_pipe.OpenAsReader(named_pipe_path, false);
1136  if (error.Fail())
1137  LLDB_LOGF(log,
1138  "GDBRemoteCommunication::%s() "
1139  "failed to open named pipe %s for reading: %s",
1140  __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1141  }
1142 
1143  if (socket_pipe.CanWrite())
1144  socket_pipe.CloseWriteFileDescriptor();
1145  if (socket_pipe.CanRead()) {
1146  char port_cstr[PATH_MAX] = {0};
1147  port_cstr[0] = '\0';
1148  size_t num_bytes = sizeof(port_cstr);
1149  // Read port from pipe with 10 second timeout.
1150  error = socket_pipe.ReadWithTimeout(
1151  port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1152  if (error.Success() && (port != nullptr)) {
1153  assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
1154  uint16_t child_port = 0;
1155  // FIXME: improve error handling
1156  llvm::to_integer(port_cstr, child_port);
1157  if (*port == 0 || *port == child_port) {
1158  *port = child_port;
1159  LLDB_LOGF(log,
1160  "GDBRemoteCommunication::%s() "
1161  "debugserver listens %u port",
1162  __FUNCTION__, *port);
1163  } else {
1164  LLDB_LOGF(log,
1165  "GDBRemoteCommunication::%s() "
1166  "debugserver listening on port "
1167  "%d but requested port was %d",
1168  __FUNCTION__, (uint32_t)child_port, (uint32_t)(*port));
1169  }
1170  } else {
1171  LLDB_LOGF(log,
1172  "GDBRemoteCommunication::%s() "
1173  "failed to read a port value from pipe %s: %s",
1174  __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1175  }
1176  socket_pipe.Close();
1177  }
1178 
1179  if (named_pipe_path.size() > 0) {
1180  const auto err = socket_pipe.Delete(named_pipe_path);
1181  if (err.Fail()) {
1182  LLDB_LOGF(log,
1183  "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1184  __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
1185  }
1186  }
1187 
1188  // Make sure we actually connect with the debugserver...
1189  JoinListenThread();
1190  }
1191  } else {
1192  error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1193  }
1194 
1195  if (error.Fail()) {
1196  LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1197  error.AsCString());
1198  }
1199 
1200  return error;
1201 }
1202 
1204 
1206  repro::PacketRecorder *recorder) {
1207  m_history.SetRecorder(recorder);
1208 }
1209 
1212  GDBRemoteCommunication &server) {
1213  const bool child_processes_inherit = false;
1214  const int backlog = 5;
1215  TCPSocket listen_socket(true, child_processes_inherit);
1216  if (llvm::Error error =
1217  listen_socket.Listen("localhost:0", backlog).ToError())
1218  return error;
1219 
1220  Socket *accept_socket;
1221  std::future<Status> accept_status = std::async(
1222  std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1223 
1224  llvm::SmallString<32> remote_addr;
1225  llvm::raw_svector_ostream(remote_addr)
1226  << "connect://localhost:" << listen_socket.GetLocalPortNumber();
1227 
1228  std::unique_ptr<ConnectionFileDescriptor> conn_up(
1229  new ConnectionFileDescriptor());
1230  Status status;
1231  if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)
1232  return llvm::createStringError(llvm::inconvertibleErrorCode(),
1233  "Unable to connect: %s", status.AsCString());
1234 
1235  client.SetConnection(std::move(conn_up));
1236  if (llvm::Error error = accept_status.get().ToError())
1237  return error;
1238 
1239  server.SetConnection(
1240  std::make_unique<ConnectionFileDescriptor>(accept_socket));
1241  return llvm::Error::success();
1242 }
1243 
1245  GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
1246  : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1247  auto curr_timeout = gdb_comm.GetPacketTimeout();
1248  // Only update the timeout if the timeout is greater than the current
1249  // timeout. If the current timeout is larger, then just use that.
1250  if (curr_timeout < timeout) {
1251  m_timeout_modified = true;
1253  }
1254 }
1255 
1257  // Only restore the timeout if we set it in the constructor.
1258  if (m_timeout_modified)
1259  m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1260 }
1261 
1262 void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1263  const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1264  StringRef Style) {
1266 
1267  switch (result) {
1268  case PacketResult::Success:
1269  Stream << "Success";
1270  break;
1272  Stream << "ErrorSendFailed";
1273  break;
1275  Stream << "ErrorSendAck";
1276  break;
1278  Stream << "ErrorReplyFailed";
1279  break;
1281  Stream << "ErrorReplyTimeout";
1282  break;
1284  Stream << "ErrorReplyInvalid";
1285  break;
1287  Stream << "ErrorReplyAck";
1288  break;
1290  Stream << "ErrorDisconnected";
1291  break;
1293  Stream << "ErrorNoSequenceLock";
1294  break;
1295  }
1296 }
1297 
1299  // Reserve enough byte for the most common case (no RLE used).
1300  std::string decoded;
1301  decoded.reserve(packet.size());
1302  for (std::string::const_iterator c = packet.begin(); c != packet.end(); ++c) {
1303  if (*c == '*') {
1304  // '*' indicates RLE. Next character will give us the repeat count and
1305  // previous character is what is to be repeated.
1306  char char_to_repeat = decoded.back();
1307  // Number of time the previous character is repeated.
1308  int repeat_count = *++c + 3 - ' ';
1309  // We have the char_to_repeat and repeat_count. Now push it in the
1310  // packet.
1311  for (int i = 0; i < repeat_count; ++i)
1312  decoded.push_back(char_to_repeat);
1313  } else if (*c == 0x7d) {
1314  // 0x7d is the escape character. The next character is to be XOR'd with
1315  // 0x20.
1316  char escapee = *++c ^ 0x20;
1317  decoded.push_back(escapee);
1318  } else {
1319  decoded.push_back(*c);
1320  }
1321  }
1322  return decoded;
1323 }
RegularExpression.h
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketType::Notify
@ Notify
lldb_private::process_gdb_remote::GDBRemoteCommunication::~GDBRemoteCommunication
~GDBRemoteCommunication() override
Definition: GDBRemoteCommunication.cpp:75
lldb_private::ProcessInfo::GetArguments
Args & GetArguments()
Definition: ProcessInfo.h:75
lldb_private::process_gdb_remote::CompressionType
CompressionType
Definition: GDBRemoteCommunication.h:45
StringExtractor::PeekChar
char PeekChar(char fail_value='\0')
Definition: StringExtractor.h:60
lldb_private::ProcessLaunchInfo::AppendDuplicateFileAction
bool AppendDuplicateFileAction(int fd, int dup_fd)
Definition: ProcessLaunchInfo.cpp:80
lldb_private::Pipe
PipePosix Pipe
Definition: Pipe.h:20
lldb_private::Log::PutString
void PutString(llvm::StringRef str)
Definition: Log.cpp:118
lldb_private::RegularExpression
Definition: RegularExpression.h:18
lldb_private::Host::LaunchProcess
static Status LaunchProcess(ProcessLaunchInfo &launch_info)
Launch the process specified in launch_info.
Definition: common/Host.cpp:547
FileSystem.h
x20
@ x20
Definition: CompactUnwindInfo.cpp:1238
lldb_private::Log::GetVerbose
bool GetVerbose() const
Definition: Log.cpp:268
lldb_private::TCPSocket::Accept
Status Accept(Socket *&conn_socket) override
Definition: TCPSocket.cpp:251
lldb_private::ThreadLauncher::LaunchThread
static llvm::Expected< HostThread > LaunchThread(llvm::StringRef name, std::function< lldb::thread_result_t()> thread_function, size_t min_stack_byte_size=0)
Definition: ThreadLauncher.cpp:25
LLDB_INVALID_PROCESS_ID
#define LLDB_INVALID_PROCESS_ID
Definition: lldb-defines.h:81
lldb_private::process_gdb_remote::GDBRemoteCommunication::CalculcateChecksum
char CalculcateChecksum(llvm::StringRef payload)
Definition: GDBRemoteCommunication.cpp:86
lldb_private::process_gdb_remote::GDBRemoteCommunication::SetPacketTimeout
std::chrono::seconds SetPacketTimeout(std::chrono::seconds packet_timeout)
Definition: GDBRemoteCommunication.h:145
StringExtractor::SetFilePos
void SetFilePos(uint32_t idx)
Definition: StringExtractor.h:39
lldb_private::process_gdb_remote::GDBRemoteCommunication::SendAck
size_t SendAck()
Definition: GDBRemoteCommunication.cpp:95
Host.h
StringExtractorGDBRemote::ResponseType
ResponseType
Definition: StringExtractorGDBRemote.h:181
StringExtractor::GetStringRef
llvm::StringRef GetStringRef() const
Definition: StringExtractor.h:48
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketResult
PacketResult
Definition: GDBRemoteCommunication.h:91
ProcessLaunchInfo.h
lldb_private::process_gdb_remote::GDBRemoteCommunication::DecompressPacket
bool DecompressPacket()
Definition: GDBRemoteCommunication.cpp:384
lldb_private::Communication::ConnectionStatusAsString
static std::string ConnectionStatusAsString(lldb::ConnectionStatus status)
Definition: Communication.cpp:424
lldb_private::Socket
Definition: Socket.h:41
lldb_private::eLazyBoolYes
@ eLazyBoolYes
Definition: lldb-private-enumerations.h:115
LLDB_LOGF
#define LLDB_LOGF(log,...)
Definition: Log.h:270
lldb_private::Args::AppendArguments
void AppendArguments(const Args &rhs)
Definition: Args.cpp:293
lldb_private::process_gdb_remote::GDBRemoteCommunication::m_listen_thread
HostThread m_listen_thread
Definition: GDBRemoteCommunication.h:227
lldb_private::Args::AppendArgument
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:318
lldb_private::process_gdb_remote::GDBRemoteCommunication::CompressionIsEnabled
bool CompressionIsEnabled()
Definition: GDBRemoteCommunication.h:201
lldb_private::process_gdb_remote::GDBRemoteCommunication
Definition: GDBRemoteCommunication.h:83
lldb_private::Args::Clear
void Clear()
Clear the arguments.
Definition: Args.cpp:374
lldb_private::process_gdb_remote::GDBRemoteCommunication::ScopedTimeout::m_saved_timeout
std::chrono::seconds m_saved_timeout
Definition: GDBRemoteCommunication.h:116
Reproducer.h
lldb_private::ProcessInfo::GetProcessID
lldb::pid_t GetProcessID() const
Definition: ProcessInfo.h:67
lldb_private::FileSystem::Exists
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
Definition: common/FileSystem.cpp:150
lldb_private::Stream
Definition: Stream.h:28
lldb_private::Args
Definition: Args.h:33
lldb_private::process_gdb_remote::GDBRemoteCommunication::ListenThread
lldb::thread_result_t ListenThread()
Definition: GDBRemoteCommunication.cpp:860
lldb::pipe_t
int pipe_t
Definition: lldb-types.h:64
lldb::eConnectionStatusNoConnection
@ eConnectionStatusNoConnection
No connection.
Definition: lldb-enumerations.h:300
ThreadLauncher.h
lldb::eConnectionStatusEndOfFile
@ eConnectionStatusEndOfFile
End-of-file encountered.
Definition: lldb-enumerations.h:297
LLDB_LOGV
#define LLDB_LOGV(log,...)
Definition: Log.h:277
lldb_private::process_gdb_remote::GDBRemoteCommunication::WaitForPacketNoLock
PacketResult WaitForPacketNoLock(StringExtractorGDBRemote &response, Timeout< std::micro > timeout, bool sync_on_timeout)
Definition: GDBRemoteCommunication.cpp:238
lldb_private::StreamString::GetString
llvm::StringRef GetString() const
Definition: StreamString.cpp:51
lldb_private::process_gdb_remote::GDBRemoteCommunication::JoinListenThread
bool JoinListenThread()
Definition: GDBRemoteCommunication.cpp:854
lldb_private::ProcessLaunchInfo::AppendCloseFileAction
bool AppendCloseFileAction(int fd)
Definition: ProcessLaunchInfo.cpp:71
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketType::Invalid
@ Invalid
lldb_private::process_gdb_remote::GDBRemoteCommunication::DumpHistory
void DumpHistory(Stream &strm)
Definition: GDBRemoteCommunication.cpp:1203
lldb_private::Communication::SetConnection
void SetConnection(std::unique_ptr< Connection > connection)
Sets the connection that it to be used by this class.
Definition: Communication.cpp:417
lldb_private::Communication
Definition: Communication.h:84
lldb_private::process_gdb_remote::GDBRemoteCommunicationHistory::Dump
void Dump(Stream &strm) const
Definition: GDBRemoteCommunicationHistory.cpp:64
lldb_private::Communication::WriteAll
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.
Definition: Communication.cpp:190
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketResult::ErrorReplyInvalid
@ ErrorReplyInvalid
lldb_private::process_gdb_remote::GDBRemoteCommunication::SendRawPacketNoLock
PacketResult SendRawPacketNoLock(llvm::StringRef payload, bool skip_ack=false)
Definition: GDBRemoteCommunication.cpp:128
Platform.h
lldb_private::FileSpec
Definition: FileSpec.h:56
lldb_private::ProcessLaunchInfo::AppendSuppressFileAction
bool AppendSuppressFileAction(int fd, bool read, bool write)
Definition: ProcessLaunchInfo.cpp:99
lldb_private::process_gdb_remote::GDBRemoteCommunication::m_compression_type
CompressionType m_compression_type
Definition: GDBRemoteCommunication.h:183
error
static llvm::raw_ostream & error(Stream &strm)
Definition: CommandReturnObject.cpp:17
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketResult::ErrorReplyAck
@ ErrorReplyAck
else
else() list(APPEND LLVM_OPTIONAL_SOURCES $
Definition: Plugins/Platform/MacOSX/CMakeLists.txt:31
lldb_private::process_gdb_remote::GDBRemoteCommunication::StartDebugserverProcess
Status StartDebugserverProcess(const char *url, Platform *platform, ProcessLaunchInfo &launch_info, uint16_t *port, const Args *inferior_args, int pass_comm_fd)
Definition: GDBRemoteCommunication.cpp:880
lldb_private::ProcessLaunchInfo
Definition: ProcessLaunchInfo.h:31
Log.h
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketResult::ErrorNoSequenceLock
@ ErrorNoSequenceLock
lldb_private::process_gdb_remote::GDBRemoteCommunication::m_history
GDBRemoteCommunicationHistory m_history
Definition: GDBRemoteCommunication.h:177
lldb_private::process_gdb_remote::GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout
~ScopedTimeout()
Definition: GDBRemoteCommunication.cpp:1256
lldb_private::StreamString::GetData
const char * GetData() const
Definition: StreamString.h:43
lldb_private::process_gdb_remote::GDBRemoteCommunication::m_echo_number
uint32_t m_echo_number
Definition: GDBRemoteCommunication.h:175
Socket.h
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketResult::ErrorSendFailed
@ ErrorSendFailed
StreamString.h
lldb_private::process_gdb_remote::CompressionType::LZMA
@ LZMA
lldb_private::process_gdb_remote::GDBRemoteCommunication::m_supports_qEcho
LazyBool m_supports_qEcho
Definition: GDBRemoteCommunication.h:176
lldb_private::process_gdb_remote::GDBRemoteCommunication::ScopedTimeout::m_gdb_comm
GDBRemoteCommunication & m_gdb_comm
Definition: GDBRemoteCommunication.h:115
lldb_private::StreamString
Definition: StreamString.h:23
StringExtractorGDBRemote::GetResponseType
ResponseType GetResponseType() const
Definition: StringExtractorGDBRemote.cpp:18
lldb_private::process_gdb_remote::GDBRemoteCommunication::SetPacketRecorder
void SetPacketRecorder(repro::PacketRecorder *recorder)
Definition: GDBRemoteCommunication.cpp:1205
lldb::eConnectionStatusTimedOut
@ eConnectionStatusTimedOut
Request timed out.
Definition: lldb-enumerations.h:299
lldb::ConnectionStatus
ConnectionStatus
Connection Status Types.
Definition: lldb-enumerations.h:295
Pipe.h
lldb::eConnectionStatusInterrupted
@ eConnectionStatusInterrupted
Interrupted read.
Definition: lldb-enumerations.h:303
ConnectionFileDescriptor.h
HostInfo.h
lldb_private::process_gdb_remote::GDBRemoteCommunicationHistory::SetRecorder
void SetRecorder(repro::PacketRecorder *recorder)
Definition: GDBRemoteCommunicationHistory.h:48
StringExtractor::GetChar
char GetChar(char fail_value='\0')
Definition: StringExtractor.cpp:43
string
string(SUBSTRING ${p} 10 -1 pStripped) if($
Definition: Plugins/CMakeLists.txt:40
lldb_private::Stream::PutChar
size_t PutChar(char ch)
Definition: Stream.cpp:104
lldb_private::process_gdb_remote
Definition: GDBRemoteClientBase.h:17
lldb_private::process_gdb_remote::GDBRemoteCommunication::SendNack
size_t SendNack()
Definition: GDBRemoteCommunication.cpp:105
lldb_private::Platform::LocateExecutable
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:724
Event.h
lldb_private::ConnectionFileDescriptor::Connect
lldb::ConnectionStatus Connect(llvm::StringRef url, Status *error_ptr) override
Connect using the connect string url.
Definition: ConnectionFileDescriptorPosix.cpp:123
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketResult::Success
@ Success
lldb_private::process_gdb_remote::GDBRemoteCommunication::GetAck
PacketResult GetAck()
Definition: GDBRemoteCommunication.cpp:189
lldb_private::process_gdb_remote::GDBRemoteCommunicationHistory::AddPacket
void AddPacket(char packet_char, GDBRemotePacket::Type type, uint32_t bytes_transmitted)
Definition: GDBRemoteCommunicationHistory.cpp:29
lldb_private::Host::GetEnvironment
static Environment GetEnvironment()
Definition: freebsd/Host.cpp:244
lldb_private::FileSpec::Clear
void Clear()
Clears the object state.
Definition: FileSpec.cpp:259
DEBUGSERVER_BASENAME
#define DEBUGSERVER_BASENAME
Definition: GDBRemoteCommunication.cpp:45
StringExtractor::GetHexByteString
size_t GetHexByteString(std::string &str)
Definition: StringExtractor.cpp:298
StreamFile.h
lldb_private::process_gdb_remote::GDBRemoteCommunication::ScopedTimeout::ScopedTimeout
ScopedTimeout(GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
Definition: GDBRemoteCommunication.cpp:1244
lldb_private::GDBRemotePacket::ePacketTypeRecv
@ ePacketTypeRecv
Definition: GDBRemote.h:56
lldb_private::Communication::Disconnect
lldb::ConnectionStatus Disconnect(Status *error_ptr=nullptr)
Disconnect the communications connection if one is currently connected.
Definition: Communication.cpp:90
lldb_private::process_gdb_remote::GDBRemoteCommunication::ConnectLocally
static llvm::Error ConnectLocally(GDBRemoteCommunication &client, GDBRemoteCommunication &server)
Definition: GDBRemoteCommunication.cpp:1211
lldb_private::HostThread::Join
Status Join(lldb::thread_result_t *result)
Definition: HostThread.cpp:20
StringExtractor::Clear
void Clear()
Definition: StringExtractor.h:41
lldb_private::process_gdb_remote::GDBRemoteCommunication::ReadPacket
PacketResult ReadPacket(StringExtractorGDBRemote &response, Timeout< std::micro > timeout, bool sync_on_timeout)
Definition: GDBRemoteCommunication.cpp:220
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketType::Standard
@ Standard
lldb_private::Status
Definition: Status.h:44
lldb_private::GDBRemotePacket::ePacketTypeSend
@ ePacketTypeSend
Definition: GDBRemote.h:56
lldb_private::Timeout< std::micro >
lldb_private::Communication::Read
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.
Definition: Communication.cpp:123
lldb_private::process_gdb_remote::GDBRLog::Packets
@ Packets
uint32_t
lldb_private::process_gdb_remote::GDBRemoteCommunication::StartListenThread
Status StartListenThread(const char *hostname="127.0.0.1", uint16_t port=0)
Definition: GDBRemoteCommunication.cpp:833
lldb::thread_result_t
void * thread_result_t
Definition: lldb-types.h:62
lldb_private::ProcessInfo::GetEnvironment
Environment & GetEnvironment()
Definition: ProcessInfo.h:87
lldb_private::process_gdb_remote::GDBRemoteCommunication::m_listen_url
std::string m_listen_url
Definition: GDBRemoteCommunication.h:228
lldb::eConnectionStatusError
@ eConnectionStatusError
Check GetError() for details.
Definition: lldb-enumerations.h:298
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketType
PacketType
Definition: GDBRemoteCommunication.h:89
lldb_private::process_gdb_remote::CompressionType::None
@ None
lldb_private::process_gdb_remote::GDBRemoteCommunication::CheckForPacket
PacketType CheckForPacket(const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
Definition: GDBRemoteCommunication.cpp:614
lldb_private::process_gdb_remote::GDBRemoteCommunication::GetSendAcks
bool GetSendAcks()
Definition: GDBRemoteCommunication.h:138
lldb_private::process_gdb_remote::CompressionType::LZFSE
@ LZFSE
lldb_private::process_gdb_remote::GDBRemoteCommunication::ReadPacketWithOutputSupport
PacketResult ReadPacketWithOutputSupport(StringExtractorGDBRemote &response, Timeout< std::micro > timeout, bool sync_on_timeout, llvm::function_ref< void(llvm::StringRef)> output_callback)
Definition: GDBRemoteCommunication.cpp:203
lldb_private::Environment
Definition: Environment.h:18
lldb_private::process_gdb_remote::GDBRLog::Process
@ Process
lldb_private::process_gdb_remote::GDBRemoteCommunication::SendPacketNoLock
PacketResult SendPacketNoLock(llvm::StringRef payload)
Definition: GDBRemoteCommunication.cpp:116
lldb_private::process_gdb_remote::GDBRemoteCommunication::ScopedTimeout::m_timeout_modified
bool m_timeout_modified
Definition: GDBRemoteCommunication.h:120
lldb_private::Communication::IsConnected
bool IsConnected() const
Check if the connection is valid.
Definition: Communication.cpp:114
uint16_t
ProcessGDBRemoteLog.h
lldb_private::process_gdb_remote::CompressionType::ZlibDeflate
@ ZlibDeflate
TCPSocket.h
LLDB_LOG
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition: Log.h:263
lldb_private::Platform
Definition: Platform.h:71
lldb_private::Stream::Printf
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:107
lldb_private::repro::PacketRecorder
Definition: GDBRemote.h:85
lldb_private::FileSystem::Instance
static FileSystem & Instance()
Definition: common/FileSystem.cpp:46
lldb::eConnectionStatusSuccess
@ eConnectionStatusSuccess
Success.
Definition: lldb-enumerations.h:296
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketResult::ErrorDisconnected
@ ErrorDisconnected
GDBRemoteCommunication.h
lldb_private::FileSpec::AppendPathComponent
void AppendPathComponent(llvm::StringRef component)
Definition: FileSpec.cpp:434
lldb_private::TCPSocket
Definition: TCPSocket.h:17
lldb_private::HostThread::IsJoinable
bool IsJoinable() const
Definition: HostThread.cpp:30
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketResult::ErrorReplyTimeout
@ ErrorReplyTimeout
lldb_private
A class that represents a running process on the host machine.
Definition: SBCommandInterpreterRunOptions.h:16
lldb_private::eLazyBoolCalculate
@ eLazyBoolCalculate
Definition: lldb-private-enumerations.h:115
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketResult::ErrorReplyFailed
@ ErrorReplyFailed
Error
llvm::Error Error
Definition: UdtRecordCompleter.cpp:30
lldb_private::ProcessInfo::GetExecutableFile
FileSpec & GetExecutableFile()
Definition: ProcessInfo.h:42
ConnectionFileDescriptorPosix.h
FileSpec.h
lldb_private::RegularExpression::Execute
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...
Definition: RegularExpression.cpp:23
lldb::eByteOrderBig
@ eByteOrderBig
Definition: lldb-enumerations.h:140
lldb_private::Stream::Write
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
Definition: Stream.h:101
lldb_private::process_gdb_remote::GDBRemoteCommunication::m_port_promise
std::promise< uint16_t > m_port_promise
Definition: GDBRemoteCommunication.h:225
lldb_private::Status::ToError
llvm::Error ToError() const
Definition: Status.cpp:89
lldb::eConnectionStatusLostConnection
@ eConnectionStatusLostConnection
Lost connection while connected to a valid connection.
Definition: lldb-enumerations.h:301
lldb_private::process_gdb_remote::GDBRemoteCommunication::GetPacketTimeout
std::chrono::seconds GetPacketTimeout() const
Definition: GDBRemoteCommunication.h:151
StringExtractorGDBRemote
Definition: StringExtractorGDBRemote.h:21
lldb_private::Communication::GetConnection
lldb_private::Connection * GetConnection()
Definition: Communication.h:162
lldb_private::Log
Definition: Log.h:48
lldb_private::ProcessLaunchInfo::GetLaunchInSeparateProcessGroup
bool GetLaunchInSeparateProcessGroup() const
Definition: ProcessLaunchInfo.h:84
lldb_private::FileSpec::SetFile
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition: FileSpec.cpp:172
lldb_private::process_gdb_remote::GDBRemoteCommunicationHistory::DidDumpToLog
bool DidDumpToLog() const
Definition: GDBRemoteCommunicationHistory.h:46
PATH_MAX
#define PATH_MAX
Definition: windows/PosixApi.h:25
lldb_private::GetLog
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:235
lldb_private::FileSpec::GetPath
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition: FileSpec.cpp:347
lldb_private::process_gdb_remote::CompressionType::LZ4
@ LZ4
lldb_private::TCPSocket::GetLocalPortNumber
uint16_t GetLocalPortNumber() const
Definition: TCPSocket.cpp:81
lldb_private::ProcessInfo::Dump
void Dump(Stream &s, Platform *platform) const
Definition: ProcessInfo.cpp:50
lldb_private::Args::GetArgumentCount
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition: Args.h:118
lldb_private::ConnectionFileDescriptor
Definition: ConnectionFileDescriptorPosix.h:29
lldb
Definition: SBAddress.h:15
lldb_private::process_gdb_remote::GDBRemoteCommunication::ExpandRLE
static std::string ExpandRLE(std::string)
Expand GDB run-length encoding.
Definition: GDBRemoteCommunication.cpp:1298
lldb_private::Stream::PutHex8
size_t size_t PutHex8(uint8_t uvalue)
Append an uint8_t value in the hexadecimal format to the stream.
Definition: Stream.cpp:234
lldb_private::Communication::m_bytes
std::string m_bytes
A buffer to cache bytes read in the ReadThread function.
Definition: Communication.h:324
lldb_private::Communication::m_bytes_mutex
std::recursive_mutex m_bytes_mutex
A mutex to protect multi-threaded access to the cached bytes.
Definition: Communication.h:325
lldb_private::Status::AsCString
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:130
endif
LLDBWrapPython cpp endif() if(LLDB_ENABLE_LUA) get_target_property(lua_bindings_dir swig_wrapper_lua BINARY_DIR) set(lldb_lua_wrapper $
Definition: API/CMakeLists.txt:11
StringExtractorGDBRemote::IsNormalResponse
bool IsNormalResponse() const
Definition: StringExtractorGDBRemote.cpp:463
lldb_private::process_gdb_remote::GDBRemoteCommunication::PacketResult::ErrorSendAck
@ ErrorSendAck
lldb_private::TCPSocket::Listen
Status Listen(llvm::StringRef name, int backlog) override
Definition: TCPSocket.cpp:187