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