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 #if LLDB_ENABLE_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<NativeFile>(fd, File::eOpenOptionWrite, owns_fd);
90   m_read_sp = std::make_shared<NativeFile>(fd, File::eOpenOptionRead, 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 #if LLDB_ENABLE_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 =
222                 std::make_shared<NativeFile>(fd, File::eOpenOptionRead, false);
223             m_write_sp =
224                 std::make_shared<NativeFile>(fd, File::eOpenOptionWrite, false);
225           }
226           m_uri = *addr;
227           return eConnectionStatusSuccess;
228         }
229       }
230 
231       if (error_ptr)
232         error_ptr->SetErrorStringWithFormat("invalid file descriptor: \"%s\"",
233                                             path.str().c_str());
234       m_read_sp.reset();
235       m_write_sp.reset();
236       return eConnectionStatusError;
237     } else if ((addr = GetURLAddress(path, FILE_SCHEME))) {
238       std::string addr_str = addr->str();
239       // file:///PATH
240       int fd = llvm::sys::RetryAfterSignal(-1, ::open, addr_str.c_str(), O_RDWR);
241       if (fd == -1) {
242         if (error_ptr)
243           error_ptr->SetErrorToErrno();
244         return eConnectionStatusError;
245       }
246 
247       if (::isatty(fd)) {
248         // Set up serial terminal emulation
249         struct termios options;
250         ::tcgetattr(fd, &options);
251 
252         // Set port speed to maximum
253         ::cfsetospeed(&options, B115200);
254         ::cfsetispeed(&options, B115200);
255 
256         // Raw input, disable echo and signals
257         options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
258 
259         // Make sure only one character is needed to return from a read
260         options.c_cc[VMIN] = 1;
261         options.c_cc[VTIME] = 0;
262 
263         llvm::sys::RetryAfterSignal(-1, ::tcsetattr, fd, TCSANOW, &options);
264       }
265 
266       int flags = ::fcntl(fd, F_GETFL, 0);
267       if (flags >= 0) {
268         if ((flags & O_NONBLOCK) == 0) {
269           flags |= O_NONBLOCK;
270           ::fcntl(fd, F_SETFL, flags);
271         }
272       }
273       m_read_sp = std::make_shared<NativeFile>(fd, File::eOpenOptionRead, true);
274       m_write_sp = std::make_shared<NativeFile>(fd, File::eOpenOptionWrite, false);
275       return eConnectionStatusSuccess;
276     }
277 #endif
278     if (error_ptr)
279       error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'",
280                                           path.str().c_str());
281     return eConnectionStatusError;
282   }
283   if (error_ptr)
284     error_ptr->SetErrorString("invalid connect arguments");
285   return eConnectionStatusError;
286 }
287 
288 bool ConnectionFileDescriptor::InterruptRead() {
289   size_t bytes_written = 0;
290   Status result = m_pipe.Write("i", 1, bytes_written);
291   return result.Success();
292 }
293 
294 ConnectionStatus ConnectionFileDescriptor::Disconnect(Status *error_ptr) {
295   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
296   LLDB_LOGF(log, "%p ConnectionFileDescriptor::Disconnect ()",
297             static_cast<void *>(this));
298 
299   ConnectionStatus status = eConnectionStatusSuccess;
300 
301   if (!IsConnected()) {
302     LLDB_LOGF(
303         log, "%p ConnectionFileDescriptor::Disconnect(): Nothing to disconnect",
304         static_cast<void *>(this));
305     return eConnectionStatusSuccess;
306   }
307 
308   if (m_read_sp && m_read_sp->IsValid() &&
309       m_read_sp->GetFdType() == IOObject::eFDTypeSocket)
310     static_cast<Socket &>(*m_read_sp).PreDisconnect();
311 
312   // Try to get the ConnectionFileDescriptor's mutex.  If we fail, that is
313   // quite likely because somebody is doing a blocking read on our file
314   // descriptor.  If that's the case, then send the "q" char to the command
315   // file channel so the read will wake up and the connection will then know to
316   // shut down.
317   std::unique_lock<std::recursive_mutex> locker(m_mutex, std::defer_lock);
318   if (!locker.try_lock()) {
319     if (m_pipe.CanWrite()) {
320       size_t bytes_written = 0;
321       Status result = m_pipe.Write("q", 1, bytes_written);
322       LLDB_LOGF(log,
323                 "%p ConnectionFileDescriptor::Disconnect(): Couldn't get "
324                 "the lock, sent 'q' to %d, error = '%s'.",
325                 static_cast<void *>(this), m_pipe.GetWriteFileDescriptor(),
326                 result.AsCString());
327     } else if (log) {
328       LLDB_LOGF(log,
329                 "%p ConnectionFileDescriptor::Disconnect(): Couldn't get the "
330                 "lock, but no command pipe is available.",
331                 static_cast<void *>(this));
332     }
333     locker.lock();
334   }
335 
336   // Prevents reads and writes during shutdown.
337   m_shutting_down = true;
338 
339   Status error = m_read_sp->Close();
340   Status error2 = m_write_sp->Close();
341   if (error.Fail() || error2.Fail())
342     status = eConnectionStatusError;
343   if (error_ptr)
344     *error_ptr = error.Fail() ? error : error2;
345 
346   // Close any pipes we were using for async interrupts
347   m_pipe.Close();
348 
349   m_uri.clear();
350   m_shutting_down = false;
351   return status;
352 }
353 
354 size_t ConnectionFileDescriptor::Read(void *dst, size_t dst_len,
355                                       const Timeout<std::micro> &timeout,
356                                       ConnectionStatus &status,
357                                       Status *error_ptr) {
358   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
359 
360   std::unique_lock<std::recursive_mutex> locker(m_mutex, std::defer_lock);
361   if (!locker.try_lock()) {
362     LLDB_LOGF(log,
363               "%p ConnectionFileDescriptor::Read () failed to get the "
364               "connection lock.",
365               static_cast<void *>(this));
366     if (error_ptr)
367       error_ptr->SetErrorString("failed to get the connection lock for read.");
368 
369     status = eConnectionStatusTimedOut;
370     return 0;
371   }
372 
373   if (m_shutting_down) {
374     if (error_ptr)
375       error_ptr->SetErrorString("shutting down");
376     status = eConnectionStatusError;
377     return 0;
378   }
379 
380   status = BytesAvailable(timeout, error_ptr);
381   if (status != eConnectionStatusSuccess)
382     return 0;
383 
384   Status error;
385   size_t bytes_read = dst_len;
386   error = m_read_sp->Read(dst, bytes_read);
387 
388   if (log) {
389     LLDB_LOGF(log,
390               "%p ConnectionFileDescriptor::Read()  fd = %" PRIu64
391               ", dst = %p, dst_len = %" PRIu64 ") => %" PRIu64 ", error = %s",
392               static_cast<void *>(this),
393               static_cast<uint64_t>(m_read_sp->GetWaitableHandle()),
394               static_cast<void *>(dst), static_cast<uint64_t>(dst_len),
395               static_cast<uint64_t>(bytes_read), error.AsCString());
396   }
397 
398   if (bytes_read == 0) {
399     error.Clear(); // End-of-file.  Do not automatically close; pass along for
400                    // the end-of-file handlers.
401     status = eConnectionStatusEndOfFile;
402   }
403 
404   if (error_ptr)
405     *error_ptr = error;
406 
407   if (error.Fail()) {
408     uint32_t error_value = error.GetError();
409     switch (error_value) {
410     case EAGAIN: // The file was marked for non-blocking I/O, and no data were
411                  // ready to be read.
412       if (m_read_sp->GetFdType() == IOObject::eFDTypeSocket)
413         status = eConnectionStatusTimedOut;
414       else
415         status = eConnectionStatusSuccess;
416       return 0;
417 
418     case EFAULT:  // Buf points outside the allocated address space.
419     case EINTR:   // A read from a slow device was interrupted before any data
420                   // arrived by the delivery of a signal.
421     case EINVAL:  // The pointer associated with fildes was negative.
422     case EIO:     // An I/O error occurred while reading from the file system.
423                   // The process group is orphaned.
424                   // The file is a regular file, nbyte is greater than 0, the
425                   // starting position is before the end-of-file, and the
426                   // starting position is greater than or equal to the offset
427                   // maximum established for the open file descriptor
428                   // associated with fildes.
429     case EISDIR:  // An attempt is made to read a directory.
430     case ENOBUFS: // An attempt to allocate a memory buffer fails.
431     case ENOMEM:  // Insufficient memory is available.
432       status = eConnectionStatusError;
433       break; // Break to close....
434 
435     case ENOENT:     // no such file or directory
436     case EBADF:      // fildes is not a valid file or socket descriptor open for
437                      // reading.
438     case ENXIO:      // An action is requested of a device that does not exist..
439                      // A requested action cannot be performed by the device.
440     case ECONNRESET: // The connection is closed by the peer during a read
441                      // attempt on a socket.
442     case ENOTCONN:   // A read is attempted on an unconnected socket.
443       status = eConnectionStatusLostConnection;
444       break; // Break to close....
445 
446     case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a
447                     // socket.
448       status = eConnectionStatusTimedOut;
449       return 0;
450 
451     default:
452       LLDB_LOG(log, "this = {0}, unexpected error: {1}", this,
453                llvm::sys::StrError(error_value));
454       status = eConnectionStatusError;
455       break; // Break to close....
456     }
457 
458     return 0;
459   }
460   return bytes_read;
461 }
462 
463 size_t ConnectionFileDescriptor::Write(const void *src, size_t src_len,
464                                        ConnectionStatus &status,
465                                        Status *error_ptr) {
466   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
467   LLDB_LOGF(log,
468             "%p ConnectionFileDescriptor::Write (src = %p, src_len = %" PRIu64
469             ")",
470             static_cast<void *>(this), static_cast<const void *>(src),
471             static_cast<uint64_t>(src_len));
472 
473   if (!IsConnected()) {
474     if (error_ptr)
475       error_ptr->SetErrorString("not connected");
476     status = eConnectionStatusNoConnection;
477     return 0;
478   }
479 
480   if (m_shutting_down) {
481     if (error_ptr)
482       error_ptr->SetErrorString("shutting down");
483     status = eConnectionStatusError;
484     return 0;
485   }
486 
487   Status error;
488 
489   size_t bytes_sent = src_len;
490   error = m_write_sp->Write(src, bytes_sent);
491 
492   if (log) {
493     LLDB_LOGF(log,
494               "%p ConnectionFileDescriptor::Write(fd = %" PRIu64
495               ", src = %p, src_len = %" PRIu64 ") => %" PRIu64 " (error = %s)",
496               static_cast<void *>(this),
497               static_cast<uint64_t>(m_write_sp->GetWaitableHandle()),
498               static_cast<const void *>(src), static_cast<uint64_t>(src_len),
499               static_cast<uint64_t>(bytes_sent), error.AsCString());
500   }
501 
502   if (error_ptr)
503     *error_ptr = error;
504 
505   if (error.Fail()) {
506     switch (error.GetError()) {
507     case EAGAIN:
508     case EINTR:
509       status = eConnectionStatusSuccess;
510       return 0;
511 
512     case ECONNRESET: // The connection is closed by the peer during a read
513                      // attempt on a socket.
514     case ENOTCONN:   // A read is attempted on an unconnected socket.
515       status = eConnectionStatusLostConnection;
516       break; // Break to close....
517 
518     default:
519       status = eConnectionStatusError;
520       break; // Break to close....
521     }
522 
523     return 0;
524   }
525 
526   status = eConnectionStatusSuccess;
527   return bytes_sent;
528 }
529 
530 std::string ConnectionFileDescriptor::GetURI() { return m_uri; }
531 
532 // This ConnectionFileDescriptor::BytesAvailable() uses select() via
533 // SelectHelper
534 //
535 // PROS:
536 //  - select is consistent across most unix platforms
537 //  - The Apple specific version allows for unlimited fds in the fd_sets by
538 //    setting the _DARWIN_UNLIMITED_SELECT define prior to including the
539 //    required header files.
540 // CONS:
541 //  - on non-Apple platforms, only supports file descriptors up to FD_SETSIZE.
542 //     This implementation  will assert if it runs into that hard limit to let
543 //     users know that another ConnectionFileDescriptor::BytesAvailable() should
544 //     be used or a new version of ConnectionFileDescriptor::BytesAvailable()
545 //     should be written for the system that is running into the limitations.
546 
547 ConnectionStatus
548 ConnectionFileDescriptor::BytesAvailable(const Timeout<std::micro> &timeout,
549                                          Status *error_ptr) {
550   // Don't need to take the mutex here separately since we are only called from
551   // Read.  If we ever get used more generally we will need to lock here as
552   // well.
553 
554   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_CONNECTION));
555   LLDB_LOG(log, "this = {0}, timeout = {1}", this, timeout);
556 
557   // Make a copy of the file descriptors to make sure we don't have another
558   // thread change these values out from under us and cause problems in the
559   // loop below where like in FS_SET()
560   const IOObject::WaitableHandle handle = m_read_sp->GetWaitableHandle();
561   const int pipe_fd = m_pipe.GetReadFileDescriptor();
562 
563   if (handle != IOObject::kInvalidHandleValue) {
564     SelectHelper select_helper;
565     if (timeout)
566       select_helper.SetTimeout(*timeout);
567 
568     select_helper.FDSetRead(handle);
569 #if defined(_WIN32)
570     // select() won't accept pipes on Windows.  The entire Windows codepath
571     // needs to be converted over to using WaitForMultipleObjects and event
572     // HANDLEs, but for now at least this will allow ::select() to not return
573     // an error.
574     const bool have_pipe_fd = false;
575 #else
576     const bool have_pipe_fd = pipe_fd >= 0;
577 #endif
578     if (have_pipe_fd)
579       select_helper.FDSetRead(pipe_fd);
580 
581     while (handle == m_read_sp->GetWaitableHandle()) {
582 
583       Status error = select_helper.Select();
584 
585       if (error_ptr)
586         *error_ptr = error;
587 
588       if (error.Fail()) {
589         switch (error.GetError()) {
590         case EBADF: // One of the descriptor sets specified an invalid
591                     // descriptor.
592           return eConnectionStatusLostConnection;
593 
594         case EINVAL: // The specified time limit is invalid. One of its
595                      // components is negative or too large.
596         default:     // Other unknown error
597           return eConnectionStatusError;
598 
599         case ETIMEDOUT:
600           return eConnectionStatusTimedOut;
601 
602         case EAGAIN: // The kernel was (perhaps temporarily) unable to
603                      // allocate the requested number of file descriptors, or
604                      // we have non-blocking IO
605         case EINTR:  // A signal was delivered before the time limit
606           // expired and before any of the selected events occurred.
607           break; // Lets keep reading to until we timeout
608         }
609       } else {
610         if (select_helper.FDIsSetRead(handle))
611           return eConnectionStatusSuccess;
612 
613         if (select_helper.FDIsSetRead(pipe_fd)) {
614           // There is an interrupt or exit command in the command pipe Read the
615           // data from that pipe:
616           char c;
617 
618           ssize_t bytes_read = llvm::sys::RetryAfterSignal(-1, ::read, pipe_fd, &c, 1);
619           assert(bytes_read == 1);
620           (void)bytes_read;
621           switch (c) {
622           case 'q':
623             LLDB_LOGF(log,
624                       "%p ConnectionFileDescriptor::BytesAvailable() "
625                       "got data: %c from the command channel.",
626                       static_cast<void *>(this), c);
627             return eConnectionStatusEndOfFile;
628           case 'i':
629             // Interrupt the current read
630             return eConnectionStatusInterrupted;
631           }
632         }
633       }
634     }
635   }
636 
637   if (error_ptr)
638     error_ptr->SetErrorString("not connected");
639   return eConnectionStatusLostConnection;
640 }
641 
642 ConnectionStatus
643 ConnectionFileDescriptor::NamedSocketAccept(llvm::StringRef socket_name,
644                                             Status *error_ptr) {
645   Socket *socket = nullptr;
646   Status error =
647       Socket::UnixDomainAccept(socket_name, m_child_processes_inherit, socket);
648   if (error_ptr)
649     *error_ptr = error;
650   m_write_sp.reset(socket);
651   m_read_sp = m_write_sp;
652   if (error.Fail()) {
653     return eConnectionStatusError;
654   }
655   m_uri.assign(socket_name);
656   return eConnectionStatusSuccess;
657 }
658 
659 ConnectionStatus
660 ConnectionFileDescriptor::NamedSocketConnect(llvm::StringRef socket_name,
661                                              Status *error_ptr) {
662   Socket *socket = nullptr;
663   Status error =
664       Socket::UnixDomainConnect(socket_name, m_child_processes_inherit, socket);
665   if (error_ptr)
666     *error_ptr = error;
667   m_write_sp.reset(socket);
668   m_read_sp = m_write_sp;
669   if (error.Fail()) {
670     return eConnectionStatusError;
671   }
672   m_uri.assign(socket_name);
673   return eConnectionStatusSuccess;
674 }
675 
676 lldb::ConnectionStatus
677 ConnectionFileDescriptor::UnixAbstractSocketConnect(llvm::StringRef socket_name,
678                                                     Status *error_ptr) {
679   Socket *socket = nullptr;
680   Status error = Socket::UnixAbstractConnect(socket_name,
681                                              m_child_processes_inherit, socket);
682   if (error_ptr)
683     *error_ptr = error;
684   m_write_sp.reset(socket);
685   m_read_sp = m_write_sp;
686   if (error.Fail()) {
687     return eConnectionStatusError;
688   }
689   m_uri.assign(socket_name);
690   return eConnectionStatusSuccess;
691 }
692 
693 ConnectionStatus
694 ConnectionFileDescriptor::SocketListenAndAccept(llvm::StringRef s,
695                                                 Status *error_ptr) {
696   m_port_predicate.SetValue(0, eBroadcastNever);
697 
698   Socket *socket = nullptr;
699   m_waiting_for_accept = true;
700   Status error = Socket::TcpListen(s, m_child_processes_inherit, socket,
701                                    &m_port_predicate);
702   if (error_ptr)
703     *error_ptr = error;
704   if (error.Fail())
705     return eConnectionStatusError;
706 
707   std::unique_ptr<Socket> listening_socket_up;
708 
709   listening_socket_up.reset(socket);
710   socket = nullptr;
711   error = listening_socket_up->Accept(socket);
712   listening_socket_up.reset();
713   if (error_ptr)
714     *error_ptr = error;
715   if (error.Fail())
716     return eConnectionStatusError;
717 
718   InitializeSocket(socket);
719   return eConnectionStatusSuccess;
720 }
721 
722 ConnectionStatus ConnectionFileDescriptor::ConnectTCP(llvm::StringRef s,
723                                                       Status *error_ptr) {
724   Socket *socket = nullptr;
725   Status error = Socket::TcpConnect(s, m_child_processes_inherit, socket);
726   if (error_ptr)
727     *error_ptr = error;
728   m_write_sp.reset(socket);
729   m_read_sp = m_write_sp;
730   if (error.Fail()) {
731     return eConnectionStatusError;
732   }
733   m_uri.assign(s);
734   return eConnectionStatusSuccess;
735 }
736 
737 ConnectionStatus ConnectionFileDescriptor::ConnectUDP(llvm::StringRef s,
738                                                       Status *error_ptr) {
739   Socket *socket = nullptr;
740   Status error = Socket::UdpConnect(s, m_child_processes_inherit, socket);
741   if (error_ptr)
742     *error_ptr = error;
743   m_write_sp.reset(socket);
744   m_read_sp = m_write_sp;
745   if (error.Fail()) {
746     return eConnectionStatusError;
747   }
748   m_uri.assign(s);
749   return eConnectionStatusSuccess;
750 }
751 
752 uint16_t
753 ConnectionFileDescriptor::GetListeningPort(const Timeout<std::micro> &timeout) {
754   auto Result = m_port_predicate.WaitForValueNotEqualTo(0, timeout);
755   return Result ? *Result : 0;
756 }
757 
758 bool ConnectionFileDescriptor::GetChildProcessesInherit() const {
759   return m_child_processes_inherit;
760 }
761 
762 void ConnectionFileDescriptor::SetChildProcessesInherit(
763     bool child_processes_inherit) {
764   m_child_processes_inherit = child_processes_inherit;
765 }
766 
767 void ConnectionFileDescriptor::InitializeSocket(Socket *socket) {
768   m_write_sp.reset(socket);
769   m_read_sp = m_write_sp;
770   m_uri = socket->GetRemoteConnectionURI();
771 }
772