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"
58 using namespace lldb_private;
61 DecodeHostAndPort (const char *host_and_port,
62 std::string &host_str,
63 std::string &port_str,
67 static RegularExpression g_regex ("([^:]+):([0-9]+)");
68 RegularExpression::Match regex_match(2);
69 if (g_regex.Execute (host_and_port, ®ex_match))
71 if (regex_match.GetMatchAtIndex (host_and_port, 1, host_str) &&
72 regex_match.GetMatchAtIndex (host_and_port, 2, port_str))
74 port = Args::StringToSInt32 (port_str.c_str(), INT32_MIN);
75 if (port != INT32_MIN)
87 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port);
91 ConnectionFileDescriptor::ConnectionFileDescriptor () :
95 m_fd_send_type (eFDTypeFile),
96 m_fd_recv_type (eFDTypeFile),
97 m_udp_send_sockaddr (new SocketAddress()),
98 m_should_close_fd (false),
99 m_socket_timeout_usec(0),
102 m_mutex (Mutex::eMutexTypeRecursive),
103 m_shutting_down (false)
105 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT));
107 log->Printf ("%p ConnectionFileDescriptor::ConnectionFileDescriptor ()", this);
110 ConnectionFileDescriptor::ConnectionFileDescriptor (int fd, bool owns_fd) :
114 m_fd_send_type (eFDTypeFile),
115 m_fd_recv_type (eFDTypeFile),
116 m_udp_send_sockaddr (new SocketAddress()),
117 m_should_close_fd (owns_fd),
118 m_socket_timeout_usec(0),
121 m_mutex (Mutex::eMutexTypeRecursive),
122 m_shutting_down (false)
124 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT));
126 log->Printf ("%p ConnectionFileDescriptor::ConnectionFileDescriptor (fd = %i, owns_fd = %i)", this, fd, owns_fd);
131 ConnectionFileDescriptor::~ConnectionFileDescriptor ()
133 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT));
135 log->Printf ("%p ConnectionFileDescriptor::~ConnectionFileDescriptor ()", this);
141 ConnectionFileDescriptor::OpenCommandPipe ()
145 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
146 // Make the command file descriptor here:
148 #ifndef LLDB_DISABLE_POSIX
149 int result = pipe (filedes);
156 log->Printf ("%p ConnectionFileDescriptor::OpenCommandPipe () - could not make pipe: %s",
162 m_pipe_read = filedes[0];
163 m_pipe_write = filedes[1];
165 log->Printf ("%p ConnectionFileDescriptor::OpenCommandPipe() - success readfd=%d writefd=%d",
173 ConnectionFileDescriptor::CloseCommandPipe ()
175 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
177 log->Printf ("%p ConnectionFileDescriptor::CloseCommandPipe()",
180 if (m_pipe_read != -1)
183 llvm_unreachable("pipe close unsupported in MSVC");
190 if (m_pipe_write != -1)
193 llvm_unreachable("pipe close unsupported in MSVC");
195 close (m_pipe_write);
202 ConnectionFileDescriptor::IsConnected () const
204 return m_fd_send >= 0 || m_fd_recv >= 0;
208 ConnectionFileDescriptor::Connect (const char *s, Error *error_ptr)
210 Mutex::Locker locker (m_mutex);
211 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
213 log->Printf ("%p ConnectionFileDescriptor::Connect (url = '%s')", this, s);
220 if (strstr(s, "listen://"))
222 // listen://HOST:PORT
223 unsigned long listen_port = ::strtoul(s + strlen("listen://"), &end, 0);
224 return SocketListen (listen_port, error_ptr);
226 else if (strstr(s, "unix-accept://"))
229 return NamedSocketAccept (s + strlen("unix-accept://"), error_ptr);
231 else if (strstr(s, "connect://"))
233 return ConnectTCP (s + strlen("connect://"), error_ptr);
235 else if (strstr(s, "tcp-connect://"))
237 return ConnectTCP (s + strlen("tcp-connect://"), error_ptr);
239 else if (strstr(s, "udp://"))
241 return ConnectUDP (s + strlen("udp://"), error_ptr);
243 else if (strstr(s, "fd://"))
245 // Just passing a native file descriptor within this current process
246 // that is already opened (possibly from a service or other source).
247 s += strlen ("fd://");
248 bool success = false;
249 m_fd_send = m_fd_recv = Args::StringToSInt32 (s, -1, 0, &success);
253 // We have what looks to be a valid file descriptor, but we
254 // should make sure it is. We currently are doing this by trying to
255 // get the flags from the file descriptor and making sure it
258 #ifndef LLDB_DISABLE_POSIX
259 int flags = ::fcntl (m_fd_send, F_GETFL, 0);
263 if (flags == -1 || errno == EBADF)
266 error_ptr->SetErrorStringWithFormat ("stale file descriptor: %s", s);
267 m_fd_send = m_fd_recv = -1;
268 return eConnectionStatusError;
272 // Try and get a socket option from this file descriptor to
273 // see if this is a socket and set m_is_socket accordingly.
275 bool is_socket = GetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, resuse) == 0;
277 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
278 // Don't take ownership of a file descriptor that gets passed
279 // to us since someone else opened the file descriptor and
281 // TODO: Since are using a URL to open connection we should
282 // eventually parse options using the web standard where we
283 // have "fd://123?opt1=value;opt2=value" and we can have an
284 // option be "owns=1" or "owns=0" or something like this to
285 // allow us to specify this. For now, we assume we must
286 // assume we don't own it.
287 m_should_close_fd = false;
288 return eConnectionStatusSuccess;
293 error_ptr->SetErrorStringWithFormat ("invalid file descriptor: \"fd://%s\"", s);
294 m_fd_send = m_fd_recv = -1;
295 return eConnectionStatusError;
297 else if (strstr(s, "file://"))
300 const char *path = s + strlen("file://");
301 #ifndef LLDB_DISABLE_POSIX
304 m_fd_send = m_fd_recv = ::open (path, O_RDWR);
305 } while (m_fd_send == -1 && errno == EINTR);
309 error_ptr->SetErrorToErrno();
310 return eConnectionStatusError;
313 if (::isatty(m_fd_send))
315 // Set up serial terminal emulation
316 struct termios options;
317 ::tcgetattr (m_fd_send, &options);
319 // Set port speed to maximum
320 ::cfsetospeed (&options, B115200);
321 ::cfsetispeed (&options, B115200);
323 // Raw input, disable echo and signals
324 options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
326 // Make sure only one character is needed to return from a read
327 options.c_cc[VMIN] = 1;
328 options.c_cc[VTIME] = 0;
330 ::tcsetattr (m_fd_send, TCSANOW, &options);
333 int flags = ::fcntl (m_fd_send, F_GETFL, 0);
336 if ((flags & O_NONBLOCK) == 0)
339 ::fcntl (m_fd_send, F_SETFL, flags);
342 m_should_close_fd = true;
343 return eConnectionStatusSuccess;
345 return eConnectionStatusError;
349 error_ptr->SetErrorStringWithFormat ("unsupported connection URL: '%s'", s);
350 return eConnectionStatusError;
353 error_ptr->SetErrorString("invalid connect arguments");
354 return eConnectionStatusError;
358 ConnectionFileDescriptor::Disconnect (Error *error_ptr)
360 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
362 log->Printf ("%p ConnectionFileDescriptor::Disconnect ()", this);
364 ConnectionStatus status = eConnectionStatusSuccess;
366 if (m_fd_send < 0 && m_fd_recv < 0)
369 log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Nothing to disconnect", this);
370 return eConnectionStatusSuccess;
373 // Try to get the ConnectionFileDescriptor's mutex. If we fail, that is quite likely
374 // because somebody is doing a blocking read on our file descriptor. If that's the case,
375 // then send the "q" char to the command file channel so the read will wake up and the connection
376 // will then know to shut down.
378 m_shutting_down = true;
380 Mutex::Locker locker;
381 bool got_lock= locker.TryLock (m_mutex);
385 if (m_pipe_write != -1 )
388 result = write (m_pipe_write, "q", 1);
390 log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Couldn't get the lock, sent 'q' to %d, result = %d.", this, m_pipe_write, result);
393 log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Couldn't get the lock, but no command pipe is available.", this);
394 locker.Lock (m_mutex);
397 if (m_should_close_fd == true)
399 if (m_fd_send == m_fd_recv)
401 status = Close (m_fd_send, m_fd_send_type, error_ptr);
405 // File descriptors are the different, close both if needed
407 status = Close (m_fd_send, m_fd_send_type, error_ptr);
410 ConnectionStatus recv_status = Close (m_fd_recv, m_fd_recv_type, error_ptr);
411 if (status == eConnectionStatusSuccess)
412 status = recv_status;
417 // Now set all our descriptors to invalid values.
419 m_fd_send = m_fd_recv = -1;
421 if (status != eConnectionStatusSuccess)
427 m_shutting_down = false;
428 return eConnectionStatusSuccess;
432 ConnectionFileDescriptor::Read (void *dst,
434 uint32_t timeout_usec,
435 ConnectionStatus &status,
438 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
440 log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %" PRIu64 ")...",
441 this, m_fd_recv, dst, (uint64_t)dst_len);
443 Mutex::Locker locker;
444 bool got_lock = locker.TryLock (m_mutex);
448 log->Printf ("%p ConnectionFileDescriptor::Read () failed to get the connection lock.",
451 error_ptr->SetErrorString ("failed to get the connection lock for read.");
453 status = eConnectionStatusTimedOut;
456 else if (m_shutting_down)
457 return eConnectionStatusError;
459 ssize_t bytes_read = 0;
461 status = BytesAvailable (timeout_usec, error_ptr);
462 if (status == eConnectionStatusSuccess)
466 #ifndef LLDB_DISABLE_POSIX
467 bytes_read = ::read (m_fd_recv, dst, dst_len);
469 switch (m_fd_send_type) {
471 case eFDTypeSocketUDP:
472 bytes_read = ::recv (m_fd_recv, (char*)dst, dst_len, 0);
481 } while (bytes_read < 0 && errno == EINTR);
484 if (status != eConnectionStatusSuccess)
490 error.Clear(); // End-of-file. Do not automatically close; pass along for the end-of-file handlers.
491 status = eConnectionStatusEndOfFile;
493 else if (bytes_read < 0)
495 error.SetErrorToErrno();
503 log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %" PRIu64 ") => %" PRIi64 ", error = %s",
516 uint32_t error_value = error.GetError();
519 case EAGAIN: // The file was marked for non-blocking I/O, and no data were ready to be read.
520 if (m_fd_recv_type == eFDTypeSocket || m_fd_recv_type == eFDTypeSocketUDP)
521 status = eConnectionStatusTimedOut;
523 status = eConnectionStatusSuccess;
526 case EFAULT: // Buf points outside the allocated address space.
527 case EINTR: // A read from a slow device was interrupted before any data arrived by the delivery of a signal.
528 case EINVAL: // The pointer associated with fildes was negative.
529 case EIO: // An I/O error occurred while reading from the file system.
530 // The process group is orphaned.
531 // The file is a regular file, nbyte is greater than 0,
532 // the starting position is before the end-of-file, and
533 // the starting position is greater than or equal to the
534 // offset maximum established for the open file
535 // descriptor associated with fildes.
536 case EISDIR: // An attempt is made to read a directory.
537 case ENOBUFS: // An attempt to allocate a memory buffer fails.
538 case ENOMEM: // Insufficient memory is available.
539 status = eConnectionStatusError;
540 break; // Break to close....
542 case ENOENT: // no such file or directory
543 case EBADF: // fildes is not a valid file or socket descriptor open for reading.
544 case ENXIO: // An action is requested of a device that does not exist..
545 // A requested action cannot be performed by the device.
546 case ECONNRESET:// The connection is closed by the peer during a read attempt on a socket.
547 case ENOTCONN: // A read is attempted on an unconnected socket.
548 status = eConnectionStatusLostConnection;
549 break; // Break to close....
551 case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a socket.
552 status = eConnectionStatusTimedOut;
557 log->Printf("%p ConnectionFileDescriptor::Read (), unexpected error: %s", this, strerror(error_value));
558 status = eConnectionStatusError;
559 break; // Break to close....
569 ConnectionFileDescriptor::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr)
571 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
573 log->Printf ("%p ConnectionFileDescriptor::Write (src = %p, src_len = %" PRIu64 ")", this, src, (uint64_t)src_len);
578 error_ptr->SetErrorString("not connected");
579 status = eConnectionStatusNoConnection;
586 ssize_t bytes_sent = 0;
588 switch (m_fd_send_type)
590 #ifndef LLDB_DISABLE_POSIX
591 case eFDTypeFile: // Other FD requireing read/write
594 bytes_sent = ::write (m_fd_send, src, src_len);
595 } while (bytes_sent < 0 && errno == EINTR);
598 case eFDTypeSocket: // Socket requiring send/recv
601 bytes_sent = ::send (m_fd_send, (char*)src, src_len, 0);
602 } while (bytes_sent < 0 && errno == EINTR);
605 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom
606 assert (m_udp_send_sockaddr->GetFamily() != 0);
609 bytes_sent = ::sendto (m_fd_send,
613 *m_udp_send_sockaddr,
614 m_udp_send_sockaddr->GetLength());
615 } while (bytes_sent < 0 && errno == EINTR);
620 error.SetErrorToErrno ();
626 switch (m_fd_send_type)
628 case eFDTypeFile: // Other FD requireing read/write
629 log->Printf ("%p ConnectionFileDescriptor::Write() ::write (fd = %i, src = %p, src_len = %" PRIu64 ") => %" PRIi64 " (error = %s)",
638 case eFDTypeSocket: // Socket requiring send/recv
639 log->Printf ("%p ConnectionFileDescriptor::Write() ::send (socket = %i, src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
648 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom
649 log->Printf ("%p ConnectionFileDescriptor::Write() ::sendto (socket = %i, src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
665 switch (error.GetError())
669 status = eConnectionStatusSuccess;
672 case ECONNRESET:// The connection is closed by the peer during a read attempt on a socket.
673 case ENOTCONN: // A read is attempted on an unconnected socket.
674 status = eConnectionStatusLostConnection;
675 break; // Break to close....
678 status = eConnectionStatusError;
679 break; // Break to close....
685 status = eConnectionStatusSuccess;
691 #if defined(__APPLE__)
693 // This ConnectionFileDescriptor::BytesAvailable() uses select().
696 // - select is consistent across most unix platforms
697 // - this Apple specific version allows for unlimited fds in the fd_sets by
698 // setting the _DARWIN_UNLIMITED_SELECT define prior to including the
699 // required header files.
705 ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
707 // Don't need to take the mutex here separately since we are only called from Read. If we
708 // ever get used more generally we will need to lock here as well.
710 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
712 log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
713 struct timeval *tv_ptr;
715 if (timeout_usec == UINT32_MAX)
722 TimeValue time_value;
723 time_value.OffsetWithMicroSeconds (timeout_usec);
724 tv.tv_sec = time_value.seconds();
725 tv.tv_usec = time_value.microseconds();
729 // Make a copy of the file descriptors to make sure we don't
730 // have another thread change these values out from under us
731 // and cause problems in the loop below where like in FS_SET()
732 const int data_fd = m_fd_recv;
733 const int pipe_fd = m_pipe_read;
737 const bool have_pipe_fd = pipe_fd >= 0;
739 while (data_fd == m_fd_recv)
741 const int nfds = std::max<int>(data_fd, pipe_fd) + 1;
742 llvm::SmallVector<fd_set, 1> read_fds;
743 read_fds.resize((nfds/FD_SETSIZE) + 1);
744 for (size_t i=0; i<read_fds.size(); ++i)
745 FD_ZERO (&read_fds[i]);
746 // FD_SET doesn't bounds check, it just happily walks off the end
747 // but we have taken care of making the extra storage with our
748 // SmallVector of fd_set objects
749 FD_SET (data_fd, read_fds.data());
751 FD_SET (pipe_fd, read_fds.data());
758 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p)...",
759 this, nfds, data_fd, pipe_fd, tv_ptr);
761 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p)...",
762 this, nfds, data_fd, tv_ptr);
765 const int num_set_fds = ::select (nfds, read_fds.data(), NULL, NULL, tv_ptr);
767 error.SetErrorToErrno();
774 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p) => %d, error = %s",
775 this, nfds, data_fd, pipe_fd, tv_ptr, num_set_fds, error.AsCString());
777 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p) => %d, error = %s",
778 this, nfds, data_fd, tv_ptr, num_set_fds, error.AsCString());
786 switch (error.GetError())
788 case EBADF: // One of the descriptor sets specified an invalid descriptor.
789 return eConnectionStatusLostConnection;
791 case EINVAL: // The specified time limit is invalid. One of its components is negative or too large.
792 default: // Other unknown error
793 return eConnectionStatusError;
795 case EAGAIN: // The kernel was (perhaps temporarily) unable to
796 // allocate the requested number of file descriptors,
797 // or we have non-blocking IO
798 case EINTR: // A signal was delivered before the time limit
799 // expired and before any of the selected events
801 break; // Lets keep reading to until we timeout
804 else if (num_set_fds == 0)
806 return eConnectionStatusTimedOut;
808 else if (num_set_fds > 0)
810 // FD_ISSET is happy to deal with a something larger than
812 if (FD_ISSET(data_fd, read_fds.data()))
813 return eConnectionStatusSuccess;
814 if (have_pipe_fd && FD_ISSET(pipe_fd, read_fds.data()))
816 // We got a command to exit. Read the data from that pipe:
822 bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
823 } while (bytes_read < 0 && errno == EINTR);
824 assert (bytes_read == 1 && buffer[0] == 'q');
827 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
828 this, (int) bytes_read, buffer);
830 return eConnectionStatusEndOfFile;
837 error_ptr->SetErrorString("not connected");
838 return eConnectionStatusLostConnection;
843 // This ConnectionFileDescriptor::BytesAvailable() uses select().
846 // - select is consistent across most unix platforms
848 // - only supports file descriptors up to FD_SETSIZE. This implementation
849 // will assert if it runs into that hard limit to let users know that
850 // another ConnectionFileDescriptor::BytesAvailable() should be used
851 // or a new version of ConnectionFileDescriptor::BytesAvailable() should
852 // be written for the system that is running into the limitations. MacOSX
853 // uses kqueues, and there is a poll() based implementation below.
856 ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
858 // Don't need to take the mutex here separately since we are only called from Read. If we
859 // ever get used more generally we will need to lock here as well.
861 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
863 log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
864 struct timeval *tv_ptr;
866 if (timeout_usec == UINT32_MAX)
873 TimeValue time_value;
874 time_value.OffsetWithMicroSeconds (timeout_usec);
875 tv.tv_sec = time_value.seconds();
876 tv.tv_usec = time_value.microseconds();
880 // Make a copy of the file descriptors to make sure we don't
881 // have another thread change these values out from under us
882 // and cause problems in the loop below where like in FS_SET()
883 const int data_fd = m_fd_recv;
884 const int pipe_fd = m_pipe_read;
888 // If this assert fires off on MacOSX, we will need to switch to using
889 // libdispatch to read from file descriptors because poll() is causing
890 // kernel panics and if we exceed FD_SETSIZE we will have no choice...
892 assert (data_fd < FD_SETSIZE);
895 const bool have_pipe_fd = pipe_fd >= 0;
899 assert (pipe_fd < FD_SETSIZE);
902 while (data_fd == m_fd_recv)
906 FD_SET (data_fd, &read_fds);
908 FD_SET (pipe_fd, &read_fds);
910 const int nfds = std::max<int>(data_fd, pipe_fd) + 1;
917 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p)...",
918 this, nfds, data_fd, pipe_fd, tv_ptr);
920 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p)...",
921 this, nfds, data_fd, tv_ptr);
924 const int num_set_fds = ::select (nfds, &read_fds, NULL, NULL, tv_ptr);
926 error.SetErrorToErrno();
933 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p) => %d, error = %s",
934 this, nfds, data_fd, pipe_fd, tv_ptr, num_set_fds, error.AsCString());
936 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p) => %d, error = %s",
937 this, nfds, data_fd, tv_ptr, num_set_fds, error.AsCString());
945 switch (error.GetError())
947 case EBADF: // One of the descriptor sets specified an invalid descriptor.
948 return eConnectionStatusLostConnection;
950 case EINVAL: // The specified time limit is invalid. One of its components is negative or too large.
951 default: // Other unknown error
952 return eConnectionStatusError;
954 case EAGAIN: // The kernel was (perhaps temporarily) unable to
955 // allocate the requested number of file descriptors,
956 // or we have non-blocking IO
957 case EINTR: // A signal was delivered before the time limit
958 // expired and before any of the selected events
960 break; // Lets keep reading to until we timeout
963 else if (num_set_fds == 0)
965 return eConnectionStatusTimedOut;
967 else if (num_set_fds > 0)
969 if (FD_ISSET(data_fd, &read_fds))
970 return eConnectionStatusSuccess;
971 if (have_pipe_fd && FD_ISSET(pipe_fd, &read_fds))
973 // We got a command to exit. Read the data from that pipe:
979 bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
980 } while (bytes_read < 0 && errno == EINTR);
981 assert (bytes_read == 1 && buffer[0] == 'q');
984 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
985 this, (int) bytes_read, buffer);
987 return eConnectionStatusEndOfFile;
994 error_ptr->SetErrorString("not connected");
995 return eConnectionStatusLostConnection;
1003 // This ConnectionFileDescriptor::BytesAvailable() uses poll(). poll() should NOT
1004 // be used on MacOSX as it has all sorts of restrictions on the types of file descriptors
1005 // that it doesn't support.
1007 // There may be some systems that properly support poll() that could use this
1008 // implementation. I will let each system opt into this on their own.
1011 // - no restrictions on the fd value that is used
1013 // - varies wildly from platform to platform in its implementation restrictions
1016 ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
1018 // Don't need to take the mutex here separately since we are only called from Read. If we
1019 // ever get used more generally we will need to lock here as well.
1021 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1023 log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
1024 int timeout_msec = 0;
1025 if (timeout_usec == UINT32_MAX)
1030 else if (timeout_usec == 0)
1032 // Return immediately, don't wait
1037 // Convert usec to msec
1038 timeout_msec = (timeout_usec + 999) / 1000;
1041 // Make a copy of the file descriptors to make sure we don't
1042 // have another thread change these values out from under us
1043 // and cause problems in the loop below where like in FS_SET()
1044 const int data_fd = m_fd_recv;
1045 const int pipe_fd = m_pipe_read;
1047 // Make sure the file descriptor can be used with select as it
1051 const bool have_pipe_fd = pipe_fd >= 0;
1052 struct pollfd fds[2] =
1054 { data_fd, POLLIN, 0 },
1055 { pipe_fd, POLLIN, 0 }
1057 const int nfds = have_pipe_fd ? 2 : 1;
1059 while (data_fd == m_fd_recv)
1061 const int num_set_fds = ::poll (fds, nfds, timeout_msec);
1063 if (num_set_fds < 0)
1064 error.SetErrorToErrno();
1074 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::poll (fds={{%i,POLLIN},{%i,POLLIN}}, nfds=%i, timeout_ms=%i) => %d, error = %s\n",
1083 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::poll (fds={{%i,POLLIN}}, nfds=%i, timeout_ms=%i) => %d, error = %s\n",
1094 switch (error.GetError())
1096 case EBADF: // One of the descriptor sets specified an invalid descriptor.
1097 return eConnectionStatusLostConnection;
1099 case EINVAL: // The specified time limit is invalid. One of its components is negative or too large.
1100 default: // Other unknown error
1101 return eConnectionStatusError;
1103 case EAGAIN: // The kernel was (perhaps temporarily) unable to
1104 // allocate the requested number of file descriptors,
1105 // or we have non-blocking IO
1106 case EINTR: // A signal was delivered before the time limit
1107 // expired and before any of the selected events
1109 break; // Lets keep reading to until we timeout
1112 else if (num_set_fds == 0)
1114 return eConnectionStatusTimedOut;
1116 else if (num_set_fds > 0)
1118 if (fds[0].revents & POLLIN)
1119 return eConnectionStatusSuccess;
1120 if (fds[1].revents & POLLIN)
1122 // We got a command to exit. Read the data from that pipe:
1128 bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
1129 } while (bytes_read < 0 && errno == EINTR);
1130 assert (bytes_read == 1 && buffer[0] == 'q');
1133 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
1134 this, (int) bytes_read, buffer);
1136 return eConnectionStatusEndOfFile;
1142 error_ptr->SetErrorString("not connected");
1143 return eConnectionStatusLostConnection;
1149 ConnectionFileDescriptor::Close (int& fd, FDType type, Error *error_ptr)
1153 bool success = true;
1154 // Avoid taking a lock if we can
1157 Mutex::Locker locker (m_mutex);
1158 // Check the FD after the lock is taken to ensure only one thread
1159 // can get into the close scope below
1162 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1164 log->Printf ("%p ConnectionFileDescriptor::Close (fd = %i)", this,fd);
1166 if (type != eFDTypeFile)
1167 success = closesocket(fd) == 0;
1170 success = ::close (fd) == 0;
1171 // A reference to a FD was passed in, set it to an invalid value
1173 if (!success && error_ptr)
1175 // Only set the error if we have been asked to since something else
1176 // might have caused us to try and shut down the connection and may
1177 // have already set the error.
1178 error_ptr->SetErrorToErrno();
1183 return eConnectionStatusSuccess;
1185 return eConnectionStatusError;
1189 ConnectionFileDescriptor::NamedSocketAccept (const char *socket_name, Error *error_ptr)
1191 #ifndef LLDB_DISABLE_POSIX
1192 ConnectionStatus result = eConnectionStatusError;
1193 struct sockaddr_un saddr_un;
1195 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1197 int listen_socket = ::socket (AF_UNIX, SOCK_STREAM, 0);
1198 if (listen_socket == -1)
1201 error_ptr->SetErrorToErrno();
1202 return eConnectionStatusError;
1205 saddr_un.sun_family = AF_UNIX;
1206 ::strncpy(saddr_un.sun_path, socket_name, sizeof(saddr_un.sun_path) - 1);
1207 saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
1208 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
1209 saddr_un.sun_len = SUN_LEN (&saddr_un);
1212 if (::bind (listen_socket, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) == 0)
1214 if (::listen (listen_socket, 5) == 0)
1216 m_fd_send = m_fd_recv = ::accept (listen_socket, NULL, 0);
1219 m_should_close_fd = true;
1223 result = eConnectionStatusSuccess;
1228 if (result != eConnectionStatusSuccess)
1231 error_ptr->SetErrorToErrno();
1233 // We are done with the listen port
1234 Close (listen_socket, eFDTypeSocket, NULL);
1237 return eConnectionStatusError;
1242 ConnectionFileDescriptor::NamedSocketConnect (const char *socket_name, Error *error_ptr)
1244 #ifndef LLDB_DISABLE_POSIX
1246 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1248 // Open the socket that was passed in as an option
1249 struct sockaddr_un saddr_un;
1250 m_fd_send = m_fd_recv = ::socket (AF_UNIX, SOCK_STREAM, 0);
1251 if (m_fd_send == -1)
1254 error_ptr->SetErrorToErrno();
1255 return eConnectionStatusError;
1258 saddr_un.sun_family = AF_UNIX;
1259 ::strncpy(saddr_un.sun_path, socket_name, sizeof(saddr_un.sun_path) - 1);
1260 saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
1261 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
1262 saddr_un.sun_len = SUN_LEN (&saddr_un);
1265 if (::connect (m_fd_send, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) < 0)
1268 error_ptr->SetErrorToErrno();
1270 return eConnectionStatusError;
1274 return eConnectionStatusSuccess;
1276 return eConnectionStatusError;
1281 ConnectionFileDescriptor::SocketListen (uint16_t listen_port_num, Error *error_ptr)
1283 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1285 log->Printf ("%p ConnectionFileDescriptor::SocketListen (port = %i)", this, listen_port_num);
1288 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1289 int listen_port = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1290 if (listen_port == -1)
1293 error_ptr->SetErrorToErrno();
1294 return eConnectionStatusError;
1297 // enable local address reuse
1298 SetSocketOption (listen_port, SOL_SOCKET, SO_REUSEADDR, 1);
1300 SocketAddress localhost;
1301 if (localhost.SetToLocalhost (AF_INET, listen_port_num))
1303 int err = ::bind (listen_port, localhost, localhost.GetLength());
1307 error_ptr->SetErrorToErrno();
1308 Close (listen_port, eFDTypeSocket, NULL);
1309 return eConnectionStatusError;
1312 err = ::listen (listen_port, 1);
1316 error_ptr->SetErrorToErrno();
1317 Close (listen_port, eFDTypeSocket, NULL);
1318 return eConnectionStatusError;
1321 m_fd_send = m_fd_recv = ::accept (listen_port, NULL, 0);
1322 if (m_fd_send == -1)
1325 error_ptr->SetErrorToErrno();
1326 Close (listen_port, eFDTypeSocket, NULL);
1327 return eConnectionStatusError;
1331 // We are done with the listen port
1332 Close (listen_port, eFDTypeSocket, NULL);
1334 m_should_close_fd = true;
1336 // Keep our TCP packets coming without any delays.
1337 SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1);
1340 return eConnectionStatusSuccess;
1344 ConnectionFileDescriptor::ConnectTCP (const char *host_and_port, Error *error_ptr)
1346 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1348 log->Printf ("%p ConnectionFileDescriptor::ConnectTCP (host/port = %s)", this, host_and_port);
1351 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1352 std::string host_str;
1353 std::string port_str;
1354 int32_t port = INT32_MIN;
1355 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr))
1356 return eConnectionStatusError;
1358 // Create the socket
1359 m_fd_send = m_fd_recv = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1360 if (m_fd_send == -1)
1363 error_ptr->SetErrorToErrno();
1364 return eConnectionStatusError;
1367 m_should_close_fd = true;
1369 // Enable local address reuse
1370 SetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, 1);
1372 struct sockaddr_in sa;
1373 ::memset (&sa, 0, sizeof (sa));
1374 sa.sin_family = AF_INET;
1375 sa.sin_port = htons (port);
1377 int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
1379 if (inet_pton_result <= 0)
1381 struct hostent *host_entry = gethostbyname (host_str.c_str());
1383 host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
1384 inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
1385 if (inet_pton_result <= 0)
1390 if (inet_pton_result == -1)
1391 error_ptr->SetErrorToErrno();
1393 error_ptr->SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str());
1397 return eConnectionStatusError;
1401 if (-1 == ::connect (m_fd_send, (const struct sockaddr *)&sa, sizeof(sa)))
1404 error_ptr->SetErrorToErrno();
1407 return eConnectionStatusError;
1410 // Keep our TCP packets coming without any delays.
1411 SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1);
1414 return eConnectionStatusSuccess;
1418 ConnectionFileDescriptor::ConnectUDP (const char *host_and_port, Error *error_ptr)
1420 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1422 log->Printf ("%p ConnectionFileDescriptor::ConnectUDP (host/port = %s)", this, host_and_port);
1425 m_fd_send_type = m_fd_recv_type = eFDTypeSocketUDP;
1427 std::string host_str;
1428 std::string port_str;
1429 int32_t port = INT32_MIN;
1430 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr))
1431 return eConnectionStatusError;
1433 // Setup the receiving end of the UDP connection on this localhost
1434 // on port zero. After we bind to port zero we can read the port.
1435 m_fd_recv = ::socket (AF_INET, SOCK_DGRAM, 0);
1436 if (m_fd_recv == -1)
1438 // Socket creation failed...
1440 error_ptr->SetErrorToErrno();
1444 // Socket was created, now lets bind to the requested port
1446 addr.SetToLocalhost (AF_INET, 0);
1448 if (::bind (m_fd_recv, addr, addr.GetLength()) == -1)
1452 error_ptr->SetErrorToErrno();
1457 if (m_fd_recv == -1)
1458 return eConnectionStatusError;
1460 // At this point we have setup the recieve port, now we need to
1461 // setup the UDP send socket
1463 struct addrinfo hints;
1464 struct addrinfo *service_info_list = NULL;
1466 ::memset (&hints, 0, sizeof(hints));
1467 hints.ai_family = AF_INET;
1468 hints.ai_socktype = SOCK_DGRAM;
1469 int err = ::getaddrinfo (host_str.c_str(), port_str.c_str(), &hints, &service_info_list);
1473 error_ptr->SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)",
1479 return eConnectionStatusError;
1482 for (struct addrinfo *service_info_ptr = service_info_list;
1483 service_info_ptr != NULL;
1484 service_info_ptr = service_info_ptr->ai_next)
1486 m_fd_send = ::socket (service_info_ptr->ai_family,
1487 service_info_ptr->ai_socktype,
1488 service_info_ptr->ai_protocol);
1490 if (m_fd_send != -1)
1492 *m_udp_send_sockaddr = service_info_ptr;
1499 :: freeaddrinfo (service_info_list);
1501 if (m_fd_send == -1)
1504 return eConnectionStatusError;
1510 m_should_close_fd = true;
1511 return eConnectionStatusSuccess;
1515 typedef const char * set_socket_option_arg_type;
1516 typedef char * get_socket_option_arg_type;
1517 #else // #if defined(_WIN32)
1518 typedef const void * set_socket_option_arg_type;
1519 typedef void * get_socket_option_arg_type;
1520 #endif // #if defined(_WIN32)
1523 ConnectionFileDescriptor::GetSocketOption(int fd, int level, int option_name, int &option_value)
1525 get_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
1526 socklen_t option_value_size = sizeof(int);
1527 return ::getsockopt(fd, level, option_name, option_value_p, &option_value_size);
1531 ConnectionFileDescriptor::SetSocketOption(int fd, int level, int option_name, int option_value)
1533 set_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
1534 return ::setsockopt(fd, level, option_name, option_value_p, sizeof(option_value));
1538 ConnectionFileDescriptor::SetSocketReceiveTimeout (uint32_t timeout_usec)
1540 switch (m_fd_recv_type)
1542 case eFDTypeFile: // Other FD requireing read/write
1545 case eFDTypeSocket: // Socket requiring send/recv
1546 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom
1548 // Check in case timeout for m_fd has already been set to this value
1549 if (timeout_usec == m_socket_timeout_usec)
1551 //printf ("ConnectionFileDescriptor::SetSocketReceiveTimeout (timeout_usec = %u)\n", timeout_usec);
1553 struct timeval timeout;
1554 if (timeout_usec == UINT32_MAX)
1557 timeout.tv_usec = 0;
1559 else if (timeout_usec == 0)
1561 // Sending in zero does an infinite timeout, so set this as low
1562 // as we can go to get an effective zero timeout...
1564 timeout.tv_usec = 1;
1568 timeout.tv_sec = timeout_usec / TimeValue::MicroSecPerSec;
1569 timeout.tv_usec = timeout_usec % TimeValue::MicroSecPerSec;
1571 if (::setsockopt (m_fd_recv, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<get_socket_option_arg_type>(&timeout), sizeof(timeout)) == 0)
1573 m_socket_timeout_usec = timeout_usec;
1582 ConnectionFileDescriptor::GetSocketPort (int fd)
1584 // We bound to port zero, so we need to figure out which port we actually bound to
1585 SocketAddress sock_addr;
1586 socklen_t sock_addr_len = sock_addr.GetMaxLength ();
1587 if (::getsockname (fd, sock_addr, &sock_addr_len) == 0)
1588 return sock_addr.GetPort ();
1593 // If the read file descriptor is a socket, then return
1594 // the port number that is being used by the socket.
1596 ConnectionFileDescriptor::GetReadPort () const
1598 return ConnectionFileDescriptor::GetSocketPort (m_fd_recv);
1601 // If the write file descriptor is a socket, then return
1602 // the port number that is being used by the socket.
1604 ConnectionFileDescriptor::GetWritePort () const
1606 return ConnectionFileDescriptor::GetSocketPort (m_fd_send);