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 std::unique_lock<std::recursive_mutex> locker(m_mutex, std::defer_lock); 316 if (!locker.try_lock()) { 317 if (m_pipe.CanWrite()) { 318 size_t bytes_written = 0; 319 Status result = m_pipe.Write("q", 1, bytes_written); 320 LLDB_LOGF(log, 321 "%p ConnectionFileDescriptor::Disconnect(): Couldn't get " 322 "the lock, sent 'q' to %d, error = '%s'.", 323 static_cast<void *>(this), m_pipe.GetWriteFileDescriptor(), 324 result.AsCString()); 325 } else if (log) { 326 LLDB_LOGF(log, 327 "%p ConnectionFileDescriptor::Disconnect(): Couldn't get the " 328 "lock, but no command pipe is available.", 329 static_cast<void *>(this)); 330 } 331 locker.lock(); 332 } 333 334 // Prevents reads and writes during shutdown. 335 m_shutting_down = true; 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 if (error_ptr) 373 error_ptr->SetErrorString("shutting down"); 374 status = eConnectionStatusError; 375 return 0; 376 } 377 378 status = BytesAvailable(timeout, error_ptr); 379 if (status != eConnectionStatusSuccess) 380 return 0; 381 382 Status error; 383 size_t bytes_read = dst_len; 384 error = m_read_sp->Read(dst, bytes_read); 385 386 if (log) { 387 LLDB_LOGF(log, 388 "%p ConnectionFileDescriptor::Read() fd = %" PRIu64 389 ", dst = %p, dst_len = %" PRIu64 ") => %" PRIu64 ", error = %s", 390 static_cast<void *>(this), 391 static_cast<uint64_t>(m_read_sp->GetWaitableHandle()), 392 static_cast<void *>(dst), static_cast<uint64_t>(dst_len), 393 static_cast<uint64_t>(bytes_read), error.AsCString()); 394 } 395 396 if (bytes_read == 0) { 397 error.Clear(); // End-of-file. Do not automatically close; pass along for 398 // the end-of-file handlers. 399 status = eConnectionStatusEndOfFile; 400 } 401 402 if (error_ptr) 403 *error_ptr = error; 404 405 if (error.Fail()) { 406 uint32_t error_value = error.GetError(); 407 switch (error_value) { 408 case EAGAIN: // The file was marked for non-blocking I/O, and no data were 409 // ready to be read. 410 if (m_read_sp->GetFdType() == IOObject::eFDTypeSocket) 411 status = eConnectionStatusTimedOut; 412 else 413 status = eConnectionStatusSuccess; 414 return 0; 415 416 case EFAULT: // Buf points outside the allocated address space. 417 case EINTR: // A read from a slow device was interrupted before any data 418 // arrived by the delivery of a signal. 419 case EINVAL: // The pointer associated with fildes was negative. 420 case EIO: // An I/O error occurred while reading from the file system. 421 // The process group is orphaned. 422 // The file is a regular file, nbyte is greater than 0, the 423 // starting position is before the end-of-file, and the 424 // starting position is greater than or equal to the offset 425 // maximum established for the open file descriptor 426 // associated with fildes. 427 case EISDIR: // An attempt is made to read a directory. 428 case ENOBUFS: // An attempt to allocate a memory buffer fails. 429 case ENOMEM: // Insufficient memory is available. 430 status = eConnectionStatusError; 431 break; // Break to close.... 432 433 case ENOENT: // no such file or directory 434 case EBADF: // fildes is not a valid file or socket descriptor open for 435 // reading. 436 case ENXIO: // An action is requested of a device that does not exist.. 437 // A requested action cannot be performed by the device. 438 case ECONNRESET: // The connection is closed by the peer during a read 439 // attempt on a socket. 440 case ENOTCONN: // A read is attempted on an unconnected socket. 441 status = eConnectionStatusLostConnection; 442 break; // Break to close.... 443 444 case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a 445 // socket. 446 status = eConnectionStatusTimedOut; 447 return 0; 448 449 default: 450 LLDB_LOG(log, "this = {0}, unexpected error: {1}", this, 451 llvm::sys::StrError(error_value)); 452 status = eConnectionStatusError; 453 break; // Break to close.... 454 } 455 456 return 0; 457 } 458 return bytes_read; 459 } 460 461 size_t ConnectionFileDescriptor::Write(const void *src, size_t src_len, 462 ConnectionStatus &status, 463 Status *error_ptr) { 464 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 465 LLDB_LOGF(log, 466 "%p ConnectionFileDescriptor::Write (src = %p, src_len = %" PRIu64 467 ")", 468 static_cast<void *>(this), static_cast<const void *>(src), 469 static_cast<uint64_t>(src_len)); 470 471 if (!IsConnected()) { 472 if (error_ptr) 473 error_ptr->SetErrorString("not connected"); 474 status = eConnectionStatusNoConnection; 475 return 0; 476 } 477 478 if (m_shutting_down) { 479 if (error_ptr) 480 error_ptr->SetErrorString("shutting down"); 481 status = eConnectionStatusError; 482 return 0; 483 } 484 485 Status error; 486 487 size_t bytes_sent = src_len; 488 error = m_write_sp->Write(src, bytes_sent); 489 490 if (log) { 491 LLDB_LOGF(log, 492 "%p ConnectionFileDescriptor::Write(fd = %" PRIu64 493 ", src = %p, src_len = %" PRIu64 ") => %" PRIu64 " (error = %s)", 494 static_cast<void *>(this), 495 static_cast<uint64_t>(m_write_sp->GetWaitableHandle()), 496 static_cast<const void *>(src), static_cast<uint64_t>(src_len), 497 static_cast<uint64_t>(bytes_sent), error.AsCString()); 498 } 499 500 if (error_ptr) 501 *error_ptr = error; 502 503 if (error.Fail()) { 504 switch (error.GetError()) { 505 case EAGAIN: 506 case EINTR: 507 status = eConnectionStatusSuccess; 508 return 0; 509 510 case ECONNRESET: // The connection is closed by the peer during a read 511 // attempt on a socket. 512 case ENOTCONN: // A read is attempted on an unconnected socket. 513 status = eConnectionStatusLostConnection; 514 break; // Break to close.... 515 516 default: 517 status = eConnectionStatusError; 518 break; // Break to close.... 519 } 520 521 return 0; 522 } 523 524 status = eConnectionStatusSuccess; 525 return bytes_sent; 526 } 527 528 std::string ConnectionFileDescriptor::GetURI() { return m_uri; } 529 530 // This ConnectionFileDescriptor::BytesAvailable() uses select() via 531 // SelectHelper 532 // 533 // PROS: 534 // - select is consistent across most unix platforms 535 // - The Apple specific version allows for unlimited fds in the fd_sets by 536 // setting the _DARWIN_UNLIMITED_SELECT define prior to including the 537 // required header files. 538 // CONS: 539 // - on non-Apple platforms, only supports file descriptors up to FD_SETSIZE. 540 // This implementation will assert if it runs into that hard limit to let 541 // users know that another ConnectionFileDescriptor::BytesAvailable() should 542 // be used or a new version of ConnectionFileDescriptor::BytesAvailable() 543 // should be written for the system that is running into the limitations. 544 545 ConnectionStatus 546 ConnectionFileDescriptor::BytesAvailable(const Timeout<std::micro> &timeout, 547 Status *error_ptr) { 548 // Don't need to take the mutex here separately since we are only called from 549 // Read. If we ever get used more generally we will need to lock here as 550 // well. 551 552 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_CONNECTION)); 553 LLDB_LOG(log, "this = {0}, timeout = {1}", this, timeout); 554 555 // Make a copy of the file descriptors to make sure we don't have another 556 // thread change these values out from under us and cause problems in the 557 // loop below where like in FS_SET() 558 const IOObject::WaitableHandle handle = m_read_sp->GetWaitableHandle(); 559 const int pipe_fd = m_pipe.GetReadFileDescriptor(); 560 561 if (handle != IOObject::kInvalidHandleValue) { 562 SelectHelper select_helper; 563 if (timeout) 564 select_helper.SetTimeout(*timeout); 565 566 select_helper.FDSetRead(handle); 567 #if defined(_WIN32) 568 // select() won't accept pipes on Windows. The entire Windows codepath 569 // needs to be converted over to using WaitForMultipleObjects and event 570 // HANDLEs, but for now at least this will allow ::select() to not return 571 // an error. 572 const bool have_pipe_fd = false; 573 #else 574 const bool have_pipe_fd = pipe_fd >= 0; 575 #endif 576 if (have_pipe_fd) 577 select_helper.FDSetRead(pipe_fd); 578 579 while (handle == m_read_sp->GetWaitableHandle()) { 580 581 Status error = select_helper.Select(); 582 583 if (error_ptr) 584 *error_ptr = error; 585 586 if (error.Fail()) { 587 switch (error.GetError()) { 588 case EBADF: // One of the descriptor sets specified an invalid 589 // descriptor. 590 return eConnectionStatusLostConnection; 591 592 case EINVAL: // The specified time limit is invalid. One of its 593 // components is negative or too large. 594 default: // Other unknown error 595 return eConnectionStatusError; 596 597 case ETIMEDOUT: 598 return eConnectionStatusTimedOut; 599 600 case EAGAIN: // The kernel was (perhaps temporarily) unable to 601 // allocate the requested number of file descriptors, or 602 // we have non-blocking IO 603 case EINTR: // A signal was delivered before the time limit 604 // expired and before any of the selected events occurred. 605 break; // Lets keep reading to until we timeout 606 } 607 } else { 608 if (select_helper.FDIsSetRead(handle)) 609 return eConnectionStatusSuccess; 610 611 if (select_helper.FDIsSetRead(pipe_fd)) { 612 // There is an interrupt or exit command in the command pipe Read the 613 // data from that pipe: 614 char c; 615 616 ssize_t bytes_read = llvm::sys::RetryAfterSignal(-1, ::read, pipe_fd, &c, 1); 617 assert(bytes_read == 1); 618 (void)bytes_read; 619 switch (c) { 620 case 'q': 621 LLDB_LOGF(log, 622 "%p ConnectionFileDescriptor::BytesAvailable() " 623 "got data: %c from the command channel.", 624 static_cast<void *>(this), c); 625 return eConnectionStatusEndOfFile; 626 case 'i': 627 // Interrupt the current read 628 return eConnectionStatusInterrupted; 629 } 630 } 631 } 632 } 633 } 634 635 if (error_ptr) 636 error_ptr->SetErrorString("not connected"); 637 return eConnectionStatusLostConnection; 638 } 639 640 ConnectionStatus 641 ConnectionFileDescriptor::NamedSocketAccept(llvm::StringRef socket_name, 642 Status *error_ptr) { 643 Socket *socket = nullptr; 644 Status error = 645 Socket::UnixDomainAccept(socket_name, m_child_processes_inherit, socket); 646 if (error_ptr) 647 *error_ptr = error; 648 m_write_sp.reset(socket); 649 m_read_sp = m_write_sp; 650 if (error.Fail()) { 651 return eConnectionStatusError; 652 } 653 m_uri.assign(socket_name); 654 return eConnectionStatusSuccess; 655 } 656 657 ConnectionStatus 658 ConnectionFileDescriptor::NamedSocketConnect(llvm::StringRef socket_name, 659 Status *error_ptr) { 660 Socket *socket = nullptr; 661 Status error = 662 Socket::UnixDomainConnect(socket_name, m_child_processes_inherit, socket); 663 if (error_ptr) 664 *error_ptr = error; 665 m_write_sp.reset(socket); 666 m_read_sp = m_write_sp; 667 if (error.Fail()) { 668 return eConnectionStatusError; 669 } 670 m_uri.assign(socket_name); 671 return eConnectionStatusSuccess; 672 } 673 674 lldb::ConnectionStatus 675 ConnectionFileDescriptor::UnixAbstractSocketConnect(llvm::StringRef socket_name, 676 Status *error_ptr) { 677 Socket *socket = nullptr; 678 Status error = Socket::UnixAbstractConnect(socket_name, 679 m_child_processes_inherit, socket); 680 if (error_ptr) 681 *error_ptr = error; 682 m_write_sp.reset(socket); 683 m_read_sp = m_write_sp; 684 if (error.Fail()) { 685 return eConnectionStatusError; 686 } 687 m_uri.assign(socket_name); 688 return eConnectionStatusSuccess; 689 } 690 691 ConnectionStatus 692 ConnectionFileDescriptor::SocketListenAndAccept(llvm::StringRef s, 693 Status *error_ptr) { 694 m_port_predicate.SetValue(0, eBroadcastNever); 695 696 Socket *socket = nullptr; 697 m_waiting_for_accept = true; 698 Status error = Socket::TcpListen(s, m_child_processes_inherit, socket, 699 &m_port_predicate); 700 if (error_ptr) 701 *error_ptr = error; 702 if (error.Fail()) 703 return eConnectionStatusError; 704 705 std::unique_ptr<Socket> listening_socket_up; 706 707 listening_socket_up.reset(socket); 708 socket = nullptr; 709 error = listening_socket_up->Accept(socket); 710 listening_socket_up.reset(); 711 if (error_ptr) 712 *error_ptr = error; 713 if (error.Fail()) 714 return eConnectionStatusError; 715 716 InitializeSocket(socket); 717 return eConnectionStatusSuccess; 718 } 719 720 ConnectionStatus ConnectionFileDescriptor::ConnectTCP(llvm::StringRef s, 721 Status *error_ptr) { 722 Socket *socket = nullptr; 723 Status error = Socket::TcpConnect(s, m_child_processes_inherit, socket); 724 if (error_ptr) 725 *error_ptr = error; 726 m_write_sp.reset(socket); 727 m_read_sp = m_write_sp; 728 if (error.Fail()) { 729 return eConnectionStatusError; 730 } 731 m_uri.assign(s); 732 return eConnectionStatusSuccess; 733 } 734 735 ConnectionStatus ConnectionFileDescriptor::ConnectUDP(llvm::StringRef s, 736 Status *error_ptr) { 737 Socket *socket = nullptr; 738 Status error = Socket::UdpConnect(s, m_child_processes_inherit, socket); 739 if (error_ptr) 740 *error_ptr = error; 741 m_write_sp.reset(socket); 742 m_read_sp = m_write_sp; 743 if (error.Fail()) { 744 return eConnectionStatusError; 745 } 746 m_uri.assign(s); 747 return eConnectionStatusSuccess; 748 } 749 750 uint16_t 751 ConnectionFileDescriptor::GetListeningPort(const Timeout<std::micro> &timeout) { 752 auto Result = m_port_predicate.WaitForValueNotEqualTo(0, timeout); 753 return Result ? *Result : 0; 754 } 755 756 bool ConnectionFileDescriptor::GetChildProcessesInherit() const { 757 return m_child_processes_inherit; 758 } 759 760 void ConnectionFileDescriptor::SetChildProcessesInherit( 761 bool child_processes_inherit) { 762 m_child_processes_inherit = child_processes_inherit; 763 } 764 765 void ConnectionFileDescriptor::InitializeSocket(Socket *socket) { 766 m_write_sp.reset(socket); 767 m_read_sp = m_write_sp; 768 m_uri = socket->GetRemoteConnectionURI(); 769 } 770