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