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/StreamFile.h" 22 #include "lldb/Core/StreamString.h" 23 #include "lldb/Host/ConnectionFileDescriptor.h" 24 #include "lldb/Host/FileSpec.h" 25 #include "lldb/Host/FileSystem.h" 26 #include "lldb/Host/Host.h" 27 #include "lldb/Host/HostInfo.h" 28 #include "lldb/Host/Socket.h" 29 #include "lldb/Host/ThreadLauncher.h" 30 #include "lldb/Host/TimeValue.h" 31 #include "lldb/Target/Process.h" 32 33 // Project includes 34 #include "ProcessGDBRemoteLog.h" 35 36 #if defined(__APPLE__) 37 # define DEBUGSERVER_BASENAME "debugserver" 38 #else 39 # define DEBUGSERVER_BASENAME "lldb-gdbserver" 40 #endif 41 42 using namespace lldb; 43 using namespace lldb_private; 44 45 GDBRemoteCommunication::History::History (uint32_t size) : 46 m_packets(), 47 m_curr_idx (0), 48 m_total_packet_count (0), 49 m_dumped_to_log (false) 50 { 51 m_packets.resize(size); 52 } 53 54 GDBRemoteCommunication::History::~History () 55 { 56 } 57 58 void 59 GDBRemoteCommunication::History::AddPacket (char packet_char, 60 PacketType type, 61 uint32_t bytes_transmitted) 62 { 63 const size_t size = m_packets.size(); 64 if (size > 0) 65 { 66 const uint32_t idx = GetNextIndex(); 67 m_packets[idx].packet.assign (1, packet_char); 68 m_packets[idx].type = type; 69 m_packets[idx].bytes_transmitted = bytes_transmitted; 70 m_packets[idx].packet_idx = m_total_packet_count; 71 m_packets[idx].tid = Host::GetCurrentThreadID(); 72 } 73 } 74 75 void 76 GDBRemoteCommunication::History::AddPacket (const std::string &src, 77 uint32_t src_len, 78 PacketType type, 79 uint32_t bytes_transmitted) 80 { 81 const size_t size = m_packets.size(); 82 if (size > 0) 83 { 84 const uint32_t idx = GetNextIndex(); 85 m_packets[idx].packet.assign (src, 0, src_len); 86 m_packets[idx].type = type; 87 m_packets[idx].bytes_transmitted = bytes_transmitted; 88 m_packets[idx].packet_idx = m_total_packet_count; 89 m_packets[idx].tid = Host::GetCurrentThreadID(); 90 } 91 } 92 93 void 94 GDBRemoteCommunication::History::Dump (lldb_private::Stream &strm) const 95 { 96 const uint32_t size = GetNumPacketsInHistory (); 97 const uint32_t first_idx = GetFirstSavedPacketIndex (); 98 const uint32_t stop_idx = m_curr_idx + size; 99 for (uint32_t i = first_idx; i < stop_idx; ++i) 100 { 101 const uint32_t idx = NormalizeIndex (i); 102 const Entry &entry = m_packets[idx]; 103 if (entry.type == ePacketTypeInvalid || entry.packet.empty()) 104 break; 105 strm.Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s\n", 106 entry.packet_idx, 107 entry.tid, 108 entry.bytes_transmitted, 109 (entry.type == ePacketTypeSend) ? "send" : "read", 110 entry.packet.c_str()); 111 } 112 } 113 114 void 115 GDBRemoteCommunication::History::Dump (lldb_private::Log *log) const 116 { 117 if (log && !m_dumped_to_log) 118 { 119 m_dumped_to_log = true; 120 const uint32_t size = GetNumPacketsInHistory (); 121 const uint32_t first_idx = GetFirstSavedPacketIndex (); 122 const uint32_t stop_idx = m_curr_idx + size; 123 for (uint32_t i = first_idx; i < stop_idx; ++i) 124 { 125 const uint32_t idx = NormalizeIndex (i); 126 const Entry &entry = m_packets[idx]; 127 if (entry.type == ePacketTypeInvalid || entry.packet.empty()) 128 break; 129 log->Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s", 130 entry.packet_idx, 131 entry.tid, 132 entry.bytes_transmitted, 133 (entry.type == ePacketTypeSend) ? "send" : "read", 134 entry.packet.c_str()); 135 } 136 } 137 } 138 139 //---------------------------------------------------------------------- 140 // GDBRemoteCommunication constructor 141 //---------------------------------------------------------------------- 142 GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name, 143 const char *listener_name, 144 bool is_platform) : 145 Communication(comm_name), 146 #ifdef LLDB_CONFIGURATION_DEBUG 147 m_packet_timeout (1000), 148 #else 149 m_packet_timeout (1), 150 #endif 151 m_sequence_mutex (Mutex::eMutexTypeRecursive), 152 m_public_is_running (false), 153 m_private_is_running (false), 154 m_history (512), 155 m_send_acks (true), 156 m_is_platform (is_platform), 157 m_listen_url () 158 { 159 } 160 161 //---------------------------------------------------------------------- 162 // Destructor 163 //---------------------------------------------------------------------- 164 GDBRemoteCommunication::~GDBRemoteCommunication() 165 { 166 if (IsConnected()) 167 { 168 Disconnect(); 169 } 170 } 171 172 char 173 GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length) 174 { 175 int checksum = 0; 176 177 for (size_t i = 0; i < payload_length; ++i) 178 checksum += payload[i]; 179 180 return checksum & 255; 181 } 182 183 size_t 184 GDBRemoteCommunication::SendAck () 185 { 186 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS)); 187 ConnectionStatus status = eConnectionStatusSuccess; 188 char ch = '+'; 189 const size_t bytes_written = Write (&ch, 1, status, NULL); 190 if (log) 191 log->Printf ("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch); 192 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written); 193 return bytes_written; 194 } 195 196 size_t 197 GDBRemoteCommunication::SendNack () 198 { 199 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS)); 200 ConnectionStatus status = eConnectionStatusSuccess; 201 char ch = '-'; 202 const size_t bytes_written = Write (&ch, 1, status, NULL); 203 if (log) 204 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch); 205 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written); 206 return bytes_written; 207 } 208 209 GDBRemoteCommunication::PacketResult 210 GDBRemoteCommunication::SendPacket (const char *payload, size_t payload_length) 211 { 212 Mutex::Locker locker(m_sequence_mutex); 213 return SendPacketNoLock (payload, payload_length); 214 } 215 216 GDBRemoteCommunication::PacketResult 217 GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length) 218 { 219 if (IsConnected()) 220 { 221 StreamString packet(0, 4, eByteOrderBig); 222 223 packet.PutChar('$'); 224 packet.Write (payload, payload_length); 225 packet.PutChar('#'); 226 packet.PutHex8(CalculcateChecksum (payload, payload_length)); 227 228 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS)); 229 ConnectionStatus status = eConnectionStatusSuccess; 230 const char *packet_data = packet.GetData(); 231 const size_t packet_length = packet.GetSize(); 232 size_t bytes_written = Write (packet_data, packet_length, status, NULL); 233 if (log) 234 { 235 size_t binary_start_offset = 0; 236 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) == 0) 237 { 238 const char *first_comma = strchr(packet_data, ','); 239 if (first_comma) 240 { 241 const char *second_comma = strchr(first_comma + 1, ','); 242 if (second_comma) 243 binary_start_offset = second_comma - packet_data + 1; 244 } 245 } 246 247 // If logging was just enabled and we have history, then dump out what 248 // we have to the log so we get the historical context. The Dump() call that 249 // logs all of the packet will set a boolean so that we don't dump this more 250 // than once 251 if (!m_history.DidDumpToLog ()) 252 m_history.Dump (log); 253 254 if (binary_start_offset) 255 { 256 StreamString strm; 257 // Print non binary data header 258 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)binary_start_offset, packet_data); 259 const uint8_t *p; 260 // Print binary data exactly as sent 261 for (p = (uint8_t*)packet_data + binary_start_offset; *p != '#'; ++p) 262 strm.Printf("\\x%2.2x", *p); 263 // Print the checksum 264 strm.Printf("%*s", (int)3, p); 265 log->PutCString(strm.GetString().c_str()); 266 } 267 else 268 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)packet_length, packet_data); 269 } 270 271 m_history.AddPacket (packet.GetString(), packet_length, History::ePacketTypeSend, bytes_written); 272 273 274 if (bytes_written == packet_length) 275 { 276 if (GetSendAcks ()) 277 return GetAck (); 278 else 279 return PacketResult::Success; 280 } 281 else 282 { 283 if (log) 284 log->Printf ("error: failed to send packet: %.*s", (int)packet_length, packet_data); 285 } 286 } 287 return PacketResult::ErrorSendFailed; 288 } 289 290 GDBRemoteCommunication::PacketResult 291 GDBRemoteCommunication::GetAck () 292 { 293 StringExtractorGDBRemote packet; 294 PacketResult result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, GetPacketTimeoutInMicroSeconds ()); 295 if (result == PacketResult::Success) 296 { 297 if (packet.GetResponseType() == StringExtractorGDBRemote::ResponseType::eAck) 298 return PacketResult::Success; 299 else 300 return PacketResult::ErrorSendAck; 301 } 302 return result; 303 } 304 305 bool 306 GDBRemoteCommunication::GetSequenceMutex (Mutex::Locker& locker, const char *failure_message) 307 { 308 if (IsRunning()) 309 return locker.TryLock (m_sequence_mutex, failure_message); 310 311 locker.Lock (m_sequence_mutex); 312 return true; 313 } 314 315 316 bool 317 GDBRemoteCommunication::WaitForNotRunningPrivate (const TimeValue *timeout_ptr) 318 { 319 return m_private_is_running.WaitForValueEqualTo (false, timeout_ptr, NULL); 320 } 321 322 GDBRemoteCommunication::PacketResult 323 GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSecondsNoLock (StringExtractorGDBRemote &packet, uint32_t timeout_usec) 324 { 325 uint8_t buffer[8192]; 326 Error error; 327 328 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS | GDBR_LOG_VERBOSE)); 329 330 // Check for a packet from our cache first without trying any reading... 331 if (CheckForPacket (NULL, 0, packet)) 332 return PacketResult::Success; 333 334 bool timed_out = false; 335 bool disconnected = false; 336 while (IsConnected() && !timed_out) 337 { 338 lldb::ConnectionStatus status = eConnectionStatusNoConnection; 339 size_t bytes_read = Read (buffer, sizeof(buffer), timeout_usec, status, &error); 340 341 if (log) 342 log->Printf ("%s: Read (buffer, (sizeof(buffer), timeout_usec = 0x%x, status = %s, error = %s) => bytes_read = %" PRIu64, 343 __PRETTY_FUNCTION__, 344 timeout_usec, 345 Communication::ConnectionStatusAsCString (status), 346 error.AsCString(), 347 (uint64_t)bytes_read); 348 349 if (bytes_read > 0) 350 { 351 if (CheckForPacket (buffer, bytes_read, packet)) 352 return PacketResult::Success; 353 } 354 else 355 { 356 switch (status) 357 { 358 case eConnectionStatusTimedOut: 359 case eConnectionStatusInterrupted: 360 timed_out = true; 361 break; 362 case eConnectionStatusSuccess: 363 //printf ("status = success but error = %s\n", error.AsCString("<invalid>")); 364 break; 365 366 case eConnectionStatusEndOfFile: 367 case eConnectionStatusNoConnection: 368 case eConnectionStatusLostConnection: 369 case eConnectionStatusError: 370 disconnected = true; 371 Disconnect(); 372 break; 373 } 374 } 375 } 376 packet.Clear (); 377 if (disconnected) 378 return PacketResult::ErrorDisconnected; 379 if (timed_out) 380 return PacketResult::ErrorReplyTimeout; 381 else 382 return PacketResult::ErrorReplyFailed; 383 } 384 385 bool 386 GDBRemoteCommunication::CheckForPacket (const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet) 387 { 388 // Put the packet data into the buffer in a thread safe fashion 389 Mutex::Locker locker(m_bytes_mutex); 390 391 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS)); 392 393 if (src && src_len > 0) 394 { 395 if (log && log->GetVerbose()) 396 { 397 StreamString s; 398 log->Printf ("GDBRemoteCommunication::%s adding %u bytes: %.*s", 399 __FUNCTION__, 400 (uint32_t)src_len, 401 (uint32_t)src_len, 402 src); 403 } 404 m_bytes.append ((const char *)src, src_len); 405 } 406 407 // Parse up the packets into gdb remote packets 408 if (!m_bytes.empty()) 409 { 410 // end_idx must be one past the last valid packet byte. Start 411 // it off with an invalid value that is the same as the current 412 // index. 413 size_t content_start = 0; 414 size_t content_length = std::string::npos; 415 size_t total_length = 0; 416 size_t checksum_idx = std::string::npos; 417 418 while (!m_bytes.empty() && content_length == std::string::npos) 419 { 420 switch (m_bytes[0]) 421 { 422 case '+': // Look for ack 423 case '-': // Look for cancel 424 case '\x03': // ^C to halt target 425 content_length = total_length = 1; // The command is one byte long... 426 break; 427 428 case '$': 429 // Look for a standard gdb packet? 430 { 431 size_t hash_pos = m_bytes.find('#'); 432 if (hash_pos != std::string::npos) 433 { 434 if (hash_pos + 2 < m_bytes.size()) 435 { 436 checksum_idx = hash_pos + 1; 437 // Skip the dollar sign 438 content_start = 1; 439 // Don't include the # in the content or the $ in the content length 440 content_length = hash_pos - 1; 441 442 total_length = hash_pos + 3; // Skip the # and the two hex checksum bytes 443 } 444 else 445 { 446 // Checksum bytes aren't all here yet 447 content_length = std::string::npos; 448 } 449 } 450 } 451 break; 452 453 default: 454 { 455 // We have an unexpected byte and we need to flush all bad 456 // data that is in m_bytes, so we need to find the first 457 // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt), 458 // or '$' character (start of packet header) or of course, 459 // the end of the data in m_bytes... 460 const size_t bytes_len = m_bytes.size(); 461 bool done = false; 462 uint32_t idx; 463 for (idx = 1; !done && idx < bytes_len; ++idx) 464 { 465 switch (m_bytes[idx]) 466 { 467 case '+': 468 case '-': 469 case '\x03': 470 case '$': 471 done = true; 472 break; 473 474 default: 475 break; 476 } 477 } 478 if (log) 479 log->Printf ("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'", 480 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str()); 481 m_bytes.erase(0, idx - 1); 482 } 483 break; 484 } 485 } 486 487 if (content_length == std::string::npos) 488 { 489 packet.Clear(); 490 return false; 491 } 492 else if (total_length > 0) 493 { 494 495 // We have a valid packet... 496 assert (content_length <= m_bytes.size()); 497 assert (total_length <= m_bytes.size()); 498 assert (content_length <= total_length); 499 const size_t content_end = content_start + content_length; 500 501 bool success = true; 502 std::string &packet_str = packet.GetStringRef(); 503 504 505 if (log) 506 { 507 // If logging was just enabled and we have history, then dump out what 508 // we have to the log so we get the historical context. The Dump() call that 509 // logs all of the packet will set a boolean so that we don't dump this more 510 // than once 511 if (!m_history.DidDumpToLog ()) 512 m_history.Dump (log); 513 514 bool binary = false; 515 // Only detect binary for packets that start with a '$' and have a '#CC' checksum 516 if (m_bytes[0] == '$' && total_length > 4) 517 { 518 for (size_t i=0; !binary && i<total_length; ++i) 519 { 520 if (isprint(m_bytes[i]) == 0) 521 binary = true; 522 } 523 } 524 if (binary) 525 { 526 StreamString strm; 527 // Packet header... 528 strm.Printf("<%4" PRIu64 "> read packet: %c", (uint64_t)total_length, m_bytes[0]); 529 for (size_t i=content_start; i<content_end; ++i) 530 { 531 // Remove binary escaped bytes when displaying the packet... 532 const char ch = m_bytes[i]; 533 if (ch == 0x7d) 534 { 535 // 0x7d is the escape character. The next character is to 536 // be XOR'd with 0x20. 537 const char escapee = m_bytes[++i] ^ 0x20; 538 strm.Printf("%2.2x", escapee); 539 } 540 else 541 { 542 strm.Printf("%2.2x", (uint8_t)ch); 543 } 544 } 545 // Packet footer... 546 strm.Printf("%c%c%c", m_bytes[total_length-3], m_bytes[total_length-2], m_bytes[total_length-1]); 547 log->PutCString(strm.GetString().c_str()); 548 } 549 else 550 { 551 log->Printf("<%4" PRIu64 "> read packet: %.*s", (uint64_t)total_length, (int)(total_length), m_bytes.c_str()); 552 } 553 } 554 555 m_history.AddPacket (m_bytes.c_str(), total_length, History::ePacketTypeRecv, total_length); 556 557 // Clear packet_str in case there is some existing data in it. 558 packet_str.clear(); 559 // Copy the packet from m_bytes to packet_str expanding the 560 // run-length encoding in the process. 561 // Reserve enough byte for the most common case (no RLE used) 562 packet_str.reserve(m_bytes.length()); 563 for (std::string::const_iterator c = m_bytes.begin() + content_start; c != m_bytes.begin() + content_end; ++c) 564 { 565 if (*c == '*') 566 { 567 // '*' indicates RLE. Next character will give us the 568 // repeat count and previous character is what is to be 569 // repeated. 570 char char_to_repeat = packet_str.back(); 571 // Number of time the previous character is repeated 572 int repeat_count = *++c + 3 - ' '; 573 // We have the char_to_repeat and repeat_count. Now push 574 // it in the packet. 575 for (int i = 0; i < repeat_count; ++i) 576 packet_str.push_back(char_to_repeat); 577 } 578 else if (*c == 0x7d) 579 { 580 // 0x7d is the escape character. The next character is to 581 // be XOR'd with 0x20. 582 char escapee = *++c ^ 0x20; 583 packet_str.push_back(escapee); 584 } 585 else 586 { 587 packet_str.push_back(*c); 588 } 589 } 590 591 if (m_bytes[0] == '$') 592 { 593 assert (checksum_idx < m_bytes.size()); 594 if (::isxdigit (m_bytes[checksum_idx+0]) || 595 ::isxdigit (m_bytes[checksum_idx+1])) 596 { 597 if (GetSendAcks ()) 598 { 599 const char *packet_checksum_cstr = &m_bytes[checksum_idx]; 600 char packet_checksum = strtol (packet_checksum_cstr, NULL, 16); 601 char actual_checksum = CalculcateChecksum (packet_str.c_str(), packet_str.size()); 602 success = packet_checksum == actual_checksum; 603 if (!success) 604 { 605 if (log) 606 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x", 607 (int)(total_length), 608 m_bytes.c_str(), 609 (uint8_t)packet_checksum, 610 (uint8_t)actual_checksum); 611 } 612 // Send the ack or nack if needed 613 if (!success) 614 SendNack(); 615 else 616 SendAck(); 617 } 618 } 619 else 620 { 621 success = false; 622 if (log) 623 log->Printf ("error: invalid checksum in packet: '%s'\n", m_bytes.c_str()); 624 } 625 } 626 627 m_bytes.erase(0, total_length); 628 packet.SetFilePos(0); 629 return success; 630 } 631 } 632 packet.Clear(); 633 return false; 634 } 635 636 Error 637 GDBRemoteCommunication::StartListenThread (const char *hostname, uint16_t port) 638 { 639 Error error; 640 if (m_listen_thread.IsJoinable()) 641 { 642 error.SetErrorString("listen thread already running"); 643 } 644 else 645 { 646 char listen_url[512]; 647 if (hostname && hostname[0]) 648 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port); 649 else 650 snprintf(listen_url, sizeof(listen_url), "listen://%i", port); 651 m_listen_url = listen_url; 652 SetConnection(new ConnectionFileDescriptor()); 653 m_listen_thread = ThreadLauncher::LaunchThread(listen_url, GDBRemoteCommunication::ListenThread, this, &error); 654 } 655 return error; 656 } 657 658 bool 659 GDBRemoteCommunication::JoinListenThread () 660 { 661 if (m_listen_thread.IsJoinable()) 662 m_listen_thread.Join(nullptr); 663 return true; 664 } 665 666 lldb::thread_result_t 667 GDBRemoteCommunication::ListenThread (lldb::thread_arg_t arg) 668 { 669 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg; 670 Error error; 671 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)comm->GetConnection (); 672 673 if (connection) 674 { 675 // Do the listen on another thread so we can continue on... 676 if (connection->Connect(comm->m_listen_url.c_str(), &error) != eConnectionStatusSuccess) 677 comm->SetConnection(NULL); 678 } 679 return NULL; 680 } 681 682 Error 683 GDBRemoteCommunication::StartDebugserverProcess (const char *hostname, 684 uint16_t in_port, 685 lldb_private::ProcessLaunchInfo &launch_info, 686 uint16_t &out_port) 687 { 688 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 689 if (log) 690 log->Printf ("GDBRemoteCommunication::%s(hostname=%s, in_port=%" PRIu16 ", out_port=%" PRIu16, __FUNCTION__, hostname ? hostname : "<empty>", in_port, out_port); 691 692 out_port = in_port; 693 Error error; 694 // If we locate debugserver, keep that located version around 695 static FileSpec g_debugserver_file_spec; 696 697 char debugserver_path[PATH_MAX]; 698 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile(); 699 700 // Always check to see if we have an environment override for the path 701 // to the debugserver to use and use it if we do. 702 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH"); 703 if (env_debugserver_path) 704 { 705 debugserver_file_spec.SetFile (env_debugserver_path, false); 706 if (log) 707 log->Printf ("GDBRemoteCommunication::%s() gdb-remote stub exe path set from environment variable: %s", __FUNCTION__, env_debugserver_path); 708 } 709 else 710 debugserver_file_spec = g_debugserver_file_spec; 711 bool debugserver_exists = debugserver_file_spec.Exists(); 712 if (!debugserver_exists) 713 { 714 // The debugserver binary is in the LLDB.framework/Resources 715 // directory. 716 if (HostInfo::GetLLDBPath(ePathTypeSupportExecutableDir, debugserver_file_spec)) 717 { 718 debugserver_file_spec.AppendPathComponent (DEBUGSERVER_BASENAME); 719 debugserver_exists = debugserver_file_spec.Exists(); 720 if (debugserver_exists) 721 { 722 if (log) 723 log->Printf ("GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ()); 724 725 g_debugserver_file_spec = debugserver_file_spec; 726 } 727 else 728 { 729 if (log) 730 log->Printf ("GDBRemoteCommunication::%s() could not find gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ()); 731 732 g_debugserver_file_spec.Clear(); 733 debugserver_file_spec.Clear(); 734 } 735 } 736 } 737 738 if (debugserver_exists) 739 { 740 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path)); 741 742 Args &debugserver_args = launch_info.GetArguments(); 743 debugserver_args.Clear(); 744 char arg_cstr[PATH_MAX]; 745 746 // Start args with "debugserver /file/path -r --" 747 debugserver_args.AppendArgument(debugserver_path); 748 749 // If a host and port is supplied then use it 750 char host_and_port[128]; 751 if (hostname) 752 { 753 snprintf (host_and_port, sizeof(host_and_port), "%s:%u", hostname, in_port); 754 debugserver_args.AppendArgument(host_and_port); 755 } 756 else 757 { 758 host_and_port[0] = '\0'; 759 } 760 761 // use native registers, not the GDB registers 762 debugserver_args.AppendArgument("--native-regs"); 763 // make debugserver run in its own session so signals generated by 764 // special terminal key sequences (^C) don't affect debugserver 765 debugserver_args.AppendArgument("--setsid"); 766 767 char named_pipe_path[PATH_MAX]; 768 named_pipe_path[0] = '\0'; 769 770 bool listen = false; 771 if (host_and_port[0]) 772 { 773 // Create a temporary file to get the stdout/stderr and redirect the 774 // output of the command into this file. We will later read this file 775 // if all goes well and fill the data into "command_output_ptr" 776 777 if (in_port == 0) 778 { 779 // Binding to port zero, we need to figure out what port it ends up 780 // using using a named pipe... 781 FileSpec tmpdir_file_spec; 782 if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec)) 783 { 784 tmpdir_file_spec.AppendPathComponent("debugserver-named-pipe.XXXXXX"); 785 strncpy(named_pipe_path, tmpdir_file_spec.GetPath().c_str(), sizeof(named_pipe_path)); 786 } 787 else 788 { 789 strncpy(named_pipe_path, "/tmp/debugserver-named-pipe.XXXXXX", sizeof(named_pipe_path)); 790 } 791 792 if (::mktemp (named_pipe_path)) 793 { 794 #if defined(_WIN32) 795 if ( false ) 796 #else 797 if (::mkfifo(named_pipe_path, 0600) == 0) 798 #endif 799 { 800 debugserver_args.AppendArgument("--named-pipe"); 801 debugserver_args.AppendArgument(named_pipe_path); 802 } 803 } 804 } 805 else 806 { 807 listen = true; 808 } 809 } 810 else 811 { 812 // No host and port given, so lets listen on our end and make the debugserver 813 // connect to us.. 814 error = StartListenThread ("127.0.0.1", 0); 815 if (error.Fail()) 816 return error; 817 818 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)GetConnection (); 819 // Wait for 10 seconds to resolve the bound port 820 out_port = connection->GetListeningPort(10); 821 if (out_port > 0) 822 { 823 char port_cstr[32]; 824 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", out_port); 825 // Send the host and port down that debugserver and specify an option 826 // so that it connects back to the port we are listening to in this process 827 debugserver_args.AppendArgument("--reverse-connect"); 828 debugserver_args.AppendArgument(port_cstr); 829 } 830 else 831 { 832 error.SetErrorString ("failed to bind to port 0 on 127.0.0.1"); 833 return error; 834 } 835 } 836 837 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE"); 838 if (env_debugserver_log_file) 839 { 840 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file); 841 debugserver_args.AppendArgument(arg_cstr); 842 } 843 844 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS"); 845 if (env_debugserver_log_flags) 846 { 847 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags); 848 debugserver_args.AppendArgument(arg_cstr); 849 } 850 851 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an env var doesn't come back. 852 uint32_t env_var_index = 1; 853 bool has_env_var; 854 do 855 { 856 char env_var_name[64]; 857 snprintf (env_var_name, sizeof (env_var_name), "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++); 858 const char *extra_arg = getenv(env_var_name); 859 has_env_var = extra_arg != nullptr; 860 861 if (has_env_var) 862 { 863 debugserver_args.AppendArgument (extra_arg); 864 if (log) 865 log->Printf ("GDBRemoteCommunication::%s adding env var %s contents to stub command line (%s)", __FUNCTION__, env_var_name, extra_arg); 866 } 867 } while (has_env_var); 868 869 // Close STDIN, STDOUT and STDERR. We might need to redirect them 870 // to "/dev/null" if we run into any problems. 871 launch_info.AppendCloseFileAction (STDIN_FILENO); 872 launch_info.AppendCloseFileAction (STDOUT_FILENO); 873 launch_info.AppendCloseFileAction (STDERR_FILENO); 874 875 error = Host::LaunchProcess(launch_info); 876 877 if (error.Success() && launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 878 { 879 if (named_pipe_path[0]) 880 { 881 File name_pipe_file; 882 error = name_pipe_file.Open(named_pipe_path, File::eOpenOptionRead); 883 if (error.Success()) 884 { 885 char port_cstr[256]; 886 port_cstr[0] = '\0'; 887 size_t num_bytes = sizeof(port_cstr); 888 error = name_pipe_file.Read(port_cstr, num_bytes); 889 assert (error.Success()); 890 assert (num_bytes > 0 && port_cstr[num_bytes-1] == '\0'); 891 out_port = Args::StringToUInt32(port_cstr, 0); 892 name_pipe_file.Close(); 893 } 894 FileSystem::Unlink(named_pipe_path); 895 } 896 else if (listen) 897 { 898 899 } 900 else 901 { 902 // Make sure we actually connect with the debugserver... 903 JoinListenThread(); 904 } 905 } 906 } 907 else 908 { 909 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME ); 910 } 911 return error; 912 } 913 914 void 915 GDBRemoteCommunication::DumpHistory(Stream &strm) 916 { 917 m_history.Dump (strm); 918 } 919