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