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