1 //===-- ConnectionFileDescriptorPosix.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 #if defined(__APPLE__) 11 // Enable this special support for Apple builds where we can have unlimited 12 // select bounds. We tried switching to poll() and kqueue and we were panicing 13 // the kernel, so we have to stick with select for now. 14 #define _DARWIN_UNLIMITED_SELECT 15 #endif 16 17 #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h" 18 #include "lldb/Host/Config.h" 19 #include "lldb/Host/Socket.h" 20 #include "lldb/Host/SocketAddress.h" 21 #include "lldb/Utility/SelectHelper.h" 22 #include "lldb/Utility/Timeout.h" 23 24 // C Includes 25 #include <errno.h> 26 #include <fcntl.h> 27 #include <stdlib.h> 28 #include <string.h> 29 #include <sys/types.h> 30 31 #ifndef LLDB_DISABLE_POSIX 32 #include <termios.h> 33 #endif 34 35 // C++ Includes 36 #include <sstream> 37 38 // Other libraries and framework includes 39 #include "llvm/Support/Errno.h" 40 #include "llvm/Support/ErrorHandling.h" 41 #if defined(__APPLE__) 42 #include "llvm/ADT/SmallVector.h" 43 #endif 44 // Project includes 45 #include "lldb/Host/Host.h" 46 #include "lldb/Host/Socket.h" 47 #include "lldb/Host/common/TCPSocket.h" 48 #include "lldb/Utility/Log.h" 49 #include "lldb/Utility/StreamString.h" 50 #include "lldb/Utility/Timer.h" 51 52 using namespace lldb; 53 using namespace lldb_private; 54 55 const char *ConnectionFileDescriptor::LISTEN_SCHEME = "listen"; 56 const char *ConnectionFileDescriptor::ACCEPT_SCHEME = "accept"; 57 const char *ConnectionFileDescriptor::UNIX_ACCEPT_SCHEME = "unix-accept"; 58 const char *ConnectionFileDescriptor::CONNECT_SCHEME = "connect"; 59 const char *ConnectionFileDescriptor::TCP_CONNECT_SCHEME = "tcp-connect"; 60 const char *ConnectionFileDescriptor::UDP_SCHEME = "udp"; 61 const char *ConnectionFileDescriptor::UNIX_CONNECT_SCHEME = "unix-connect"; 62 const char *ConnectionFileDescriptor::UNIX_ABSTRACT_CONNECT_SCHEME = 63 "unix-abstract-connect"; 64 const char *ConnectionFileDescriptor::FD_SCHEME = "fd"; 65 const char *ConnectionFileDescriptor::FILE_SCHEME = "file"; 66 67 namespace { 68 69 llvm::Optional<llvm::StringRef> GetURLAddress(llvm::StringRef url, 70 llvm::StringRef scheme) { 71 if (!url.consume_front(scheme)) 72 return llvm::None; 73 if (!url.consume_front("://")) 74 return llvm::None; 75 return url; 76 } 77 } 78 79 ConnectionFileDescriptor::ConnectionFileDescriptor(bool child_processes_inherit) 80 : Connection(), m_pipe(), m_mutex(), m_shutting_down(false), 81 m_waiting_for_accept(false), 82 m_child_processes_inherit(child_processes_inherit) { 83 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION | 84 LIBLLDB_LOG_OBJECT)); 85 if (log) 86 log->Printf("%p ConnectionFileDescriptor::ConnectionFileDescriptor ()", 87 static_cast<void *>(this)); 88 } 89 90 ConnectionFileDescriptor::ConnectionFileDescriptor(int fd, bool owns_fd) 91 : Connection(), m_pipe(), m_mutex(), m_shutting_down(false), 92 m_waiting_for_accept(false), m_child_processes_inherit(false) { 93 m_write_sp.reset(new File(fd, owns_fd)); 94 m_read_sp.reset(new File(fd, false)); 95 96 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION | 97 LIBLLDB_LOG_OBJECT)); 98 if (log) 99 log->Printf("%p ConnectionFileDescriptor::ConnectionFileDescriptor (fd = " 100 "%i, owns_fd = %i)", 101 static_cast<void *>(this), fd, owns_fd); 102 OpenCommandPipe(); 103 } 104 105 ConnectionFileDescriptor::ConnectionFileDescriptor(Socket *socket) 106 : Connection(), m_pipe(), m_mutex(), m_shutting_down(false), 107 m_waiting_for_accept(false), m_child_processes_inherit(false) { 108 InitializeSocket(socket); 109 } 110 111 ConnectionFileDescriptor::~ConnectionFileDescriptor() { 112 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION | 113 LIBLLDB_LOG_OBJECT)); 114 if (log) 115 log->Printf("%p ConnectionFileDescriptor::~ConnectionFileDescriptor ()", 116 static_cast<void *>(this)); 117 Disconnect(NULL); 118 CloseCommandPipe(); 119 } 120 121 void ConnectionFileDescriptor::OpenCommandPipe() { 122 CloseCommandPipe(); 123 124 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 125 // Make the command file descriptor here: 126 Status result = m_pipe.CreateNew(m_child_processes_inherit); 127 if (!result.Success()) { 128 if (log) 129 log->Printf("%p ConnectionFileDescriptor::OpenCommandPipe () - could not " 130 "make pipe: %s", 131 static_cast<void *>(this), result.AsCString()); 132 } else { 133 if (log) 134 log->Printf("%p ConnectionFileDescriptor::OpenCommandPipe() - success " 135 "readfd=%d writefd=%d", 136 static_cast<void *>(this), m_pipe.GetReadFileDescriptor(), 137 m_pipe.GetWriteFileDescriptor()); 138 } 139 } 140 141 void ConnectionFileDescriptor::CloseCommandPipe() { 142 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 143 if (log) 144 log->Printf("%p ConnectionFileDescriptor::CloseCommandPipe()", 145 static_cast<void *>(this)); 146 147 m_pipe.Close(); 148 } 149 150 bool ConnectionFileDescriptor::IsConnected() const { 151 return (m_read_sp && m_read_sp->IsValid()) || 152 (m_write_sp && m_write_sp->IsValid()); 153 } 154 155 ConnectionStatus ConnectionFileDescriptor::Connect(llvm::StringRef path, 156 Status *error_ptr) { 157 std::lock_guard<std::recursive_mutex> guard(m_mutex); 158 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 159 if (log) 160 log->Printf("%p ConnectionFileDescriptor::Connect (url = '%s')", 161 static_cast<void *>(this), path.str().c_str()); 162 163 OpenCommandPipe(); 164 165 if (!path.empty()) { 166 llvm::Optional<llvm::StringRef> addr; 167 if ((addr = GetURLAddress(path, LISTEN_SCHEME))) { 168 // listen://HOST:PORT 169 return SocketListenAndAccept(*addr, error_ptr); 170 } else if ((addr = GetURLAddress(path, ACCEPT_SCHEME))) { 171 // unix://SOCKNAME 172 return NamedSocketAccept(*addr, error_ptr); 173 } else if ((addr = GetURLAddress(path, UNIX_ACCEPT_SCHEME))) { 174 // unix://SOCKNAME 175 return NamedSocketAccept(*addr, error_ptr); 176 } else if ((addr = GetURLAddress(path, CONNECT_SCHEME))) { 177 return ConnectTCP(*addr, error_ptr); 178 } else if ((addr = GetURLAddress(path, TCP_CONNECT_SCHEME))) { 179 return ConnectTCP(*addr, error_ptr); 180 } else if ((addr = GetURLAddress(path, UDP_SCHEME))) { 181 return ConnectUDP(*addr, error_ptr); 182 } else if ((addr = GetURLAddress(path, UNIX_CONNECT_SCHEME))) { 183 // unix-connect://SOCKNAME 184 return NamedSocketConnect(*addr, error_ptr); 185 } else if ((addr = GetURLAddress(path, UNIX_ABSTRACT_CONNECT_SCHEME))) { 186 // unix-abstract-connect://SOCKNAME 187 return UnixAbstractSocketConnect(*addr, error_ptr); 188 } 189 #ifndef LLDB_DISABLE_POSIX 190 else if ((addr = GetURLAddress(path, FD_SCHEME))) { 191 // Just passing a native file descriptor within this current process 192 // that is already opened (possibly from a service or other source). 193 int fd = -1; 194 195 if (!addr->getAsInteger(0, fd)) { 196 // We have what looks to be a valid file descriptor, but we 197 // should make sure it is. We currently are doing this by trying to 198 // get the flags from the file descriptor and making sure it 199 // isn't a bad fd. 200 errno = 0; 201 int flags = ::fcntl(fd, F_GETFL, 0); 202 if (flags == -1 || errno == EBADF) { 203 if (error_ptr) 204 error_ptr->SetErrorStringWithFormat("stale file descriptor: %s", 205 path.str().c_str()); 206 m_read_sp.reset(); 207 m_write_sp.reset(); 208 return eConnectionStatusError; 209 } else { 210 // Don't take ownership of a file descriptor that gets passed 211 // to us since someone else opened the file descriptor and 212 // handed it to us. 213 // TODO: Since are using a URL to open connection we should 214 // eventually parse options using the web standard where we 215 // have "fd://123?opt1=value;opt2=value" and we can have an 216 // option be "owns=1" or "owns=0" or something like this to 217 // allow us to specify this. For now, we assume we must 218 // assume we don't own it. 219 220 std::unique_ptr<TCPSocket> tcp_socket; 221 tcp_socket.reset(new TCPSocket(fd, false, false)); 222 // Try and get a socket option from this file descriptor to 223 // see if this is a socket and set m_is_socket accordingly. 224 int resuse; 225 bool is_socket = 226 !!tcp_socket->GetOption(SOL_SOCKET, SO_REUSEADDR, resuse); 227 if (is_socket) { 228 m_read_sp = std::move(tcp_socket); 229 m_write_sp = m_read_sp; 230 } else { 231 m_read_sp.reset(new File(fd, false)); 232 m_write_sp.reset(new File(fd, false)); 233 } 234 m_uri = *addr; 235 return eConnectionStatusSuccess; 236 } 237 } 238 239 if (error_ptr) 240 error_ptr->SetErrorStringWithFormat("invalid file descriptor: \"%s\"", 241 path.str().c_str()); 242 m_read_sp.reset(); 243 m_write_sp.reset(); 244 return eConnectionStatusError; 245 } else if ((addr = GetURLAddress(path, FILE_SCHEME))) { 246 std::string addr_str = addr->str(); 247 // file:///PATH 248 int fd = llvm::sys::RetryAfterSignal(-1, ::open, addr_str.c_str(), O_RDWR); 249 if (fd == -1) { 250 if (error_ptr) 251 error_ptr->SetErrorToErrno(); 252 return eConnectionStatusError; 253 } 254 255 if (::isatty(fd)) { 256 // Set up serial terminal emulation 257 struct termios options; 258 ::tcgetattr(fd, &options); 259 260 // Set port speed to maximum 261 ::cfsetospeed(&options, B115200); 262 ::cfsetispeed(&options, B115200); 263 264 // Raw input, disable echo and signals 265 options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); 266 267 // Make sure only one character is needed to return from a read 268 options.c_cc[VMIN] = 1; 269 options.c_cc[VTIME] = 0; 270 271 ::tcsetattr(fd, TCSANOW, &options); 272 } 273 274 int flags = ::fcntl(fd, F_GETFL, 0); 275 if (flags >= 0) { 276 if ((flags & O_NONBLOCK) == 0) { 277 flags |= O_NONBLOCK; 278 ::fcntl(fd, F_SETFL, flags); 279 } 280 } 281 m_read_sp.reset(new File(fd, true)); 282 m_write_sp.reset(new File(fd, false)); 283 return eConnectionStatusSuccess; 284 } 285 #endif 286 if (error_ptr) 287 error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'", 288 path.str().c_str()); 289 return eConnectionStatusError; 290 } 291 if (error_ptr) 292 error_ptr->SetErrorString("invalid connect arguments"); 293 return eConnectionStatusError; 294 } 295 296 bool ConnectionFileDescriptor::InterruptRead() { 297 size_t bytes_written = 0; 298 Status result = m_pipe.Write("i", 1, bytes_written); 299 return result.Success(); 300 } 301 302 ConnectionStatus ConnectionFileDescriptor::Disconnect(Status *error_ptr) { 303 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 304 if (log) 305 log->Printf("%p ConnectionFileDescriptor::Disconnect ()", 306 static_cast<void *>(this)); 307 308 ConnectionStatus status = eConnectionStatusSuccess; 309 310 if (!IsConnected()) { 311 if (log) 312 log->Printf( 313 "%p ConnectionFileDescriptor::Disconnect(): Nothing to disconnect", 314 static_cast<void *>(this)); 315 return eConnectionStatusSuccess; 316 } 317 318 if (m_read_sp && m_read_sp->IsValid() && 319 m_read_sp->GetFdType() == IOObject::eFDTypeSocket) 320 static_cast<Socket &>(*m_read_sp).PreDisconnect(); 321 322 // Try to get the ConnectionFileDescriptor's mutex. If we fail, that is quite 323 // likely 324 // because somebody is doing a blocking read on our file descriptor. If 325 // that's the case, 326 // then send the "q" char to the command file channel so the read will wake up 327 // and the connection 328 // will then know to shut down. 329 330 m_shutting_down = true; 331 332 std::unique_lock<std::recursive_mutex> locker(m_mutex, std::defer_lock); 333 if (!locker.try_lock()) { 334 if (m_pipe.CanWrite()) { 335 size_t bytes_written = 0; 336 Status result = m_pipe.Write("q", 1, bytes_written); 337 if (log) 338 log->Printf("%p ConnectionFileDescriptor::Disconnect(): Couldn't get " 339 "the lock, sent 'q' to %d, error = '%s'.", 340 static_cast<void *>(this), m_pipe.GetWriteFileDescriptor(), 341 result.AsCString()); 342 } else if (log) { 343 log->Printf("%p ConnectionFileDescriptor::Disconnect(): Couldn't get the " 344 "lock, but no command pipe is available.", 345 static_cast<void *>(this)); 346 } 347 locker.lock(); 348 } 349 350 Status error = m_read_sp->Close(); 351 Status error2 = m_write_sp->Close(); 352 if (error.Fail() || error2.Fail()) 353 status = eConnectionStatusError; 354 if (error_ptr) 355 *error_ptr = error.Fail() ? error : error2; 356 357 // Close any pipes we were using for async interrupts 358 m_pipe.Close(); 359 360 m_uri.clear(); 361 m_shutting_down = false; 362 return status; 363 } 364 365 size_t ConnectionFileDescriptor::Read(void *dst, size_t dst_len, 366 const Timeout<std::micro> &timeout, 367 ConnectionStatus &status, 368 Status *error_ptr) { 369 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 370 371 std::unique_lock<std::recursive_mutex> locker(m_mutex, std::defer_lock); 372 if (!locker.try_lock()) { 373 if (log) 374 log->Printf("%p ConnectionFileDescriptor::Read () failed to get the " 375 "connection lock.", 376 static_cast<void *>(this)); 377 if (error_ptr) 378 error_ptr->SetErrorString("failed to get the connection lock for read."); 379 380 status = eConnectionStatusTimedOut; 381 return 0; 382 } 383 384 if (m_shutting_down) { 385 status = eConnectionStatusError; 386 return 0; 387 } 388 389 status = BytesAvailable(timeout, error_ptr); 390 if (status != eConnectionStatusSuccess) 391 return 0; 392 393 Status error; 394 size_t bytes_read = dst_len; 395 error = m_read_sp->Read(dst, bytes_read); 396 397 if (log) { 398 log->Printf("%p ConnectionFileDescriptor::Read() fd = %" PRIu64 399 ", dst = %p, dst_len = %" PRIu64 ") => %" PRIu64 ", error = %s", 400 static_cast<void *>(this), 401 static_cast<uint64_t>(m_read_sp->GetWaitableHandle()), 402 static_cast<void *>(dst), static_cast<uint64_t>(dst_len), 403 static_cast<uint64_t>(bytes_read), error.AsCString()); 404 } 405 406 if (bytes_read == 0) { 407 error.Clear(); // End-of-file. Do not automatically close; pass along for 408 // the end-of-file handlers. 409 status = eConnectionStatusEndOfFile; 410 } 411 412 if (error_ptr) 413 *error_ptr = error; 414 415 if (error.Fail()) { 416 uint32_t error_value = error.GetError(); 417 switch (error_value) { 418 case EAGAIN: // The file was marked for non-blocking I/O, and no data were 419 // ready to be read. 420 if (m_read_sp->GetFdType() == IOObject::eFDTypeSocket) 421 status = eConnectionStatusTimedOut; 422 else 423 status = eConnectionStatusSuccess; 424 return 0; 425 426 case EFAULT: // Buf points outside the allocated address space. 427 case EINTR: // A read from a slow device was interrupted before any data 428 // arrived by the delivery of a signal. 429 case EINVAL: // The pointer associated with fildes was negative. 430 case EIO: // An I/O error occurred while reading from the file system. 431 // The process group is orphaned. 432 // The file is a regular file, nbyte is greater than 0, 433 // the starting position is before the end-of-file, and 434 // the starting position is greater than or equal to the 435 // offset maximum established for the open file 436 // descriptor associated with fildes. 437 case EISDIR: // An attempt is made to read a directory. 438 case ENOBUFS: // An attempt to allocate a memory buffer fails. 439 case ENOMEM: // Insufficient memory is available. 440 status = eConnectionStatusError; 441 break; // Break to close.... 442 443 case ENOENT: // no such file or directory 444 case EBADF: // fildes is not a valid file or socket descriptor open for 445 // reading. 446 case ENXIO: // An action is requested of a device that does not exist.. 447 // A requested action cannot be performed by the device. 448 case ECONNRESET: // The connection is closed by the peer during a read 449 // attempt on a socket. 450 case ENOTCONN: // A read is attempted on an unconnected socket. 451 status = eConnectionStatusLostConnection; 452 break; // Break to close.... 453 454 case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a 455 // socket. 456 status = eConnectionStatusTimedOut; 457 return 0; 458 459 default: 460 LLDB_LOG(log, "this = {0}, unexpected error: {1}", this, 461 llvm::sys::StrError(error_value)); 462 status = eConnectionStatusError; 463 break; // Break to close.... 464 } 465 466 return 0; 467 } 468 return bytes_read; 469 } 470 471 size_t ConnectionFileDescriptor::Write(const void *src, size_t src_len, 472 ConnectionStatus &status, 473 Status *error_ptr) { 474 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 475 if (log) 476 log->Printf( 477 "%p ConnectionFileDescriptor::Write (src = %p, src_len = %" PRIu64 ")", 478 static_cast<void *>(this), static_cast<const void *>(src), 479 static_cast<uint64_t>(src_len)); 480 481 if (!IsConnected()) { 482 if (error_ptr) 483 error_ptr->SetErrorString("not connected"); 484 status = eConnectionStatusNoConnection; 485 return 0; 486 } 487 488 Status error; 489 490 size_t bytes_sent = src_len; 491 error = m_write_sp->Write(src, bytes_sent); 492 493 if (log) { 494 log->Printf("%p ConnectionFileDescriptor::Write(fd = %" PRIu64 495 ", src = %p, src_len = %" PRIu64 ") => %" PRIu64 496 " (error = %s)", 497 static_cast<void *>(this), 498 static_cast<uint64_t>(m_write_sp->GetWaitableHandle()), 499 static_cast<const void *>(src), static_cast<uint64_t>(src_len), 500 static_cast<uint64_t>(bytes_sent), error.AsCString()); 501 } 502 503 if (error_ptr) 504 *error_ptr = error; 505 506 if (error.Fail()) { 507 switch (error.GetError()) { 508 case EAGAIN: 509 case EINTR: 510 status = eConnectionStatusSuccess; 511 return 0; 512 513 case ECONNRESET: // The connection is closed by the peer during a read 514 // attempt on a socket. 515 case ENOTCONN: // A read is attempted on an unconnected socket. 516 status = eConnectionStatusLostConnection; 517 break; // Break to close.... 518 519 default: 520 status = eConnectionStatusError; 521 break; // Break to close.... 522 } 523 524 return 0; 525 } 526 527 status = eConnectionStatusSuccess; 528 return bytes_sent; 529 } 530 531 std::string ConnectionFileDescriptor::GetURI() { return m_uri; } 532 533 // This ConnectionFileDescriptor::BytesAvailable() uses select() via 534 // SelectHelper 535 // 536 // PROS: 537 // - select is consistent across most unix platforms 538 // - The Apple specific version allows for unlimited fds in the fd_sets by 539 // setting the _DARWIN_UNLIMITED_SELECT define prior to including the 540 // required header files. 541 // CONS: 542 // - on non-Apple platforms, only supports file descriptors up to FD_SETSIZE. 543 // This implementation will assert if it runs into that hard limit to let 544 // users know that another ConnectionFileDescriptor::BytesAvailable() should 545 // be used or a new version of ConnectionFileDescriptor::BytesAvailable() 546 // should be written for the system that is running into the limitations. 547 548 ConnectionStatus 549 ConnectionFileDescriptor::BytesAvailable(const Timeout<std::micro> &timeout, 550 Status *error_ptr) { 551 // Don't need to take the mutex here separately since we are only called from 552 // Read. If we 553 // ever get used more generally we will need to lock here as well. 554 555 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_CONNECTION)); 556 LLDB_LOG(log, "this = {0}, timeout = {1}", this, timeout); 557 558 // Make a copy of the file descriptors to make sure we don't 559 // have another thread change these values out from under us 560 // and cause problems in the loop below where like in FS_SET() 561 const IOObject::WaitableHandle handle = m_read_sp->GetWaitableHandle(); 562 const int pipe_fd = m_pipe.GetReadFileDescriptor(); 563 564 if (handle != IOObject::kInvalidHandleValue) { 565 SelectHelper select_helper; 566 if (timeout) 567 select_helper.SetTimeout(*timeout); 568 569 select_helper.FDSetRead(handle); 570 #if defined(_MSC_VER) 571 // select() won't accept pipes on Windows. The entire Windows codepath 572 // needs to be 573 // converted over to using WaitForMultipleObjects and event HANDLEs, but for 574 // now at least 575 // this will allow ::select() to not return an error. 576 const bool have_pipe_fd = false; 577 #else 578 const bool have_pipe_fd = pipe_fd >= 0; 579 #endif 580 if (have_pipe_fd) 581 select_helper.FDSetRead(pipe_fd); 582 583 while (handle == m_read_sp->GetWaitableHandle()) { 584 585 Status error = select_helper.Select(); 586 587 if (error_ptr) 588 *error_ptr = error; 589 590 if (error.Fail()) { 591 switch (error.GetError()) { 592 case EBADF: // One of the descriptor sets specified an invalid 593 // descriptor. 594 return eConnectionStatusLostConnection; 595 596 case EINVAL: // The specified time limit is invalid. One of its 597 // components is negative or too large. 598 default: // Other unknown error 599 return eConnectionStatusError; 600 601 case ETIMEDOUT: 602 return eConnectionStatusTimedOut; 603 604 case EAGAIN: // The kernel was (perhaps temporarily) unable to 605 // allocate the requested number of file descriptors, 606 // or we have non-blocking IO 607 case EINTR: // A signal was delivered before the time limit 608 // expired and before any of the selected events 609 // occurred. 610 break; // Lets keep reading to until we timeout 611 } 612 } else { 613 if (select_helper.FDIsSetRead(handle)) 614 return eConnectionStatusSuccess; 615 616 if (select_helper.FDIsSetRead(pipe_fd)) { 617 // There is an interrupt or exit command in the command pipe 618 // Read the data from that pipe: 619 char c; 620 621 ssize_t bytes_read = llvm::sys::RetryAfterSignal(-1, ::read, pipe_fd, &c, 1); 622 assert(bytes_read == 1); 623 (void)bytes_read; 624 switch (c) { 625 case 'q': 626 if (log) 627 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() " 628 "got data: %c from the command channel.", 629 static_cast<void *>(this), c); 630 return eConnectionStatusEndOfFile; 631 case 'i': 632 // Interrupt the current read 633 return eConnectionStatusInterrupted; 634 } 635 } 636 } 637 } 638 } 639 640 if (error_ptr) 641 error_ptr->SetErrorString("not connected"); 642 return eConnectionStatusLostConnection; 643 } 644 645 ConnectionStatus 646 ConnectionFileDescriptor::NamedSocketAccept(llvm::StringRef socket_name, 647 Status *error_ptr) { 648 Socket *socket = nullptr; 649 Status error = 650 Socket::UnixDomainAccept(socket_name, m_child_processes_inherit, socket); 651 if (error_ptr) 652 *error_ptr = error; 653 m_write_sp.reset(socket); 654 m_read_sp = m_write_sp; 655 if (error.Fail()) { 656 return eConnectionStatusError; 657 } 658 m_uri.assign(socket_name); 659 return eConnectionStatusSuccess; 660 } 661 662 ConnectionStatus 663 ConnectionFileDescriptor::NamedSocketConnect(llvm::StringRef socket_name, 664 Status *error_ptr) { 665 Socket *socket = nullptr; 666 Status error = 667 Socket::UnixDomainConnect(socket_name, m_child_processes_inherit, socket); 668 if (error_ptr) 669 *error_ptr = error; 670 m_write_sp.reset(socket); 671 m_read_sp = m_write_sp; 672 if (error.Fail()) { 673 return eConnectionStatusError; 674 } 675 m_uri.assign(socket_name); 676 return eConnectionStatusSuccess; 677 } 678 679 lldb::ConnectionStatus 680 ConnectionFileDescriptor::UnixAbstractSocketConnect(llvm::StringRef socket_name, 681 Status *error_ptr) { 682 Socket *socket = nullptr; 683 Status error = Socket::UnixAbstractConnect(socket_name, 684 m_child_processes_inherit, socket); 685 if (error_ptr) 686 *error_ptr = error; 687 m_write_sp.reset(socket); 688 m_read_sp = m_write_sp; 689 if (error.Fail()) { 690 return eConnectionStatusError; 691 } 692 m_uri.assign(socket_name); 693 return eConnectionStatusSuccess; 694 } 695 696 ConnectionStatus 697 ConnectionFileDescriptor::SocketListenAndAccept(llvm::StringRef s, 698 Status *error_ptr) { 699 m_port_predicate.SetValue(0, eBroadcastNever); 700 701 Socket *socket = nullptr; 702 m_waiting_for_accept = true; 703 Status error = Socket::TcpListen(s, m_child_processes_inherit, socket, 704 &m_port_predicate); 705 if (error_ptr) 706 *error_ptr = error; 707 if (error.Fail()) 708 return eConnectionStatusError; 709 710 std::unique_ptr<Socket> listening_socket_up; 711 712 listening_socket_up.reset(socket); 713 socket = nullptr; 714 error = listening_socket_up->Accept(socket); 715 listening_socket_up.reset(); 716 if (error_ptr) 717 *error_ptr = error; 718 if (error.Fail()) 719 return eConnectionStatusError; 720 721 InitializeSocket(socket); 722 return eConnectionStatusSuccess; 723 } 724 725 ConnectionStatus ConnectionFileDescriptor::ConnectTCP(llvm::StringRef s, 726 Status *error_ptr) { 727 Socket *socket = nullptr; 728 Status error = Socket::TcpConnect(s, m_child_processes_inherit, socket); 729 if (error_ptr) 730 *error_ptr = error; 731 m_write_sp.reset(socket); 732 m_read_sp = m_write_sp; 733 if (error.Fail()) { 734 return eConnectionStatusError; 735 } 736 m_uri.assign(s); 737 return eConnectionStatusSuccess; 738 } 739 740 ConnectionStatus ConnectionFileDescriptor::ConnectUDP(llvm::StringRef s, 741 Status *error_ptr) { 742 Socket *socket = nullptr; 743 Status error = Socket::UdpConnect(s, m_child_processes_inherit, socket); 744 if (error_ptr) 745 *error_ptr = error; 746 m_write_sp.reset(socket); 747 m_read_sp = m_write_sp; 748 if (error.Fail()) { 749 return eConnectionStatusError; 750 } 751 m_uri.assign(s); 752 return eConnectionStatusSuccess; 753 } 754 755 uint16_t ConnectionFileDescriptor::GetListeningPort(uint32_t timeout_sec) { 756 uint16_t bound_port = 0; 757 if (timeout_sec == UINT32_MAX) 758 m_port_predicate.WaitForValueNotEqualTo(0, bound_port); 759 else 760 m_port_predicate.WaitForValueNotEqualTo(0, bound_port, 761 std::chrono::seconds(timeout_sec)); 762 return bound_port; 763 } 764 765 bool ConnectionFileDescriptor::GetChildProcessesInherit() const { 766 return m_child_processes_inherit; 767 } 768 769 void ConnectionFileDescriptor::SetChildProcessesInherit( 770 bool child_processes_inherit) { 771 m_child_processes_inherit = child_processes_inherit; 772 } 773 774 void ConnectionFileDescriptor::InitializeSocket(Socket *socket) { 775 assert(socket->GetSocketProtocol() == Socket::ProtocolTcp); 776 TCPSocket *tcp_socket = static_cast<TCPSocket *>(socket); 777 778 m_write_sp.reset(socket); 779 m_read_sp = m_write_sp; 780 StreamString strm; 781 strm.Printf("connect://%s:%u", tcp_socket->GetRemoteIPAddress().c_str(), 782 tcp_socket->GetRemotePortNumber()); 783 m_uri = strm.GetString(); 784 } 785