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