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