1 //===-- ConnectionFileDescriptor.cpp ----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
17 #include "lldb/Core/ConnectionFileDescriptor.h"
18 #include "lldb/Host/Config.h"
19 #include "lldb/Host/SocketAddress.h"
26 #include <sys/types.h>
27 #ifndef LLDB_DISABLE_POSIX
28 #include <arpa/inet.h>
30 #include <netinet/in.h>
31 #include <netinet/tcp.h>
32 #include <sys/socket.h>
38 #include "lldb/Host/windows/windows.h"
44 // Other libraries and framework includes
45 #include "llvm/Support/ErrorHandling.h"
46 #if defined(__APPLE__)
47 #include "llvm/ADT/SmallVector.h"
50 #include "lldb/lldb-private-log.h"
51 #include "lldb/Interpreter/Args.h"
52 #include "lldb/Core/Communication.h"
53 #include "lldb/Core/Log.h"
54 #include "lldb/Core/RegularExpression.h"
55 #include "lldb/Core/Timer.h"
56 #include "lldb/Host/Host.h"
60 using namespace lldb_private;
63 DecodeHostAndPort (const char *host_and_port,
64 std::string &host_str,
65 std::string &port_str,
69 static RegularExpression g_regex ("([^:]+):([0-9]+)");
70 RegularExpression::Match regex_match(2);
71 if (g_regex.Execute (host_and_port, ®ex_match))
73 if (regex_match.GetMatchAtIndex (host_and_port, 1, host_str) &&
74 regex_match.GetMatchAtIndex (host_and_port, 2, port_str))
76 port = Args::StringToSInt32 (port_str.c_str(), INT32_MIN);
77 if (port != INT32_MIN)
89 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port);
93 ConnectionFileDescriptor::ConnectionFileDescriptor () :
97 m_fd_send_type (eFDTypeFile),
98 m_fd_recv_type (eFDTypeFile),
99 m_udp_send_sockaddr (new SocketAddress()),
100 m_socket_timeout_usec(0),
103 m_mutex (Mutex::eMutexTypeRecursive),
104 m_should_close_fd (false),
105 m_shutting_down (false)
107 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT));
109 log->Printf ("%p ConnectionFileDescriptor::ConnectionFileDescriptor ()", this);
112 ConnectionFileDescriptor::ConnectionFileDescriptor (int fd, bool owns_fd) :
116 m_fd_send_type (eFDTypeFile),
117 m_fd_recv_type (eFDTypeFile),
118 m_udp_send_sockaddr (new SocketAddress()),
119 m_socket_timeout_usec(0),
122 m_mutex (Mutex::eMutexTypeRecursive),
123 m_should_close_fd (owns_fd),
124 m_shutting_down (false)
126 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT));
128 log->Printf ("%p ConnectionFileDescriptor::ConnectionFileDescriptor (fd = %i, owns_fd = %i)", this, fd, owns_fd);
133 ConnectionFileDescriptor::~ConnectionFileDescriptor ()
135 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT));
137 log->Printf ("%p ConnectionFileDescriptor::~ConnectionFileDescriptor ()", this);
143 ConnectionFileDescriptor::OpenCommandPipe ()
147 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
148 // Make the command file descriptor here:
150 #ifndef LLDB_DISABLE_POSIX
151 int result = pipe (filedes);
158 log->Printf ("%p ConnectionFileDescriptor::OpenCommandPipe () - could not make pipe: %s",
164 m_pipe_read = filedes[0];
165 m_pipe_write = filedes[1];
167 log->Printf ("%p ConnectionFileDescriptor::OpenCommandPipe() - success readfd=%d writefd=%d",
175 ConnectionFileDescriptor::CloseCommandPipe ()
177 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
179 log->Printf ("%p ConnectionFileDescriptor::CloseCommandPipe()",
182 if (m_pipe_read != -1)
185 llvm_unreachable("pipe close unsupported in MSVC");
192 if (m_pipe_write != -1)
195 llvm_unreachable("pipe close unsupported in MSVC");
197 close (m_pipe_write);
204 ConnectionFileDescriptor::IsConnected () const
206 return m_fd_send >= 0 || m_fd_recv >= 0;
210 ConnectionFileDescriptor::Connect (const char *s, Error *error_ptr)
212 Mutex::Locker locker (m_mutex);
213 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
215 log->Printf ("%p ConnectionFileDescriptor::Connect (url = '%s')", this, s);
221 if (strstr(s, "listen://"))
223 // listen://HOST:PORT
224 return SocketListen (s + strlen("listen://"), error_ptr);
226 else if (strstr(s, "accept://"))
229 return NamedSocketAccept (s + strlen("accept://"), error_ptr);
231 else if (strstr(s, "unix-accept://"))
234 return NamedSocketAccept (s + strlen("unix-accept://"), error_ptr);
236 else if (strstr(s, "connect://"))
238 return ConnectTCP (s + strlen("connect://"), error_ptr);
240 else if (strstr(s, "tcp-connect://"))
242 return ConnectTCP (s + strlen("tcp-connect://"), error_ptr);
244 else if (strstr(s, "udp://"))
246 return ConnectUDP (s + strlen("udp://"), error_ptr);
248 else if (strstr(s, "fd://"))
250 // Just passing a native file descriptor within this current process
251 // that is already opened (possibly from a service or other source).
252 s += strlen ("fd://");
253 bool success = false;
254 m_fd_send = m_fd_recv = Args::StringToSInt32 (s, -1, 0, &success);
258 // We have what looks to be a valid file descriptor, but we
259 // should make sure it is. We currently are doing this by trying to
260 // get the flags from the file descriptor and making sure it
263 #ifndef LLDB_DISABLE_POSIX
264 int flags = ::fcntl (m_fd_send, F_GETFL, 0);
268 if (flags == -1 || errno == EBADF)
271 error_ptr->SetErrorStringWithFormat ("stale file descriptor: %s", s);
272 m_fd_send = m_fd_recv = -1;
273 return eConnectionStatusError;
277 // Try and get a socket option from this file descriptor to
278 // see if this is a socket and set m_is_socket accordingly.
280 bool is_socket = GetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, resuse) == 0;
282 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
283 // Don't take ownership of a file descriptor that gets passed
284 // to us since someone else opened the file descriptor and
286 // TODO: Since are using a URL to open connection we should
287 // eventually parse options using the web standard where we
288 // have "fd://123?opt1=value;opt2=value" and we can have an
289 // option be "owns=1" or "owns=0" or something like this to
290 // allow us to specify this. For now, we assume we must
291 // assume we don't own it.
292 m_should_close_fd = false;
293 return eConnectionStatusSuccess;
298 error_ptr->SetErrorStringWithFormat ("invalid file descriptor: \"fd://%s\"", s);
299 m_fd_send = m_fd_recv = -1;
300 return eConnectionStatusError;
302 else if (strstr(s, "file://"))
305 const char *path = s + strlen("file://");
306 #ifndef LLDB_DISABLE_POSIX
309 m_fd_send = m_fd_recv = ::open (path, O_RDWR);
310 } while (m_fd_send == -1 && errno == EINTR);
314 error_ptr->SetErrorToErrno();
315 return eConnectionStatusError;
318 if (::isatty(m_fd_send))
320 // Set up serial terminal emulation
321 struct termios options;
322 ::tcgetattr (m_fd_send, &options);
324 // Set port speed to maximum
325 ::cfsetospeed (&options, B115200);
326 ::cfsetispeed (&options, B115200);
328 // Raw input, disable echo and signals
329 options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
331 // Make sure only one character is needed to return from a read
332 options.c_cc[VMIN] = 1;
333 options.c_cc[VTIME] = 0;
335 ::tcsetattr (m_fd_send, TCSANOW, &options);
338 int flags = ::fcntl (m_fd_send, F_GETFL, 0);
341 if ((flags & O_NONBLOCK) == 0)
344 ::fcntl (m_fd_send, F_SETFL, flags);
347 m_should_close_fd = true;
348 return eConnectionStatusSuccess;
350 return eConnectionStatusError;
354 error_ptr->SetErrorStringWithFormat ("unsupported connection URL: '%s'", s);
355 return eConnectionStatusError;
358 error_ptr->SetErrorString("invalid connect arguments");
359 return eConnectionStatusError;
363 ConnectionFileDescriptor::Disconnect (Error *error_ptr)
365 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
367 log->Printf ("%p ConnectionFileDescriptor::Disconnect ()", this);
369 // Reset the port predicate when disconnecting and don't broadcast
370 m_port_predicate.SetValue(0, eBroadcastNever);
372 ConnectionStatus status = eConnectionStatusSuccess;
374 if (m_fd_send < 0 && m_fd_recv < 0)
377 log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Nothing to disconnect", this);
378 return eConnectionStatusSuccess;
381 // Try to get the ConnectionFileDescriptor's mutex. If we fail, that is quite likely
382 // because somebody is doing a blocking read on our file descriptor. If that's the case,
383 // then send the "q" char to the command file channel so the read will wake up and the connection
384 // will then know to shut down.
386 m_shutting_down = true;
388 Mutex::Locker locker;
389 bool got_lock= locker.TryLock (m_mutex);
393 if (m_pipe_write != -1 )
396 result = write (m_pipe_write, "q", 1);
398 log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Couldn't get the lock, sent 'q' to %d, result = %d.", this, m_pipe_write, result);
401 log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Couldn't get the lock, but no command pipe is available.", this);
402 locker.Lock (m_mutex);
405 if (m_should_close_fd == true)
407 if (m_fd_send == m_fd_recv)
409 status = Close (m_fd_send, m_fd_send_type, error_ptr);
413 // File descriptors are the different, close both if needed
415 status = Close (m_fd_send, m_fd_send_type, error_ptr);
418 ConnectionStatus recv_status = Close (m_fd_recv, m_fd_recv_type, error_ptr);
419 if (status == eConnectionStatusSuccess)
420 status = recv_status;
425 // Now set all our descriptors to invalid values.
427 m_fd_send = m_fd_recv = -1;
429 if (status != eConnectionStatusSuccess)
435 m_shutting_down = false;
436 return eConnectionStatusSuccess;
440 ConnectionFileDescriptor::Read (void *dst,
442 uint32_t timeout_usec,
443 ConnectionStatus &status,
446 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
448 log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %" PRIu64 ")...",
449 this, m_fd_recv, dst, (uint64_t)dst_len);
451 Mutex::Locker locker;
452 bool got_lock = locker.TryLock (m_mutex);
456 log->Printf ("%p ConnectionFileDescriptor::Read () failed to get the connection lock.",
459 error_ptr->SetErrorString ("failed to get the connection lock for read.");
461 status = eConnectionStatusTimedOut;
464 else if (m_shutting_down)
465 return eConnectionStatusError;
467 ssize_t bytes_read = 0;
469 status = BytesAvailable (timeout_usec, error_ptr);
470 if (status == eConnectionStatusSuccess)
474 #ifndef LLDB_DISABLE_POSIX
475 bytes_read = ::read (m_fd_recv, dst, dst_len);
477 switch (m_fd_send_type) {
479 case eFDTypeSocketUDP:
480 bytes_read = ::recv (m_fd_recv, (char*)dst, dst_len, 0);
489 } while (bytes_read < 0 && errno == EINTR);
492 if (status != eConnectionStatusSuccess)
498 error.Clear(); // End-of-file. Do not automatically close; pass along for the end-of-file handlers.
499 status = eConnectionStatusEndOfFile;
501 else if (bytes_read < 0)
503 error.SetErrorToErrno();
511 log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %" PRIu64 ") => %" PRIi64 ", error = %s",
524 uint32_t error_value = error.GetError();
527 case EAGAIN: // The file was marked for non-blocking I/O, and no data were ready to be read.
528 if (m_fd_recv_type == eFDTypeSocket || m_fd_recv_type == eFDTypeSocketUDP)
529 status = eConnectionStatusTimedOut;
531 status = eConnectionStatusSuccess;
534 case EFAULT: // Buf points outside the allocated address space.
535 case EINTR: // A read from a slow device was interrupted before any data arrived by the delivery of a signal.
536 case EINVAL: // The pointer associated with fildes was negative.
537 case EIO: // An I/O error occurred while reading from the file system.
538 // The process group is orphaned.
539 // The file is a regular file, nbyte is greater than 0,
540 // the starting position is before the end-of-file, and
541 // the starting position is greater than or equal to the
542 // offset maximum established for the open file
543 // descriptor associated with fildes.
544 case EISDIR: // An attempt is made to read a directory.
545 case ENOBUFS: // An attempt to allocate a memory buffer fails.
546 case ENOMEM: // Insufficient memory is available.
547 status = eConnectionStatusError;
548 break; // Break to close....
550 case ENOENT: // no such file or directory
551 case EBADF: // fildes is not a valid file or socket descriptor open for reading.
552 case ENXIO: // An action is requested of a device that does not exist..
553 // A requested action cannot be performed by the device.
554 case ECONNRESET:// The connection is closed by the peer during a read attempt on a socket.
555 case ENOTCONN: // A read is attempted on an unconnected socket.
556 status = eConnectionStatusLostConnection;
557 break; // Break to close....
559 case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a socket.
560 status = eConnectionStatusTimedOut;
565 log->Printf("%p ConnectionFileDescriptor::Read (), unexpected error: %s", this, strerror(error_value));
566 status = eConnectionStatusError;
567 break; // Break to close....
577 ConnectionFileDescriptor::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr)
579 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
581 log->Printf ("%p ConnectionFileDescriptor::Write (src = %p, src_len = %" PRIu64 ")", this, src, (uint64_t)src_len);
586 error_ptr->SetErrorString("not connected");
587 status = eConnectionStatusNoConnection;
594 ssize_t bytes_sent = 0;
596 switch (m_fd_send_type)
598 #ifndef LLDB_DISABLE_POSIX
599 case eFDTypeFile: // Other FD requireing read/write
602 bytes_sent = ::write (m_fd_send, src, src_len);
603 } while (bytes_sent < 0 && errno == EINTR);
606 case eFDTypeSocket: // Socket requiring send/recv
609 bytes_sent = ::send (m_fd_send, (char*)src, src_len, 0);
610 } while (bytes_sent < 0 && errno == EINTR);
613 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom
614 assert (m_udp_send_sockaddr->GetFamily() != 0);
617 bytes_sent = ::sendto (m_fd_send,
621 *m_udp_send_sockaddr,
622 m_udp_send_sockaddr->GetLength());
623 } while (bytes_sent < 0 && errno == EINTR);
628 error.SetErrorToErrno ();
634 switch (m_fd_send_type)
636 case eFDTypeFile: // Other FD requireing read/write
637 log->Printf ("%p ConnectionFileDescriptor::Write() ::write (fd = %i, src = %p, src_len = %" PRIu64 ") => %" PRIi64 " (error = %s)",
646 case eFDTypeSocket: // Socket requiring send/recv
647 log->Printf ("%p ConnectionFileDescriptor::Write() ::send (socket = %i, src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
656 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom
657 log->Printf ("%p ConnectionFileDescriptor::Write() ::sendto (socket = %i, src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
673 switch (error.GetError())
677 status = eConnectionStatusSuccess;
680 case ECONNRESET:// The connection is closed by the peer during a read attempt on a socket.
681 case ENOTCONN: // A read is attempted on an unconnected socket.
682 status = eConnectionStatusLostConnection;
683 break; // Break to close....
686 status = eConnectionStatusError;
687 break; // Break to close....
693 status = eConnectionStatusSuccess;
699 #if defined(__APPLE__)
701 // This ConnectionFileDescriptor::BytesAvailable() uses select().
704 // - select is consistent across most unix platforms
705 // - this Apple specific version allows for unlimited fds in the fd_sets by
706 // setting the _DARWIN_UNLIMITED_SELECT define prior to including the
707 // required header files.
713 ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
715 // Don't need to take the mutex here separately since we are only called from Read. If we
716 // ever get used more generally we will need to lock here as well.
718 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
720 log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
721 struct timeval *tv_ptr;
723 if (timeout_usec == UINT32_MAX)
730 TimeValue time_value;
731 time_value.OffsetWithMicroSeconds (timeout_usec);
732 tv.tv_sec = time_value.seconds();
733 tv.tv_usec = time_value.microseconds();
737 // Make a copy of the file descriptors to make sure we don't
738 // have another thread change these values out from under us
739 // and cause problems in the loop below where like in FS_SET()
740 const int data_fd = m_fd_recv;
741 const int pipe_fd = m_pipe_read;
745 const bool have_pipe_fd = pipe_fd >= 0;
747 while (data_fd == m_fd_recv)
749 const int nfds = std::max<int>(data_fd, pipe_fd) + 1;
750 llvm::SmallVector<fd_set, 1> read_fds;
751 read_fds.resize((nfds/FD_SETSIZE) + 1);
752 for (size_t i=0; i<read_fds.size(); ++i)
753 FD_ZERO (&read_fds[i]);
754 // FD_SET doesn't bounds check, it just happily walks off the end
755 // but we have taken care of making the extra storage with our
756 // SmallVector of fd_set objects
757 FD_SET (data_fd, read_fds.data());
759 FD_SET (pipe_fd, read_fds.data());
766 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p)...",
767 this, nfds, data_fd, pipe_fd, tv_ptr);
769 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p)...",
770 this, nfds, data_fd, tv_ptr);
773 const int num_set_fds = ::select (nfds, read_fds.data(), NULL, NULL, tv_ptr);
775 error.SetErrorToErrno();
782 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p) => %d, error = %s",
783 this, nfds, data_fd, pipe_fd, tv_ptr, num_set_fds, error.AsCString());
785 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p) => %d, error = %s",
786 this, nfds, data_fd, tv_ptr, num_set_fds, error.AsCString());
794 switch (error.GetError())
796 case EBADF: // One of the descriptor sets specified an invalid descriptor.
797 return eConnectionStatusLostConnection;
799 case EINVAL: // The specified time limit is invalid. One of its components is negative or too large.
800 default: // Other unknown error
801 return eConnectionStatusError;
803 case EAGAIN: // The kernel was (perhaps temporarily) unable to
804 // allocate the requested number of file descriptors,
805 // or we have non-blocking IO
806 case EINTR: // A signal was delivered before the time limit
807 // expired and before any of the selected events
809 break; // Lets keep reading to until we timeout
812 else if (num_set_fds == 0)
814 return eConnectionStatusTimedOut;
816 else if (num_set_fds > 0)
818 // FD_ISSET is happy to deal with a something larger than
820 if (FD_ISSET(data_fd, read_fds.data()))
821 return eConnectionStatusSuccess;
822 if (have_pipe_fd && FD_ISSET(pipe_fd, read_fds.data()))
824 // We got a command to exit. Read the data from that pipe:
830 bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
831 } while (bytes_read < 0 && errno == EINTR);
832 assert (bytes_read == 1 && buffer[0] == 'q');
835 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
836 this, (int) bytes_read, buffer);
838 return eConnectionStatusEndOfFile;
845 error_ptr->SetErrorString("not connected");
846 return eConnectionStatusLostConnection;
851 // This ConnectionFileDescriptor::BytesAvailable() uses select().
854 // - select is consistent across most unix platforms
856 // - only supports file descriptors up to FD_SETSIZE. This implementation
857 // will assert if it runs into that hard limit to let users know that
858 // another ConnectionFileDescriptor::BytesAvailable() should be used
859 // or a new version of ConnectionFileDescriptor::BytesAvailable() should
860 // be written for the system that is running into the limitations. MacOSX
861 // uses kqueues, and there is a poll() based implementation below.
864 ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
866 // Don't need to take the mutex here separately since we are only called from Read. If we
867 // ever get used more generally we will need to lock here as well.
869 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
871 log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
872 struct timeval *tv_ptr;
874 if (timeout_usec == UINT32_MAX)
881 TimeValue time_value;
882 time_value.OffsetWithMicroSeconds (timeout_usec);
883 tv.tv_sec = time_value.seconds();
884 tv.tv_usec = time_value.microseconds();
888 // Make a copy of the file descriptors to make sure we don't
889 // have another thread change these values out from under us
890 // and cause problems in the loop below where like in FS_SET()
891 const int data_fd = m_fd_recv;
892 const int pipe_fd = m_pipe_read;
896 // If this assert fires off on MacOSX, we will need to switch to using
897 // libdispatch to read from file descriptors because poll() is causing
898 // kernel panics and if we exceed FD_SETSIZE we will have no choice...
900 assert (data_fd < FD_SETSIZE);
903 const bool have_pipe_fd = pipe_fd >= 0;
907 assert (pipe_fd < FD_SETSIZE);
910 while (data_fd == m_fd_recv)
914 FD_SET (data_fd, &read_fds);
916 FD_SET (pipe_fd, &read_fds);
918 const int nfds = std::max<int>(data_fd, pipe_fd) + 1;
925 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p)...",
926 this, nfds, data_fd, pipe_fd, tv_ptr);
928 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p)...",
929 this, nfds, data_fd, tv_ptr);
932 const int num_set_fds = ::select (nfds, &read_fds, NULL, NULL, tv_ptr);
934 error.SetErrorToErrno();
941 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p) => %d, error = %s",
942 this, nfds, data_fd, pipe_fd, tv_ptr, num_set_fds, error.AsCString());
944 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p) => %d, error = %s",
945 this, nfds, data_fd, tv_ptr, num_set_fds, error.AsCString());
953 switch (error.GetError())
955 case EBADF: // One of the descriptor sets specified an invalid descriptor.
956 return eConnectionStatusLostConnection;
958 case EINVAL: // The specified time limit is invalid. One of its components is negative or too large.
959 default: // Other unknown error
960 return eConnectionStatusError;
962 case EAGAIN: // The kernel was (perhaps temporarily) unable to
963 // allocate the requested number of file descriptors,
964 // or we have non-blocking IO
965 case EINTR: // A signal was delivered before the time limit
966 // expired and before any of the selected events
968 break; // Lets keep reading to until we timeout
971 else if (num_set_fds == 0)
973 return eConnectionStatusTimedOut;
975 else if (num_set_fds > 0)
977 if (FD_ISSET(data_fd, &read_fds))
978 return eConnectionStatusSuccess;
979 if (have_pipe_fd && FD_ISSET(pipe_fd, &read_fds))
981 // We got a command to exit. Read the data from that pipe:
987 bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
988 } while (bytes_read < 0 && errno == EINTR);
989 assert (bytes_read == 1 && buffer[0] == 'q');
992 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
993 this, (int) bytes_read, buffer);
995 return eConnectionStatusEndOfFile;
1002 error_ptr->SetErrorString("not connected");
1003 return eConnectionStatusLostConnection;
1011 // This ConnectionFileDescriptor::BytesAvailable() uses poll(). poll() should NOT
1012 // be used on MacOSX as it has all sorts of restrictions on the types of file descriptors
1013 // that it doesn't support.
1015 // There may be some systems that properly support poll() that could use this
1016 // implementation. I will let each system opt into this on their own.
1019 // - no restrictions on the fd value that is used
1021 // - varies wildly from platform to platform in its implementation restrictions
1024 ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
1026 // Don't need to take the mutex here separately since we are only called from Read. If we
1027 // ever get used more generally we will need to lock here as well.
1029 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1031 log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
1032 int timeout_msec = 0;
1033 if (timeout_usec == UINT32_MAX)
1038 else if (timeout_usec == 0)
1040 // Return immediately, don't wait
1045 // Convert usec to msec
1046 timeout_msec = (timeout_usec + 999) / 1000;
1049 // Make a copy of the file descriptors to make sure we don't
1050 // have another thread change these values out from under us
1051 // and cause problems in the loop below where like in FS_SET()
1052 const int data_fd = m_fd_recv;
1053 const int pipe_fd = m_pipe_read;
1055 // Make sure the file descriptor can be used with select as it
1059 const bool have_pipe_fd = pipe_fd >= 0;
1060 struct pollfd fds[2] =
1062 { data_fd, POLLIN, 0 },
1063 { pipe_fd, POLLIN, 0 }
1065 const int nfds = have_pipe_fd ? 2 : 1;
1067 while (data_fd == m_fd_recv)
1069 const int num_set_fds = ::poll (fds, nfds, timeout_msec);
1071 if (num_set_fds < 0)
1072 error.SetErrorToErrno();
1082 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::poll (fds={{%i,POLLIN},{%i,POLLIN}}, nfds=%i, timeout_ms=%i) => %d, error = %s\n",
1091 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::poll (fds={{%i,POLLIN}}, nfds=%i, timeout_ms=%i) => %d, error = %s\n",
1102 switch (error.GetError())
1104 case EBADF: // One of the descriptor sets specified an invalid descriptor.
1105 return eConnectionStatusLostConnection;
1107 case EINVAL: // The specified time limit is invalid. One of its components is negative or too large.
1108 default: // Other unknown error
1109 return eConnectionStatusError;
1111 case EAGAIN: // The kernel was (perhaps temporarily) unable to
1112 // allocate the requested number of file descriptors,
1113 // or we have non-blocking IO
1114 case EINTR: // A signal was delivered before the time limit
1115 // expired and before any of the selected events
1117 break; // Lets keep reading to until we timeout
1120 else if (num_set_fds == 0)
1122 return eConnectionStatusTimedOut;
1124 else if (num_set_fds > 0)
1126 if (fds[0].revents & POLLIN)
1127 return eConnectionStatusSuccess;
1128 if (fds[1].revents & POLLIN)
1130 // We got a command to exit. Read the data from that pipe:
1136 bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
1137 } while (bytes_read < 0 && errno == EINTR);
1138 assert (bytes_read == 1 && buffer[0] == 'q');
1141 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
1142 this, (int) bytes_read, buffer);
1144 return eConnectionStatusEndOfFile;
1150 error_ptr->SetErrorString("not connected");
1151 return eConnectionStatusLostConnection;
1157 ConnectionFileDescriptor::Close (int& fd, FDType type, Error *error_ptr)
1161 bool success = true;
1162 // Avoid taking a lock if we can
1165 Mutex::Locker locker (m_mutex);
1166 // Check the FD after the lock is taken to ensure only one thread
1167 // can get into the close scope below
1170 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1172 log->Printf ("%p ConnectionFileDescriptor::Close (fd = %i)", this,fd);
1174 if (type != eFDTypeFile)
1175 success = closesocket(fd) == 0;
1178 success = ::close (fd) == 0;
1179 // A reference to a FD was passed in, set it to an invalid value
1181 if (!success && error_ptr)
1183 // Only set the error if we have been asked to since something else
1184 // might have caused us to try and shut down the connection and may
1185 // have already set the error.
1186 error_ptr->SetErrorToErrno();
1191 return eConnectionStatusSuccess;
1193 return eConnectionStatusError;
1197 ConnectionFileDescriptor::NamedSocketAccept (const char *socket_name, Error *error_ptr)
1199 #ifndef LLDB_DISABLE_POSIX
1200 ConnectionStatus result = eConnectionStatusError;
1201 struct sockaddr_un saddr_un;
1203 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1205 int listen_socket = ::socket (AF_UNIX, SOCK_STREAM, 0);
1206 if (listen_socket == -1)
1209 error_ptr->SetErrorToErrno();
1210 return eConnectionStatusError;
1213 saddr_un.sun_family = AF_UNIX;
1214 ::strncpy(saddr_un.sun_path, socket_name, sizeof(saddr_un.sun_path) - 1);
1215 saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
1216 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
1217 saddr_un.sun_len = SUN_LEN (&saddr_un);
1220 Host::Unlink (socket_name);
1221 if (::bind (listen_socket, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) == 0)
1223 if (::listen (listen_socket, 5) == 0)
1225 m_fd_send = m_fd_recv = ::accept (listen_socket, NULL, 0);
1228 m_should_close_fd = true;
1232 result = eConnectionStatusSuccess;
1237 if (result != eConnectionStatusSuccess)
1240 error_ptr->SetErrorToErrno();
1242 // We are done with the listen port
1243 Close (listen_socket, eFDTypeSocket, NULL);
1246 return eConnectionStatusError;
1251 ConnectionFileDescriptor::NamedSocketConnect (const char *socket_name, Error *error_ptr)
1253 #ifndef LLDB_DISABLE_POSIX
1255 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1257 // Open the socket that was passed in as an option
1258 struct sockaddr_un saddr_un;
1259 m_fd_send = m_fd_recv = ::socket (AF_UNIX, SOCK_STREAM, 0);
1260 if (m_fd_send == -1)
1263 error_ptr->SetErrorToErrno();
1264 return eConnectionStatusError;
1267 saddr_un.sun_family = AF_UNIX;
1268 ::strncpy(saddr_un.sun_path, socket_name, sizeof(saddr_un.sun_path) - 1);
1269 saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
1270 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
1271 saddr_un.sun_len = SUN_LEN (&saddr_un);
1274 if (::connect (m_fd_send, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) < 0)
1277 error_ptr->SetErrorToErrno();
1279 return eConnectionStatusError;
1283 return eConnectionStatusSuccess;
1285 return eConnectionStatusError;
1290 ConnectionFileDescriptor::SocketListen (const char *host_and_port, Error *error_ptr)
1292 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1294 log->Printf ("%p ConnectionFileDescriptor::SocketListen (%s)", this, host_and_port);
1297 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1298 std::string host_str;
1299 std::string port_str;
1300 int32_t port = INT32_MIN;
1301 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr))
1303 // Might be just a port number
1304 port = Args::StringToSInt32(host_and_port, -1);
1306 return eConnectionStatusError;
1310 const sa_family_t family = AF_INET;
1311 const int socktype = SOCK_STREAM;
1312 const int protocol = IPPROTO_TCP;
1313 int listen_fd = ::socket (family, socktype, protocol);
1314 if (listen_fd == -1)
1317 error_ptr->SetErrorToErrno();
1318 return eConnectionStatusError;
1321 // enable local address reuse
1322 SetSocketOption (listen_fd, SOL_SOCKET, SO_REUSEADDR, 1);
1324 SocketAddress listen_addr;
1325 if (host_str.empty())
1326 listen_addr.SetToLocalhost(family, port);
1327 else if (host_str.compare("*") == 0)
1328 listen_addr.SetToAnyAddress(family, port);
1331 if (!listen_addr.getaddrinfo(host_str.c_str(), port_str.c_str(), family, socktype, protocol))
1334 error_ptr->SetErrorStringWithFormat("unable to resolve hostname '%s'", host_str.c_str());
1335 Close (listen_fd, eFDTypeSocket, NULL);
1336 return eConnectionStatusError;
1340 SocketAddress anyaddr;
1341 if (anyaddr.SetToAnyAddress (family, port))
1343 int err = ::bind (listen_fd, anyaddr, anyaddr.GetLength());
1347 error_ptr->SetErrorToErrno();
1348 Close (listen_fd, eFDTypeSocket, NULL);
1349 return eConnectionStatusError;
1352 err = ::listen (listen_fd, 1);
1356 error_ptr->SetErrorToErrno();
1357 Close (listen_fd, eFDTypeSocket, NULL);
1358 return eConnectionStatusError;
1361 // We were asked to listen on port zero which means we
1362 // must now read the actual port that was given to us
1363 // as port zero is a special code for "find an open port
1366 port = GetSocketPort(listen_fd);
1368 // Set the port predicate since when doing a listen://<host>:<port>
1369 // it often needs to accept the incoming connection which is a blocking
1370 // system call. Allowing access to the bound port using a predicate allows
1371 // us to wait for the port predicate to be set to a non-zero value from
1372 // another thread in an efficient manor.
1373 m_port_predicate.SetValue(port, eBroadcastAlways);
1376 bool accept_connection = false;
1378 // Loop until we are happy with our connection
1379 while (!accept_connection)
1381 struct sockaddr_in accept_addr;
1382 ::memset (&accept_addr, 0, sizeof accept_addr);
1383 #if !(defined (__linux__) || defined(_MSC_VER))
1384 accept_addr.sin_len = sizeof accept_addr;
1386 socklen_t accept_addr_len = sizeof accept_addr;
1388 int fd = ::accept (listen_fd, (struct sockaddr *)&accept_addr, &accept_addr_len);
1393 error_ptr->SetErrorToErrno();
1397 if (listen_addr.sockaddr_in().sin_addr.s_addr == INADDR_ANY)
1399 accept_connection = true;
1400 m_fd_send = m_fd_recv = fd;
1405 #if !(defined(__linux__) || (defined(_MSC_VER)))
1406 accept_addr_len == listen_addr.sockaddr_in().sin_len &&
1408 accept_addr.sin_addr.s_addr == listen_addr.sockaddr_in().sin_addr.s_addr)
1410 accept_connection = true;
1411 m_fd_send = m_fd_recv = fd;
1416 m_fd_send = m_fd_recv = -1;
1417 const uint8_t *accept_ip = (const uint8_t *)&accept_addr.sin_addr.s_addr;
1418 const uint8_t *listen_ip = (const uint8_t *)&listen_addr.sockaddr_in().sin_addr.s_addr;
1419 ::fprintf (stderr, "error: rejecting incoming connection from %u.%u.%u.%u (expecting %u.%u.%u.%u)\n",
1420 accept_ip[0], accept_ip[1], accept_ip[2], accept_ip[3],
1421 listen_ip[0], listen_ip[1], listen_ip[2], listen_ip[3]);
1426 if (m_fd_send == -1)
1428 Close (listen_fd, eFDTypeSocket, NULL);
1429 return eConnectionStatusError;
1433 // We are done with the listen port
1434 Close (listen_fd, eFDTypeSocket, NULL);
1436 m_should_close_fd = true;
1438 // Keep our TCP packets coming without any delays.
1439 SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1);
1442 return eConnectionStatusSuccess;
1446 ConnectionFileDescriptor::ConnectTCP (const char *host_and_port, Error *error_ptr)
1448 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1450 log->Printf ("%p ConnectionFileDescriptor::ConnectTCP (host/port = %s)", this, host_and_port);
1453 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1454 std::string host_str;
1455 std::string port_str;
1456 int32_t port = INT32_MIN;
1457 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr))
1458 return eConnectionStatusError;
1460 // Create the socket
1461 m_fd_send = m_fd_recv = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1462 if (m_fd_send == -1)
1465 error_ptr->SetErrorToErrno();
1466 return eConnectionStatusError;
1469 m_should_close_fd = true;
1471 // Enable local address reuse
1472 SetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, 1);
1474 struct sockaddr_in sa;
1475 ::memset (&sa, 0, sizeof (sa));
1476 sa.sin_family = AF_INET;
1477 sa.sin_port = htons (port);
1479 int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
1481 if (inet_pton_result <= 0)
1483 struct hostent *host_entry = gethostbyname (host_str.c_str());
1485 host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
1486 inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
1487 if (inet_pton_result <= 0)
1492 if (inet_pton_result == -1)
1493 error_ptr->SetErrorToErrno();
1495 error_ptr->SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str());
1499 return eConnectionStatusError;
1503 if (-1 == ::connect (m_fd_send, (const struct sockaddr *)&sa, sizeof(sa)))
1506 error_ptr->SetErrorToErrno();
1509 return eConnectionStatusError;
1512 // Keep our TCP packets coming without any delays.
1513 SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1);
1516 return eConnectionStatusSuccess;
1520 ConnectionFileDescriptor::ConnectUDP (const char *host_and_port, Error *error_ptr)
1522 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1524 log->Printf ("%p ConnectionFileDescriptor::ConnectUDP (host/port = %s)", this, host_and_port);
1527 m_fd_send_type = m_fd_recv_type = eFDTypeSocketUDP;
1529 std::string host_str;
1530 std::string port_str;
1531 int32_t port = INT32_MIN;
1532 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr))
1533 return eConnectionStatusError;
1535 // Setup the receiving end of the UDP connection on this localhost
1536 // on port zero. After we bind to port zero we can read the port.
1537 m_fd_recv = ::socket (AF_INET, SOCK_DGRAM, 0);
1538 if (m_fd_recv == -1)
1540 // Socket creation failed...
1542 error_ptr->SetErrorToErrno();
1546 // Socket was created, now lets bind to the requested port
1548 addr.SetToAnyAddress (AF_INET, 0);
1550 if (::bind (m_fd_recv, addr, addr.GetLength()) == -1)
1554 error_ptr->SetErrorToErrno();
1559 if (m_fd_recv == -1)
1560 return eConnectionStatusError;
1562 // At this point we have setup the recieve port, now we need to
1563 // setup the UDP send socket
1565 struct addrinfo hints;
1566 struct addrinfo *service_info_list = NULL;
1568 ::memset (&hints, 0, sizeof(hints));
1569 hints.ai_family = AF_INET;
1570 hints.ai_socktype = SOCK_DGRAM;
1571 int err = ::getaddrinfo (host_str.c_str(), port_str.c_str(), &hints, &service_info_list);
1575 error_ptr->SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)",
1581 return eConnectionStatusError;
1584 for (struct addrinfo *service_info_ptr = service_info_list;
1585 service_info_ptr != NULL;
1586 service_info_ptr = service_info_ptr->ai_next)
1588 m_fd_send = ::socket (service_info_ptr->ai_family,
1589 service_info_ptr->ai_socktype,
1590 service_info_ptr->ai_protocol);
1592 if (m_fd_send != -1)
1594 *m_udp_send_sockaddr = service_info_ptr;
1601 :: freeaddrinfo (service_info_list);
1603 if (m_fd_send == -1)
1606 return eConnectionStatusError;
1612 m_should_close_fd = true;
1613 return eConnectionStatusSuccess;
1617 typedef const char * set_socket_option_arg_type;
1618 typedef char * get_socket_option_arg_type;
1619 #else // #if defined(_WIN32)
1620 typedef const void * set_socket_option_arg_type;
1621 typedef void * get_socket_option_arg_type;
1622 #endif // #if defined(_WIN32)
1625 ConnectionFileDescriptor::GetSocketOption(int fd, int level, int option_name, int &option_value)
1627 get_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
1628 socklen_t option_value_size = sizeof(int);
1629 return ::getsockopt(fd, level, option_name, option_value_p, &option_value_size);
1633 ConnectionFileDescriptor::SetSocketOption(int fd, int level, int option_name, int option_value)
1635 set_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
1636 return ::setsockopt(fd, level, option_name, option_value_p, sizeof(option_value));
1640 ConnectionFileDescriptor::SetSocketReceiveTimeout (uint32_t timeout_usec)
1642 switch (m_fd_recv_type)
1644 case eFDTypeFile: // Other FD requireing read/write
1647 case eFDTypeSocket: // Socket requiring send/recv
1648 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom
1650 // Check in case timeout for m_fd has already been set to this value
1651 if (timeout_usec == m_socket_timeout_usec)
1653 //printf ("ConnectionFileDescriptor::SetSocketReceiveTimeout (timeout_usec = %u)\n", timeout_usec);
1655 struct timeval timeout;
1656 if (timeout_usec == UINT32_MAX)
1659 timeout.tv_usec = 0;
1661 else if (timeout_usec == 0)
1663 // Sending in zero does an infinite timeout, so set this as low
1664 // as we can go to get an effective zero timeout...
1666 timeout.tv_usec = 1;
1670 timeout.tv_sec = timeout_usec / TimeValue::MicroSecPerSec;
1671 timeout.tv_usec = timeout_usec % TimeValue::MicroSecPerSec;
1673 if (::setsockopt (m_fd_recv, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<get_socket_option_arg_type>(&timeout), sizeof(timeout)) == 0)
1675 m_socket_timeout_usec = timeout_usec;
1684 ConnectionFileDescriptor::GetSocketPort (int fd)
1686 // We bound to port zero, so we need to figure out which port we actually bound to
1689 SocketAddress sock_addr;
1690 socklen_t sock_addr_len = sock_addr.GetMaxLength ();
1691 if (::getsockname (fd, sock_addr, &sock_addr_len) == 0)
1692 return sock_addr.GetPort ();
1697 // If the read file descriptor is a socket, then return
1698 // the port number that is being used by the socket.
1700 ConnectionFileDescriptor::GetReadPort () const
1702 return ConnectionFileDescriptor::GetSocketPort (m_fd_recv);
1705 // If the write file descriptor is a socket, then return
1706 // the port number that is being used by the socket.
1708 ConnectionFileDescriptor::GetWritePort () const
1710 return ConnectionFileDescriptor::GetSocketPort (m_fd_send);
1714 ConnectionFileDescriptor::GetBoundPort (uint32_t timeout_sec)
1716 uint16_t bound_port = 0;
1717 if (timeout_sec == UINT32_MAX)
1718 m_port_predicate.WaitForValueNotEqualTo (0, bound_port);
1721 TimeValue timeout = TimeValue::Now();
1722 timeout.OffsetWithSeconds(timeout_sec);
1723 m_port_predicate.WaitForValueNotEqualTo (0, bound_port, &timeout);