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