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); 408 } else { 409 echo_packet_len = 410 ::snprintf(echo_packet, sizeof(echo_packet), "qC"); 411 response_regex.Compile(llvm::StringRef("^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(echo_response.GetStringRef())) { 426 sync_success = true; 427 break; 428 } else if (successful_responses == 1) { 429 // We got something else back as the first successful 430 // response, it probably is 431 // the response to the packet we actually wanted, so copy it 432 // over if this 433 // is the first success and continue to try to get the qEcho 434 // response 435 packet = echo_response; 436 got_actual_response = true; 437 } 438 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout) 439 continue; // Packet timed out, continue waiting for a response 440 else 441 break; // Something else went wrong getting the packet back, we 442 // failed and are done trying 443 } 444 } 445 446 // We weren't able to sync back up with the server, we must abort 447 // otherwise 448 // all responses might not be from the right packets... 449 if (sync_success) { 450 // We timed out, but were able to recover 451 if (got_actual_response) { 452 // We initially timed out, but we did get a response that came in 453 // before the successful 454 // reply to our qEcho packet, so lets say everything is fine... 455 return PacketResult::Success; 456 } 457 } else { 458 disconnected = true; 459 Disconnect(); 460 } 461 } 462 timed_out = true; 463 break; 464 case eConnectionStatusSuccess: 465 // printf ("status = success but error = %s\n", 466 // error.AsCString("<invalid>")); 467 break; 468 469 case eConnectionStatusEndOfFile: 470 case eConnectionStatusNoConnection: 471 case eConnectionStatusLostConnection: 472 case eConnectionStatusError: 473 disconnected = true; 474 Disconnect(); 475 break; 476 } 477 } 478 } 479 packet.Clear(); 480 if (disconnected) 481 return PacketResult::ErrorDisconnected; 482 if (timed_out) 483 return PacketResult::ErrorReplyTimeout; 484 else 485 return PacketResult::ErrorReplyFailed; 486 } 487 488 bool GDBRemoteCommunication::DecompressPacket() { 489 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS)); 490 491 if (!CompressionIsEnabled()) 492 return true; 493 494 size_t pkt_size = m_bytes.size(); 495 496 // Smallest possible compressed packet is $N#00 - an uncompressed empty reply, 497 // most commonly indicating 498 // an unsupported packet. Anything less than 5 characters, it's definitely 499 // not a compressed packet. 500 if (pkt_size < 5) 501 return true; 502 503 if (m_bytes[0] != '$' && m_bytes[0] != '%') 504 return true; 505 if (m_bytes[1] != 'C' && m_bytes[1] != 'N') 506 return true; 507 508 size_t hash_mark_idx = m_bytes.find('#'); 509 if (hash_mark_idx == std::string::npos) 510 return true; 511 if (hash_mark_idx + 2 >= m_bytes.size()) 512 return true; 513 514 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) || 515 !::isxdigit(m_bytes[hash_mark_idx + 2])) 516 return true; 517 518 size_t content_length = 519 pkt_size - 520 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars 521 size_t content_start = 2; // The first character of the 522 // compressed/not-compressed text of the packet 523 size_t checksum_idx = 524 hash_mark_idx + 525 1; // The first character of the two hex checksum characters 526 527 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain 528 // multiple packets. 529 // size_of_first_packet is the size of the initial packet which we'll replace 530 // with the decompressed 531 // version of, leaving the rest of m_bytes unmodified. 532 size_t size_of_first_packet = hash_mark_idx + 3; 533 534 // Compressed packets ("$C") start with a base10 number which is the size of 535 // the uncompressed payload, 536 // then a : and then the compressed data. e.g. $C1024:<binary>#00 537 // Update content_start and content_length to only include the <binary> part 538 // of the packet. 539 540 uint64_t decompressed_bufsize = ULONG_MAX; 541 if (m_bytes[1] == 'C') { 542 size_t i = content_start; 543 while (i < hash_mark_idx && isdigit(m_bytes[i])) 544 i++; 545 if (i < hash_mark_idx && m_bytes[i] == ':') { 546 i++; 547 content_start = i; 548 content_length = hash_mark_idx - content_start; 549 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1); 550 errno = 0; 551 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), NULL, 10); 552 if (errno != 0 || decompressed_bufsize == ULONG_MAX) { 553 m_bytes.erase(0, size_of_first_packet); 554 return false; 555 } 556 } 557 } 558 559 if (GetSendAcks()) { 560 char packet_checksum_cstr[3]; 561 packet_checksum_cstr[0] = m_bytes[checksum_idx]; 562 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1]; 563 packet_checksum_cstr[2] = '\0'; 564 long packet_checksum = strtol(packet_checksum_cstr, NULL, 16); 565 566 long actual_checksum = CalculcateChecksum( 567 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1)); 568 bool success = packet_checksum == actual_checksum; 569 if (!success) { 570 if (log) 571 log->Printf( 572 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x", 573 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum, 574 (uint8_t)actual_checksum); 575 } 576 // Send the ack or nack if needed 577 if (!success) { 578 SendNack(); 579 m_bytes.erase(0, size_of_first_packet); 580 return false; 581 } else { 582 SendAck(); 583 } 584 } 585 586 if (m_bytes[1] == 'N') { 587 // This packet was not compressed -- delete the 'N' character at the 588 // start and the packet may be processed as-is. 589 m_bytes.erase(1, 1); 590 return true; 591 } 592 593 // Reverse the gdb-remote binary escaping that was done to the compressed text 594 // to 595 // guard characters like '$', '#', '}', etc. 596 std::vector<uint8_t> unescaped_content; 597 unescaped_content.reserve(content_length); 598 size_t i = content_start; 599 while (i < hash_mark_idx) { 600 if (m_bytes[i] == '}') { 601 i++; 602 unescaped_content.push_back(m_bytes[i] ^ 0x20); 603 } else { 604 unescaped_content.push_back(m_bytes[i]); 605 } 606 i++; 607 } 608 609 uint8_t *decompressed_buffer = nullptr; 610 size_t decompressed_bytes = 0; 611 612 if (decompressed_bufsize != ULONG_MAX) { 613 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize + 1); 614 if (decompressed_buffer == nullptr) { 615 m_bytes.erase(0, size_of_first_packet); 616 return false; 617 } 618 } 619 620 #if defined(HAVE_LIBCOMPRESSION) 621 // libcompression is weak linked so check that compression_decode_buffer() is 622 // available 623 if (compression_decode_buffer != NULL && 624 (m_compression_type == CompressionType::ZlibDeflate || 625 m_compression_type == CompressionType::LZFSE || 626 m_compression_type == CompressionType::LZ4)) { 627 compression_algorithm compression_type; 628 if (m_compression_type == CompressionType::ZlibDeflate) 629 compression_type = COMPRESSION_ZLIB; 630 else if (m_compression_type == CompressionType::LZFSE) 631 compression_type = COMPRESSION_LZFSE; 632 else if (m_compression_type == CompressionType::LZ4) 633 compression_type = COMPRESSION_LZ4_RAW; 634 else if (m_compression_type == CompressionType::LZMA) 635 compression_type = COMPRESSION_LZMA; 636 637 // If we have the expected size of the decompressed payload, we can allocate 638 // the right-sized buffer and do it. If we don't have that information, 639 // we'll 640 // need to try decoding into a big buffer and if the buffer wasn't big 641 // enough, 642 // increase it and try again. 643 644 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) { 645 decompressed_bytes = compression_decode_buffer( 646 decompressed_buffer, decompressed_bufsize + 10, 647 (uint8_t *)unescaped_content.data(), unescaped_content.size(), NULL, 648 compression_type); 649 } 650 } 651 #endif 652 653 #if defined(HAVE_LIBZ) 654 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX && 655 decompressed_buffer != nullptr && 656 m_compression_type == CompressionType::ZlibDeflate) { 657 z_stream stream; 658 memset(&stream, 0, sizeof(z_stream)); 659 stream.next_in = (Bytef *)unescaped_content.data(); 660 stream.avail_in = (uInt)unescaped_content.size(); 661 stream.total_in = 0; 662 stream.next_out = (Bytef *)decompressed_buffer; 663 stream.avail_out = decompressed_bufsize; 664 stream.total_out = 0; 665 stream.zalloc = Z_NULL; 666 stream.zfree = Z_NULL; 667 stream.opaque = Z_NULL; 668 669 if (inflateInit2(&stream, -15) == Z_OK) { 670 int status = inflate(&stream, Z_NO_FLUSH); 671 inflateEnd(&stream); 672 if (status == Z_STREAM_END) { 673 decompressed_bytes = stream.total_out; 674 } 675 } 676 } 677 #endif 678 679 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) { 680 if (decompressed_buffer) 681 free(decompressed_buffer); 682 m_bytes.erase(0, size_of_first_packet); 683 return false; 684 } 685 686 std::string new_packet; 687 new_packet.reserve(decompressed_bytes + 6); 688 new_packet.push_back(m_bytes[0]); 689 new_packet.append((const char *)decompressed_buffer, decompressed_bytes); 690 new_packet.push_back('#'); 691 if (GetSendAcks()) { 692 uint8_t decompressed_checksum = CalculcateChecksum( 693 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes)); 694 char decompressed_checksum_str[3]; 695 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum); 696 new_packet.append(decompressed_checksum_str); 697 } else { 698 new_packet.push_back('0'); 699 new_packet.push_back('0'); 700 } 701 702 m_bytes.replace(0, size_of_first_packet, new_packet.data(), 703 new_packet.size()); 704 705 free(decompressed_buffer); 706 return true; 707 } 708 709 GDBRemoteCommunication::PacketType 710 GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len, 711 StringExtractorGDBRemote &packet) { 712 // Put the packet data into the buffer in a thread safe fashion 713 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex); 714 715 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS)); 716 717 if (src && src_len > 0) { 718 if (log && log->GetVerbose()) { 719 StreamString s; 720 log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s", 721 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src); 722 } 723 m_bytes.append((const char *)src, src_len); 724 } 725 726 bool isNotifyPacket = false; 727 728 // Parse up the packets into gdb remote packets 729 if (!m_bytes.empty()) { 730 // end_idx must be one past the last valid packet byte. Start 731 // it off with an invalid value that is the same as the current 732 // index. 733 size_t content_start = 0; 734 size_t content_length = 0; 735 size_t total_length = 0; 736 size_t checksum_idx = std::string::npos; 737 738 // Size of packet before it is decompressed, for logging purposes 739 size_t original_packet_size = m_bytes.size(); 740 if (CompressionIsEnabled()) { 741 if (DecompressPacket() == false) { 742 packet.Clear(); 743 return GDBRemoteCommunication::PacketType::Standard; 744 } 745 } 746 747 switch (m_bytes[0]) { 748 case '+': // Look for ack 749 case '-': // Look for cancel 750 case '\x03': // ^C to halt target 751 content_length = total_length = 1; // The command is one byte long... 752 break; 753 754 case '%': // Async notify packet 755 isNotifyPacket = true; 756 LLVM_FALLTHROUGH; 757 758 case '$': 759 // Look for a standard gdb packet? 760 { 761 size_t hash_pos = m_bytes.find('#'); 762 if (hash_pos != std::string::npos) { 763 if (hash_pos + 2 < m_bytes.size()) { 764 checksum_idx = hash_pos + 1; 765 // Skip the dollar sign 766 content_start = 1; 767 // Don't include the # in the content or the $ in the content length 768 content_length = hash_pos - 1; 769 770 total_length = 771 hash_pos + 3; // Skip the # and the two hex checksum bytes 772 } else { 773 // Checksum bytes aren't all here yet 774 content_length = std::string::npos; 775 } 776 } 777 } 778 break; 779 780 default: { 781 // We have an unexpected byte and we need to flush all bad 782 // data that is in m_bytes, so we need to find the first 783 // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt), 784 // or '$' character (start of packet header) or of course, 785 // the end of the data in m_bytes... 786 const size_t bytes_len = m_bytes.size(); 787 bool done = false; 788 uint32_t idx; 789 for (idx = 1; !done && idx < bytes_len; ++idx) { 790 switch (m_bytes[idx]) { 791 case '+': 792 case '-': 793 case '\x03': 794 case '%': 795 case '$': 796 done = true; 797 break; 798 799 default: 800 break; 801 } 802 } 803 if (log) 804 log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'", 805 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str()); 806 m_bytes.erase(0, idx - 1); 807 } break; 808 } 809 810 if (content_length == std::string::npos) { 811 packet.Clear(); 812 return GDBRemoteCommunication::PacketType::Invalid; 813 } else if (total_length > 0) { 814 815 // We have a valid packet... 816 assert(content_length <= m_bytes.size()); 817 assert(total_length <= m_bytes.size()); 818 assert(content_length <= total_length); 819 size_t content_end = content_start + content_length; 820 821 bool success = true; 822 std::string &packet_str = packet.GetStringRef(); 823 if (log) { 824 // If logging was just enabled and we have history, then dump out what 825 // we have to the log so we get the historical context. The Dump() call 826 // that 827 // logs all of the packet will set a boolean so that we don't dump this 828 // more 829 // than once 830 if (!m_history.DidDumpToLog()) 831 m_history.Dump(log); 832 833 bool binary = false; 834 // Only detect binary for packets that start with a '$' and have a '#CC' 835 // checksum 836 if (m_bytes[0] == '$' && total_length > 4) { 837 for (size_t i = 0; !binary && i < total_length; ++i) { 838 if (isprint(m_bytes[i]) == 0 && isspace(m_bytes[i]) == 0) { 839 binary = true; 840 } 841 } 842 } 843 if (binary) { 844 StreamString strm; 845 // Packet header... 846 if (CompressionIsEnabled()) 847 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c", 848 (uint64_t)original_packet_size, (uint64_t)total_length, 849 m_bytes[0]); 850 else 851 strm.Printf("<%4" PRIu64 "> read packet: %c", 852 (uint64_t)total_length, m_bytes[0]); 853 for (size_t i = content_start; i < content_end; ++i) { 854 // Remove binary escaped bytes when displaying the packet... 855 const char ch = m_bytes[i]; 856 if (ch == 0x7d) { 857 // 0x7d is the escape character. The next character is to 858 // be XOR'd with 0x20. 859 const char escapee = m_bytes[++i] ^ 0x20; 860 strm.Printf("%2.2x", escapee); 861 } else { 862 strm.Printf("%2.2x", (uint8_t)ch); 863 } 864 } 865 // Packet footer... 866 strm.Printf("%c%c%c", m_bytes[total_length - 3], 867 m_bytes[total_length - 2], m_bytes[total_length - 1]); 868 log->PutCString(strm.GetString().c_str()); 869 } else { 870 if (CompressionIsEnabled()) 871 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s", 872 (uint64_t)original_packet_size, (uint64_t)total_length, 873 (int)(total_length), m_bytes.c_str()); 874 else 875 log->Printf("<%4" PRIu64 "> read packet: %.*s", 876 (uint64_t)total_length, (int)(total_length), 877 m_bytes.c_str()); 878 } 879 } 880 881 m_history.AddPacket(m_bytes.c_str(), total_length, 882 History::ePacketTypeRecv, total_length); 883 884 // Clear packet_str in case there is some existing data in it. 885 packet_str.clear(); 886 // Copy the packet from m_bytes to packet_str expanding the 887 // run-length encoding in the process. 888 // Reserve enough byte for the most common case (no RLE used) 889 packet_str.reserve(m_bytes.length()); 890 for (std::string::const_iterator c = m_bytes.begin() + content_start; 891 c != m_bytes.begin() + content_end; ++c) { 892 if (*c == '*') { 893 // '*' indicates RLE. Next character will give us the 894 // repeat count and previous character is what is to be 895 // repeated. 896 char char_to_repeat = packet_str.back(); 897 // Number of time the previous character is repeated 898 int repeat_count = *++c + 3 - ' '; 899 // We have the char_to_repeat and repeat_count. Now push 900 // it in the packet. 901 for (int i = 0; i < repeat_count; ++i) 902 packet_str.push_back(char_to_repeat); 903 } else if (*c == 0x7d) { 904 // 0x7d is the escape character. The next character is to 905 // be XOR'd with 0x20. 906 char escapee = *++c ^ 0x20; 907 packet_str.push_back(escapee); 908 } else { 909 packet_str.push_back(*c); 910 } 911 } 912 913 if (m_bytes[0] == '$' || m_bytes[0] == '%') { 914 assert(checksum_idx < m_bytes.size()); 915 if (::isxdigit(m_bytes[checksum_idx + 0]) || 916 ::isxdigit(m_bytes[checksum_idx + 1])) { 917 if (GetSendAcks()) { 918 const char *packet_checksum_cstr = &m_bytes[checksum_idx]; 919 char packet_checksum = strtol(packet_checksum_cstr, NULL, 16); 920 char actual_checksum = CalculcateChecksum(packet_str); 921 success = packet_checksum == actual_checksum; 922 if (!success) { 923 if (log) 924 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, " 925 "got 0x%2.2x", 926 (int)(total_length), m_bytes.c_str(), 927 (uint8_t)packet_checksum, (uint8_t)actual_checksum); 928 } 929 // Send the ack or nack if needed 930 if (!success) 931 SendNack(); 932 else 933 SendAck(); 934 } 935 } else { 936 success = false; 937 if (log) 938 log->Printf("error: invalid checksum in packet: '%s'\n", 939 m_bytes.c_str()); 940 } 941 } 942 943 m_bytes.erase(0, total_length); 944 packet.SetFilePos(0); 945 946 if (isNotifyPacket) 947 return GDBRemoteCommunication::PacketType::Notify; 948 else 949 return GDBRemoteCommunication::PacketType::Standard; 950 } 951 } 952 packet.Clear(); 953 return GDBRemoteCommunication::PacketType::Invalid; 954 } 955 956 Error GDBRemoteCommunication::StartListenThread(const char *hostname, 957 uint16_t port) { 958 Error error; 959 if (m_listen_thread.IsJoinable()) { 960 error.SetErrorString("listen thread already running"); 961 } else { 962 char listen_url[512]; 963 if (hostname && hostname[0]) 964 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, 965 port); 966 else 967 snprintf(listen_url, sizeof(listen_url), "listen://%i", port); 968 m_listen_url = listen_url; 969 SetConnection(new ConnectionFileDescriptor()); 970 m_listen_thread = ThreadLauncher::LaunchThread( 971 listen_url, GDBRemoteCommunication::ListenThread, this, &error); 972 } 973 return error; 974 } 975 976 bool GDBRemoteCommunication::JoinListenThread() { 977 if (m_listen_thread.IsJoinable()) 978 m_listen_thread.Join(nullptr); 979 return true; 980 } 981 982 lldb::thread_result_t 983 GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) { 984 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg; 985 Error error; 986 ConnectionFileDescriptor *connection = 987 (ConnectionFileDescriptor *)comm->GetConnection(); 988 989 if (connection) { 990 // Do the listen on another thread so we can continue on... 991 if (connection->Connect(comm->m_listen_url.c_str(), &error) != 992 eConnectionStatusSuccess) 993 comm->SetConnection(NULL); 994 } 995 return NULL; 996 } 997 998 Error GDBRemoteCommunication::StartDebugserverProcess( 999 const char *url, Platform *platform, ProcessLaunchInfo &launch_info, 1000 uint16_t *port, const Args *inferior_args, int pass_comm_fd) { 1001 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1002 if (log) 1003 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")", 1004 __FUNCTION__, url ? url : "<empty>", 1005 port ? *port : uint16_t(0)); 1006 1007 Error error; 1008 // If we locate debugserver, keep that located version around 1009 static FileSpec g_debugserver_file_spec; 1010 1011 char debugserver_path[PATH_MAX]; 1012 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile(); 1013 1014 // Always check to see if we have an environment override for the path 1015 // to the debugserver to use and use it if we do. 1016 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH"); 1017 if (env_debugserver_path) { 1018 debugserver_file_spec.SetFile(env_debugserver_path, false); 1019 if (log) 1020 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set " 1021 "from environment variable: %s", 1022 __FUNCTION__, env_debugserver_path); 1023 } else 1024 debugserver_file_spec = g_debugserver_file_spec; 1025 bool debugserver_exists = debugserver_file_spec.Exists(); 1026 if (!debugserver_exists) { 1027 // The debugserver binary is in the LLDB.framework/Resources 1028 // directory. 1029 if (HostInfo::GetLLDBPath(ePathTypeSupportExecutableDir, 1030 debugserver_file_spec)) { 1031 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME); 1032 debugserver_exists = debugserver_file_spec.Exists(); 1033 if (debugserver_exists) { 1034 if (log) 1035 log->Printf( 1036 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'", 1037 __FUNCTION__, debugserver_file_spec.GetPath().c_str()); 1038 1039 g_debugserver_file_spec = debugserver_file_spec; 1040 } else { 1041 debugserver_file_spec = 1042 platform->LocateExecutable(DEBUGSERVER_BASENAME); 1043 if (debugserver_file_spec) { 1044 // Platform::LocateExecutable() wouldn't return a path if it doesn't 1045 // exist 1046 debugserver_exists = true; 1047 } else { 1048 if (log) 1049 log->Printf("GDBRemoteCommunication::%s() could not find " 1050 "gdb-remote stub exe '%s'", 1051 __FUNCTION__, debugserver_file_spec.GetPath().c_str()); 1052 } 1053 // Don't cache the platform specific GDB server binary as it could 1054 // change 1055 // from platform to platform 1056 g_debugserver_file_spec.Clear(); 1057 } 1058 } 1059 } 1060 1061 if (debugserver_exists) { 1062 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path)); 1063 1064 Args &debugserver_args = launch_info.GetArguments(); 1065 debugserver_args.Clear(); 1066 char arg_cstr[PATH_MAX]; 1067 1068 // Start args with "debugserver /file/path -r --" 1069 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path)); 1070 1071 #if !defined(__APPLE__) 1072 // First argument to lldb-server must be mode in which to run. 1073 debugserver_args.AppendArgument(llvm::StringRef("gdbserver")); 1074 #endif 1075 1076 // If a url is supplied then use it 1077 if (url) 1078 debugserver_args.AppendArgument(llvm::StringRef(url)); 1079 1080 if (pass_comm_fd >= 0) { 1081 StreamString fd_arg; 1082 fd_arg.Printf("--fd=%i", pass_comm_fd); 1083 debugserver_args.AppendArgument(fd_arg.GetString()); 1084 // Send "pass_comm_fd" down to the inferior so it can use it to 1085 // communicate back with this process 1086 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd); 1087 } 1088 1089 // use native registers, not the GDB registers 1090 debugserver_args.AppendArgument(llvm::StringRef("--native-regs")); 1091 1092 if (launch_info.GetLaunchInSeparateProcessGroup()) { 1093 debugserver_args.AppendArgument(llvm::StringRef("--setsid")); 1094 } 1095 1096 llvm::SmallString<PATH_MAX> named_pipe_path; 1097 // socket_pipe is used by debug server to communicate back either 1098 // TCP port or domain socket name which it listens on. 1099 // The second purpose of the pipe to serve as a synchronization point - 1100 // once data is written to the pipe, debug server is up and running. 1101 Pipe socket_pipe; 1102 1103 // port is null when debug server should listen on domain socket - 1104 // we're not interested in port value but rather waiting for debug server 1105 // to become available. 1106 if (pass_comm_fd == -1 && 1107 ((port != nullptr && *port == 0) || port == nullptr)) { 1108 if (url) { 1109 // Create a temporary file to get the stdout/stderr and redirect the 1110 // output of the command into this file. We will later read this file 1111 // if all goes well and fill the data into "command_output_ptr" 1112 #if defined(__APPLE__) 1113 // Binding to port zero, we need to figure out what port it ends up 1114 // using using a named pipe... 1115 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe", 1116 false, named_pipe_path); 1117 if (error.Fail()) { 1118 if (log) 1119 log->Printf("GDBRemoteCommunication::%s() " 1120 "named pipe creation failed: %s", 1121 __FUNCTION__, error.AsCString()); 1122 return error; 1123 } 1124 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe")); 1125 debugserver_args.AppendArgument(named_pipe_path); 1126 #else 1127 // Binding to port zero, we need to figure out what port it ends up 1128 // using using an unnamed pipe... 1129 error = socket_pipe.CreateNew(true); 1130 if (error.Fail()) { 1131 if (log) 1132 log->Printf("GDBRemoteCommunication::%s() " 1133 "unnamed pipe creation failed: %s", 1134 __FUNCTION__, error.AsCString()); 1135 return error; 1136 } 1137 int write_fd = socket_pipe.GetWriteFileDescriptor(); 1138 debugserver_args.AppendArgument(llvm::StringRef("--pipe")); 1139 debugserver_args.AppendArgument(llvm::to_string(write_fd)); 1140 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor()); 1141 #endif 1142 } else { 1143 // No host and port given, so lets listen on our end and make the 1144 // debugserver 1145 // connect to us.. 1146 error = StartListenThread("127.0.0.1", 0); 1147 if (error.Fail()) { 1148 if (log) 1149 log->Printf("GDBRemoteCommunication::%s() unable to start listen " 1150 "thread: %s", 1151 __FUNCTION__, error.AsCString()); 1152 return error; 1153 } 1154 1155 ConnectionFileDescriptor *connection = 1156 (ConnectionFileDescriptor *)GetConnection(); 1157 // Wait for 10 seconds to resolve the bound port 1158 uint16_t port_ = connection->GetListeningPort(10); 1159 if (port_ > 0) { 1160 char port_cstr[32]; 1161 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_); 1162 // Send the host and port down that debugserver and specify an option 1163 // so that it connects back to the port we are listening to in this 1164 // process 1165 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect")); 1166 debugserver_args.AppendArgument(llvm::StringRef(port_cstr)); 1167 if (port) 1168 *port = port_; 1169 } else { 1170 error.SetErrorString("failed to bind to port 0 on 127.0.0.1"); 1171 if (log) 1172 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__, 1173 error.AsCString()); 1174 return error; 1175 } 1176 } 1177 } 1178 1179 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE"); 1180 if (env_debugserver_log_file) { 1181 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-file=%s", 1182 env_debugserver_log_file); 1183 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr)); 1184 } 1185 1186 #if defined(__APPLE__) 1187 const char *env_debugserver_log_flags = 1188 getenv("LLDB_DEBUGSERVER_LOG_FLAGS"); 1189 if (env_debugserver_log_flags) { 1190 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-flags=%s", 1191 env_debugserver_log_flags); 1192 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr)); 1193 } 1194 #else 1195 const char *env_debugserver_log_channels = 1196 getenv("LLDB_SERVER_LOG_CHANNELS"); 1197 if (env_debugserver_log_channels) { 1198 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-channels=%s", 1199 env_debugserver_log_channels); 1200 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr)); 1201 } 1202 #endif 1203 1204 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an 1205 // env var doesn't come back. 1206 uint32_t env_var_index = 1; 1207 bool has_env_var; 1208 do { 1209 char env_var_name[64]; 1210 snprintf(env_var_name, sizeof(env_var_name), 1211 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++); 1212 const char *extra_arg = getenv(env_var_name); 1213 has_env_var = extra_arg != nullptr; 1214 1215 if (has_env_var) { 1216 debugserver_args.AppendArgument(llvm::StringRef(extra_arg)); 1217 if (log) 1218 log->Printf("GDBRemoteCommunication::%s adding env var %s contents " 1219 "to stub command line (%s)", 1220 __FUNCTION__, env_var_name, extra_arg); 1221 } 1222 } while (has_env_var); 1223 1224 if (inferior_args && inferior_args->GetArgumentCount() > 0) { 1225 debugserver_args.AppendArgument(llvm::StringRef("--")); 1226 debugserver_args.AppendArguments(*inferior_args); 1227 } 1228 1229 // Copy the current environment to the gdbserver/debugserver instance 1230 StringList env; 1231 if (Host::GetEnvironment(env)) { 1232 for (size_t i = 0; i < env.GetSize(); ++i) 1233 launch_info.GetEnvironmentEntries().AppendArgument(env[i]); 1234 } 1235 1236 // Close STDIN, STDOUT and STDERR. 1237 launch_info.AppendCloseFileAction(STDIN_FILENO); 1238 launch_info.AppendCloseFileAction(STDOUT_FILENO); 1239 launch_info.AppendCloseFileAction(STDERR_FILENO); 1240 1241 // Redirect STDIN, STDOUT and STDERR to "/dev/null". 1242 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false); 1243 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true); 1244 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true); 1245 1246 if (log) { 1247 StreamString string_stream; 1248 Platform *const platform = nullptr; 1249 launch_info.Dump(string_stream, platform); 1250 log->Printf("launch info for gdb-remote stub:\n%s", 1251 string_stream.GetString().c_str()); 1252 } 1253 error = Host::LaunchProcess(launch_info); 1254 1255 if (error.Success() && 1256 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) && 1257 pass_comm_fd == -1) { 1258 if (named_pipe_path.size() > 0) { 1259 error = socket_pipe.OpenAsReader(named_pipe_path, false); 1260 if (error.Fail()) 1261 if (log) 1262 log->Printf("GDBRemoteCommunication::%s() " 1263 "failed to open named pipe %s for reading: %s", 1264 __FUNCTION__, named_pipe_path.c_str(), 1265 error.AsCString()); 1266 } 1267 1268 if (socket_pipe.CanWrite()) 1269 socket_pipe.CloseWriteFileDescriptor(); 1270 if (socket_pipe.CanRead()) { 1271 char port_cstr[PATH_MAX] = {0}; 1272 port_cstr[0] = '\0'; 1273 size_t num_bytes = sizeof(port_cstr); 1274 // Read port from pipe with 10 second timeout. 1275 error = socket_pipe.ReadWithTimeout( 1276 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes); 1277 if (error.Success() && (port != nullptr)) { 1278 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0'); 1279 *port = StringConvert::ToUInt32(port_cstr, 0); 1280 if (log) 1281 log->Printf("GDBRemoteCommunication::%s() " 1282 "debugserver listens %u port", 1283 __FUNCTION__, *port); 1284 } else { 1285 if (log) 1286 log->Printf("GDBRemoteCommunication::%s() " 1287 "failed to read a port value from pipe %s: %s", 1288 __FUNCTION__, named_pipe_path.c_str(), 1289 error.AsCString()); 1290 } 1291 socket_pipe.Close(); 1292 } 1293 1294 if (named_pipe_path.size() > 0) { 1295 const auto err = socket_pipe.Delete(named_pipe_path); 1296 if (err.Fail()) { 1297 if (log) 1298 log->Printf( 1299 "GDBRemoteCommunication::%s failed to delete pipe %s: %s", 1300 __FUNCTION__, named_pipe_path.c_str(), err.AsCString()); 1301 } 1302 } 1303 1304 // Make sure we actually connect with the debugserver... 1305 JoinListenThread(); 1306 } 1307 } else { 1308 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME); 1309 } 1310 1311 if (error.Fail()) { 1312 if (log) 1313 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__, 1314 error.AsCString()); 1315 } 1316 1317 return error; 1318 } 1319 1320 void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); } 1321 1322 GDBRemoteCommunication::ScopedTimeout::ScopedTimeout( 1323 GDBRemoteCommunication &gdb_comm, uint32_t timeout) 1324 : m_gdb_comm(gdb_comm) { 1325 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout); 1326 } 1327 1328 GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() { 1329 m_gdb_comm.SetPacketTimeout(m_saved_timeout); 1330 } 1331 1332 // This function is called via the Communications class read thread when bytes 1333 // become available 1334 // for this connection. This function will consume all incoming bytes and try to 1335 // parse whole 1336 // packets as they become available. Full packets are placed in a queue, so that 1337 // all packet 1338 // requests can simply pop from this queue. Async notification packets will be 1339 // dispatched 1340 // immediately to the ProcessGDBRemote Async thread via an event. 1341 void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes, 1342 size_t len, bool broadcast, 1343 lldb::ConnectionStatus status) { 1344 StringExtractorGDBRemote packet; 1345 1346 while (true) { 1347 PacketType type = CheckForPacket(bytes, len, packet); 1348 1349 // scrub the data so we do not pass it back to CheckForPacket 1350 // on future passes of the loop 1351 bytes = nullptr; 1352 len = 0; 1353 1354 // we may have received no packet so lets bail out 1355 if (type == PacketType::Invalid) 1356 break; 1357 1358 if (type == PacketType::Standard) { 1359 // scope for the mutex 1360 { 1361 // lock down the packet queue 1362 std::lock_guard<std::mutex> guard(m_packet_queue_mutex); 1363 // push a new packet into the queue 1364 m_packet_queue.push(packet); 1365 // Signal condition variable that we have a packet 1366 m_condition_queue_not_empty.notify_one(); 1367 } 1368 } 1369 1370 if (type == PacketType::Notify) { 1371 // put this packet into an event 1372 const char *pdata = packet.GetStringRef().c_str(); 1373 1374 // as the communication class, we are a broadcaster and the 1375 // async thread is tuned to listen to us 1376 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify, 1377 new EventDataBytes(pdata)); 1378 } 1379 } 1380 } 1381