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