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