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