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