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