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"
22 #include <arpa/inet.h>
24 #include <netinet/in.h>
25 #include <netinet/tcp.h>
26 #include <sys/socket.h>
29 #include <sys/types.h>
35 // Other libraries and framework includes
36 #if defined(__APPLE__)
37 #include "llvm/ADT/SmallVector.h"
40 #include "lldb/lldb-private-log.h"
41 #include "lldb/Interpreter/Args.h"
42 #include "lldb/Core/Communication.h"
43 #include "lldb/Core/Log.h"
44 #include "lldb/Core/RegularExpression.h"
45 #include "lldb/Core/Timer.h"
48 using namespace lldb_private;
51 DecodeHostAndPort (const char *host_and_port,
52 std::string &host_str,
53 std::string &port_str,
57 static RegularExpression g_regex ("([^:]+):([0-9]+)");
58 RegularExpression::Match regex_match(2);
59 if (g_regex.Execute (host_and_port, ®ex_match))
61 if (regex_match.GetMatchAtIndex (host_and_port, 1, host_str) &&
62 regex_match.GetMatchAtIndex (host_and_port, 2, port_str))
64 port = Args::StringToSInt32 (port_str.c_str(), INT32_MIN);
65 if (port != INT32_MIN)
77 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port);
81 ConnectionFileDescriptor::ConnectionFileDescriptor () :
85 m_fd_send_type (eFDTypeFile),
86 m_fd_recv_type (eFDTypeFile),
87 m_udp_send_sockaddr (),
88 m_should_close_fd (false),
89 m_socket_timeout_usec(0),
92 m_mutex (Mutex::eMutexTypeRecursive),
93 m_shutting_down (false)
95 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT));
97 log->Printf ("%p ConnectionFileDescriptor::ConnectionFileDescriptor ()", this);
100 ConnectionFileDescriptor::ConnectionFileDescriptor (int fd, bool owns_fd) :
104 m_fd_send_type (eFDTypeFile),
105 m_fd_recv_type (eFDTypeFile),
106 m_udp_send_sockaddr (),
107 m_should_close_fd (owns_fd),
108 m_socket_timeout_usec(0),
111 m_mutex (Mutex::eMutexTypeRecursive),
112 m_shutting_down (false)
114 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT));
116 log->Printf ("%p ConnectionFileDescriptor::ConnectionFileDescriptor (fd = %i, owns_fd = %i)", this, fd, owns_fd);
121 ConnectionFileDescriptor::~ConnectionFileDescriptor ()
123 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT));
125 log->Printf ("%p ConnectionFileDescriptor::~ConnectionFileDescriptor ()", this);
131 ConnectionFileDescriptor::OpenCommandPipe ()
135 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
136 // Make the command file descriptor here:
138 int result = pipe (filedes);
142 log->Printf ("%p ConnectionFileDescriptor::ConnectionFileDescriptor () - could not make pipe: %s",
148 m_pipe_read = filedes[0];
149 m_pipe_write = filedes[1];
154 ConnectionFileDescriptor::CloseCommandPipe ()
156 if (m_pipe_read != -1)
162 if (m_pipe_write != -1)
164 close (m_pipe_write);
170 ConnectionFileDescriptor::IsConnected () const
172 return m_fd_send >= 0 || m_fd_recv >= 0;
176 ConnectionFileDescriptor::Connect (const char *s, Error *error_ptr)
178 Mutex::Locker locker (m_mutex);
179 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
181 log->Printf ("%p ConnectionFileDescriptor::Connect (url = '%s')", this, s);
188 if (strstr(s, "listen://"))
190 // listen://HOST:PORT
191 unsigned long listen_port = ::strtoul(s + strlen("listen://"), &end, 0);
192 return SocketListen (listen_port, error_ptr);
194 else if (strstr(s, "unix-accept://"))
197 return NamedSocketAccept (s + strlen("unix-accept://"), error_ptr);
199 else if (strstr(s, "connect://"))
201 return ConnectTCP (s + strlen("connect://"), error_ptr);
203 else if (strstr(s, "tcp-connect://"))
205 return ConnectTCP (s + strlen("tcp-connect://"), error_ptr);
207 else if (strstr(s, "udp://"))
209 return ConnectUDP (s + strlen("udp://"), error_ptr);
211 else if (strstr(s, "fd://"))
213 // Just passing a native file descriptor within this current process
214 // that is already opened (possibly from a service or other source).
215 s += strlen ("fd://");
216 bool success = false;
217 m_fd_send = m_fd_recv = Args::StringToSInt32 (s, -1, 0, &success);
221 // We have what looks to be a valid file descriptor, but we
222 // should make sure it is. We currently are doing this by trying to
223 // get the flags from the file descriptor and making sure it
226 int flags = ::fcntl (m_fd_send, F_GETFL, 0);
227 if (flags == -1 || errno == EBADF)
230 error_ptr->SetErrorStringWithFormat ("stale file descriptor: %s", s);
231 m_fd_send = m_fd_recv = -1;
232 return eConnectionStatusError;
236 // Try and get a socket option from this file descriptor to
237 // see if this is a socket and set m_is_socket accordingly.
239 bool is_socket = GetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, resuse) == 0;
241 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
242 // Don't take ownership of a file descriptor that gets passed
243 // to us since someone else opened the file descriptor and
245 // TODO: Since are using a URL to open connection we should
246 // eventually parse options using the web standard where we
247 // have "fd://123?opt1=value;opt2=value" and we can have an
248 // option be "owns=1" or "owns=0" or something like this to
249 // allow us to specify this. For now, we assume we must
250 // assume we don't own it.
251 m_should_close_fd = false;
252 return eConnectionStatusSuccess;
257 error_ptr->SetErrorStringWithFormat ("invalid file descriptor: \"fd://%s\"", s);
258 m_fd_send = m_fd_recv = -1;
259 return eConnectionStatusError;
261 else if (strstr(s, "file://"))
264 const char *path = s + strlen("file://");
267 m_fd_send = m_fd_recv = ::open (path, O_RDWR);
268 } while (m_fd_send == -1 && errno == EINTR);
272 error_ptr->SetErrorToErrno();
273 return eConnectionStatusError;
276 if (::isatty(m_fd_send))
278 // Set up serial terminal emulation
279 struct termios options;
280 ::tcgetattr (m_fd_send, &options);
282 // Set port speed to maximum
283 ::cfsetospeed (&options, B115200);
284 ::cfsetispeed (&options, B115200);
286 // Raw input, disable echo and signals
287 options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
289 // Make sure only one character is needed to return from a read
290 options.c_cc[VMIN] = 1;
291 options.c_cc[VTIME] = 0;
293 ::tcsetattr (m_fd_send, TCSANOW, &options);
296 int flags = ::fcntl (m_fd_send, F_GETFL, 0);
299 if ((flags & O_NONBLOCK) == 0)
302 ::fcntl (m_fd_send, F_SETFL, flags);
305 m_should_close_fd = true;
306 return eConnectionStatusSuccess;
309 error_ptr->SetErrorStringWithFormat ("unsupported connection URL: '%s'", s);
310 return eConnectionStatusError;
313 error_ptr->SetErrorString("invalid connect arguments");
314 return eConnectionStatusError;
318 ConnectionFileDescriptor::Disconnect (Error *error_ptr)
320 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
322 log->Printf ("%p ConnectionFileDescriptor::Disconnect ()", this);
324 ConnectionStatus status = eConnectionStatusSuccess;
326 if (m_fd_send < 0 && m_fd_recv < 0)
329 log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Nothing to disconnect", this);
330 return eConnectionStatusSuccess;
333 // Try to get the ConnectionFileDescriptor's mutex. If we fail, that is quite likely
334 // because somebody is doing a blocking read on our file descriptor. If that's the case,
335 // then send the "q" char to the command file channel so the read will wake up and the connection
336 // will then know to shut down.
338 m_shutting_down = true;
340 Mutex::Locker locker;
341 bool got_lock= locker.TryLock (m_mutex);
345 if (m_pipe_write != -1 )
347 write (m_pipe_write, "q", 1);
348 close (m_pipe_write);
351 locker.Lock (m_mutex);
354 if (m_should_close_fd == true)
356 if (m_fd_send == m_fd_recv)
358 status = Close (m_fd_send, error_ptr);
362 // File descriptors are the different, close both if needed
364 status = Close (m_fd_send, error_ptr);
367 ConnectionStatus recv_status = Close (m_fd_recv, error_ptr);
368 if (status == eConnectionStatusSuccess)
369 status = recv_status;
374 // Now set all our descriptors to invalid values.
376 m_fd_send = m_fd_recv = -1;
378 if (status != eConnectionStatusSuccess)
384 m_shutting_down = false;
385 return eConnectionStatusSuccess;
389 ConnectionFileDescriptor::Read (void *dst,
391 uint32_t timeout_usec,
392 ConnectionStatus &status,
395 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
397 log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %" PRIu64 ")...",
398 this, m_fd_recv, dst, (uint64_t)dst_len);
400 Mutex::Locker locker;
401 bool got_lock = locker.TryLock (m_mutex);
405 log->Printf ("%p ConnectionFileDescriptor::Read () failed to get the connection lock.",
408 error_ptr->SetErrorString ("failed to get the connection lock for read.");
410 status = eConnectionStatusTimedOut;
413 else if (m_shutting_down)
414 return eConnectionStatusError;
416 ssize_t bytes_read = 0;
418 status = BytesAvailable (timeout_usec, error_ptr);
419 if (status == eConnectionStatusSuccess)
423 bytes_read = ::read (m_fd_recv, dst, dst_len);
424 } while (bytes_read < 0 && errno == EINTR);
427 if (status != eConnectionStatusSuccess)
433 error.Clear(); // End-of-file. Do not automatically close; pass along for the end-of-file handlers.
434 status = eConnectionStatusEndOfFile;
436 else if (bytes_read < 0)
438 error.SetErrorToErrno();
446 log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %" PRIu64 ") => %" PRIi64 ", error = %s",
459 uint32_t error_value = error.GetError();
462 case EAGAIN: // The file was marked for non-blocking I/O, and no data were ready to be read.
463 if (m_fd_recv_type == eFDTypeSocket || m_fd_recv_type == eFDTypeSocketUDP)
464 status = eConnectionStatusTimedOut;
466 status = eConnectionStatusSuccess;
469 case EFAULT: // Buf points outside the allocated address space.
470 case EINTR: // A read from a slow device was interrupted before any data arrived by the delivery of a signal.
471 case EINVAL: // The pointer associated with fildes was negative.
472 case EIO: // An I/O error occurred while reading from the file system.
473 // The process group is orphaned.
474 // The file is a regular file, nbyte is greater than 0,
475 // the starting position is before the end-of-file, and
476 // the starting position is greater than or equal to the
477 // offset maximum established for the open file
478 // descriptor associated with fildes.
479 case EISDIR: // An attempt is made to read a directory.
480 case ENOBUFS: // An attempt to allocate a memory buffer fails.
481 case ENOMEM: // Insufficient memory is available.
482 status = eConnectionStatusError;
483 break; // Break to close....
485 case ENOENT: // no such file or directory
486 case EBADF: // fildes is not a valid file or socket descriptor open for reading.
487 case ENXIO: // An action is requested of a device that does not exist..
488 // A requested action cannot be performed by the device.
489 case ECONNRESET:// The connection is closed by the peer during a read attempt on a socket.
490 case ENOTCONN: // A read is attempted on an unconnected socket.
491 status = eConnectionStatusLostConnection;
492 break; // Break to close....
494 case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a socket.
495 status = eConnectionStatusTimedOut;
505 ConnectionFileDescriptor::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr)
507 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
509 log->Printf ("%p ConnectionFileDescriptor::Write (src = %p, src_len = %" PRIu64 ")", this, src, (uint64_t)src_len);
514 error_ptr->SetErrorString("not connected");
515 status = eConnectionStatusNoConnection;
522 ssize_t bytes_sent = 0;
524 switch (m_fd_send_type)
526 case eFDTypeFile: // Other FD requireing read/write
529 bytes_sent = ::write (m_fd_send, src, src_len);
530 } while (bytes_sent < 0 && errno == EINTR);
533 case eFDTypeSocket: // Socket requiring send/recv
536 bytes_sent = ::send (m_fd_send, src, src_len, 0);
537 } while (bytes_sent < 0 && errno == EINTR);
540 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom
541 assert (m_udp_send_sockaddr.GetFamily() != 0);
544 bytes_sent = ::sendto (m_fd_send,
549 m_udp_send_sockaddr.GetLength());
550 } while (bytes_sent < 0 && errno == EINTR);
555 error.SetErrorToErrno ();
561 switch (m_fd_send_type)
563 case eFDTypeFile: // Other FD requireing read/write
564 log->Printf ("%p ConnectionFileDescriptor::Write() ::write (fd = %i, src = %p, src_len = %" PRIu64 ") => %" PRIi64 " (error = %s)",
573 case eFDTypeSocket: // Socket requiring send/recv
574 log->Printf ("%p ConnectionFileDescriptor::Write() ::send (socket = %i, src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
583 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom
584 log->Printf ("%p ConnectionFileDescriptor::Write() ::sendto (socket = %i, src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
600 switch (error.GetError())
604 status = eConnectionStatusSuccess;
607 case ECONNRESET:// The connection is closed by the peer during a read attempt on a socket.
608 case ENOTCONN: // A read is attempted on an unconnected socket.
609 status = eConnectionStatusLostConnection;
610 break; // Break to close....
613 status = eConnectionStatusError;
614 break; // Break to close....
620 status = eConnectionStatusSuccess;
626 #if defined(__APPLE__)
628 // This ConnectionFileDescriptor::BytesAvailable() uses select().
631 // - select is consistent across most unix platforms
632 // - this Apple specific version allows for unlimited fds in the fd_sets by
633 // setting the _DARWIN_UNLIMITED_SELECT define prior to including the
634 // required header files.
640 ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
642 // Don't need to take the mutex here separately since we are only called from Read. If we
643 // ever get used more generally we will need to lock here as well.
645 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
647 log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
648 struct timeval *tv_ptr;
650 if (timeout_usec == UINT32_MAX)
657 TimeValue time_value;
658 time_value.OffsetWithMicroSeconds (timeout_usec);
659 tv = time_value.GetAsTimeVal();
663 // Make a copy of the file descriptors to make sure we don't
664 // have another thread change these values out from under us
665 // and cause problems in the loop below where like in FS_SET()
666 const int data_fd = m_fd_recv;
667 const int pipe_fd = m_pipe_read;
671 const bool have_pipe_fd = pipe_fd >= 0;
673 while (data_fd == m_fd_recv)
675 const int nfds = std::max<int>(data_fd, pipe_fd) + 1;
676 llvm::SmallVector<fd_set, 1> read_fds;
677 read_fds.resize((nfds/FD_SETSIZE) + 1);
678 for (size_t i=0; i<read_fds.size(); ++i)
679 FD_ZERO (&read_fds[i]);
680 // FD_SET doesn't bounds check, it just happily walks off the end
681 // but we have taken care of making the extra storage with our
682 // SmallVector of fd_set objects
683 FD_SET (data_fd, read_fds.data());
685 FD_SET (pipe_fd, read_fds.data());
692 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p)...",
693 this, nfds, data_fd, pipe_fd, tv_ptr);
695 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p)...",
696 this, nfds, data_fd, tv_ptr);
699 const int num_set_fds = ::select (nfds, read_fds.data(), NULL, NULL, tv_ptr);
701 error.SetErrorToErrno();
708 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p) => %d, error = %s",
709 this, nfds, data_fd, pipe_fd, tv_ptr, num_set_fds, error.AsCString());
711 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p) => %d, error = %s",
712 this, nfds, data_fd, tv_ptr, num_set_fds, error.AsCString());
720 switch (error.GetError())
722 case EBADF: // One of the descriptor sets specified an invalid descriptor.
723 return eConnectionStatusLostConnection;
725 case EINVAL: // The specified time limit is invalid. One of its components is negative or too large.
726 default: // Other unknown error
727 return eConnectionStatusError;
729 case EAGAIN: // The kernel was (perhaps temporarily) unable to
730 // allocate the requested number of file descriptors,
731 // or we have non-blocking IO
732 case EINTR: // A signal was delivered before the time limit
733 // expired and before any of the selected events
735 break; // Lets keep reading to until we timeout
738 else if (num_set_fds == 0)
740 return eConnectionStatusTimedOut;
742 else if (num_set_fds > 0)
744 // FD_ISSET is happy to deal with a something larger than
746 if (FD_ISSET(data_fd, read_fds.data()))
747 return eConnectionStatusSuccess;
748 if (have_pipe_fd && FD_ISSET(pipe_fd, read_fds.data()))
750 // We got a command to exit. Read the data from that pipe:
756 bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
757 } while (bytes_read < 0 && errno == EINTR);
758 assert (bytes_read == 1 && buffer[0] == 'q');
761 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
762 this, (int) bytes_read, buffer);
764 return eConnectionStatusEndOfFile;
771 error_ptr->SetErrorString("not connected");
772 return eConnectionStatusLostConnection;
777 // This ConnectionFileDescriptor::BytesAvailable() uses select().
780 // - select is consistent across most unix platforms
782 // - only supports file descriptors up to FD_SETSIZE. This implementation
783 // will assert if it runs into that hard limit to let users know that
784 // another ConnectionFileDescriptor::BytesAvailable() should be used
785 // or a new version of ConnectionFileDescriptor::BytesAvailable() should
786 // be written for the system that is running into the limitations. MacOSX
787 // uses kqueues, and there is a poll() based implementation below.
790 ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
792 // Don't need to take the mutex here separately since we are only called from Read. If we
793 // ever get used more generally we will need to lock here as well.
795 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
797 log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
798 struct timeval *tv_ptr;
800 if (timeout_usec == UINT32_MAX)
807 TimeValue time_value;
808 time_value.OffsetWithMicroSeconds (timeout_usec);
809 tv = time_value.GetAsTimeVal();
813 // Make a copy of the file descriptors to make sure we don't
814 // have another thread change these values out from under us
815 // and cause problems in the loop below where like in FS_SET()
816 const int data_fd = m_fd_recv;
817 const int pipe_fd = m_pipe_read;
821 // If this assert fires off on MacOSX, we will need to switch to using
822 // libdispatch to read from file descriptors because poll() is causing
823 // kernel panics and if we exceed FD_SETSIZE we will have no choice...
824 assert (data_fd < FD_SETSIZE);
826 const bool have_pipe_fd = pipe_fd >= 0;
830 assert (pipe_fd < FD_SETSIZE);
833 while (data_fd == m_fd_recv)
837 FD_SET (data_fd, &read_fds);
839 FD_SET (pipe_fd, &read_fds);
841 const int nfds = std::max<int>(data_fd, pipe_fd) + 1;
848 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p)...",
849 this, nfds, data_fd, pipe_fd, tv_ptr);
851 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p)...",
852 this, nfds, data_fd, tv_ptr);
855 const int num_set_fds = ::select (nfds, &read_fds, NULL, NULL, tv_ptr);
857 error.SetErrorToErrno();
864 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p) => %d, error = %s",
865 this, nfds, data_fd, pipe_fd, tv_ptr, num_set_fds, error.AsCString());
867 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p) => %d, error = %s",
868 this, nfds, data_fd, tv_ptr, num_set_fds, error.AsCString());
876 switch (error.GetError())
878 case EBADF: // One of the descriptor sets specified an invalid descriptor.
879 return eConnectionStatusLostConnection;
881 case EINVAL: // The specified time limit is invalid. One of its components is negative or too large.
882 default: // Other unknown error
883 return eConnectionStatusError;
885 case EAGAIN: // The kernel was (perhaps temporarily) unable to
886 // allocate the requested number of file descriptors,
887 // or we have non-blocking IO
888 case EINTR: // A signal was delivered before the time limit
889 // expired and before any of the selected events
891 break; // Lets keep reading to until we timeout
894 else if (num_set_fds == 0)
896 return eConnectionStatusTimedOut;
898 else if (num_set_fds > 0)
900 if (FD_ISSET(data_fd, &read_fds))
901 return eConnectionStatusSuccess;
902 if (have_pipe_fd && FD_ISSET(pipe_fd, &read_fds))
904 // We got a command to exit. Read the data from that pipe:
910 bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
911 } while (bytes_read < 0 && errno == EINTR);
912 assert (bytes_read == 1 && buffer[0] == 'q');
915 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
916 this, (int) bytes_read, buffer);
918 return eConnectionStatusEndOfFile;
925 error_ptr->SetErrorString("not connected");
926 return eConnectionStatusLostConnection;
934 // This ConnectionFileDescriptor::BytesAvailable() uses poll(). poll() should NOT
935 // be used on MacOSX as it has all sorts of restrictions on the types of file descriptors
936 // that it doesn't support.
938 // There may be some systems that properly support poll() that could use this
939 // implementation. I will let each system opt into this on their own.
942 // - no restrictions on the fd value that is used
944 // - varies wildly from platform to platform in its implementation restrictions
947 ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
949 // Don't need to take the mutex here separately since we are only called from Read. If we
950 // ever get used more generally we will need to lock here as well.
952 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
954 log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
955 int timeout_msec = 0;
956 if (timeout_usec == UINT32_MAX)
961 else if (timeout_usec == 0)
963 // Return immediately, don't wait
968 // Convert usec to msec
969 timeout_msec = (timeout_usec + 999) / 1000;
972 // Make a copy of the file descriptors to make sure we don't
973 // have another thread change these values out from under us
974 // and cause problems in the loop below where like in FS_SET()
975 const int data_fd = m_fd_recv;
976 const int pipe_fd = m_pipe_read;
978 // Make sure the file descriptor can be used with select as it
982 const bool have_pipe_fd = pipe_fd >= 0;
983 struct pollfd fds[2] =
985 { data_fd, POLLIN, 0 },
986 { pipe_fd, POLLIN, 0 }
988 const int nfds = have_pipe_fd ? 2 : 1;
990 while (data_fd == m_fd_recv)
992 const int num_set_fds = ::poll (fds, nfds, timeout_msec);
995 error.SetErrorToErrno();
1005 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::poll (fds={{%i,POLLIN},{%i,POLLIN}}, nfds=%i, timeout_ms=%i) => %d, error = %s\n",
1014 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::poll (fds={{%i,POLLIN}}, nfds=%i, timeout_ms=%i) => %d, error = %s\n",
1025 switch (error.GetError())
1027 case EBADF: // One of the descriptor sets specified an invalid descriptor.
1028 return eConnectionStatusLostConnection;
1030 case EINVAL: // The specified time limit is invalid. One of its components is negative or too large.
1031 default: // Other unknown error
1032 return eConnectionStatusError;
1034 case EAGAIN: // The kernel was (perhaps temporarily) unable to
1035 // allocate the requested number of file descriptors,
1036 // or we have non-blocking IO
1037 case EINTR: // A signal was delivered before the time limit
1038 // expired and before any of the selected events
1040 break; // Lets keep reading to until we timeout
1043 else if (num_set_fds == 0)
1045 return eConnectionStatusTimedOut;
1047 else if (num_set_fds > 0)
1049 if (fds[0].revents & POLLIN)
1050 return eConnectionStatusSuccess;
1051 if (fds[1].revents & POLLIN)
1053 // We got a command to exit. Read the data from that pipe:
1059 bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
1060 } while (bytes_read < 0 && errno == EINTR);
1061 assert (bytes_read == 1 && buffer[0] == 'q');
1064 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
1065 this, (int) bytes_read, buffer);
1067 return eConnectionStatusEndOfFile;
1073 error_ptr->SetErrorString("not connected");
1074 return eConnectionStatusLostConnection;
1080 ConnectionFileDescriptor::Close (int& fd, Error *error_ptr)
1084 bool success = true;
1085 // Avoid taking a lock if we can
1088 Mutex::Locker locker (m_mutex);
1089 // Check the FD after the lock is taken to ensure only one thread
1090 // can get into the close scope below
1093 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1095 log->Printf ("%p ConnectionFileDescriptor::Close (fd = %i)", this,fd);
1097 success = ::close (fd) == 0;
1098 // A reference to a FD was passed in, set it to an invalid value
1100 if (!success && error_ptr)
1102 // Only set the error if we have been asked to since something else
1103 // might have caused us to try and shut down the connection and may
1104 // have already set the error.
1105 error_ptr->SetErrorToErrno();
1110 return eConnectionStatusSuccess;
1112 return eConnectionStatusError;
1116 ConnectionFileDescriptor::NamedSocketAccept (const char *socket_name, Error *error_ptr)
1118 ConnectionStatus result = eConnectionStatusError;
1119 struct sockaddr_un saddr_un;
1121 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1123 int listen_socket = ::socket (AF_UNIX, SOCK_STREAM, 0);
1124 if (listen_socket == -1)
1127 error_ptr->SetErrorToErrno();
1128 return eConnectionStatusError;
1131 saddr_un.sun_family = AF_UNIX;
1132 ::strncpy(saddr_un.sun_path, socket_name, sizeof(saddr_un.sun_path) - 1);
1133 saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
1134 #if defined(__APPLE__) || defined(__FreeBSD__)
1135 saddr_un.sun_len = SUN_LEN (&saddr_un);
1138 if (::bind (listen_socket, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) == 0)
1140 if (::listen (listen_socket, 5) == 0)
1142 m_fd_send = m_fd_recv = ::accept (listen_socket, NULL, 0);
1145 m_should_close_fd = true;
1149 result = eConnectionStatusSuccess;
1154 if (result != eConnectionStatusSuccess)
1157 error_ptr->SetErrorToErrno();
1159 // We are done with the listen port
1160 Close (listen_socket, NULL);
1165 ConnectionFileDescriptor::NamedSocketConnect (const char *socket_name, Error *error_ptr)
1168 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1170 // Open the socket that was passed in as an option
1171 struct sockaddr_un saddr_un;
1172 m_fd_send = m_fd_recv = ::socket (AF_UNIX, SOCK_STREAM, 0);
1173 if (m_fd_send == -1)
1176 error_ptr->SetErrorToErrno();
1177 return eConnectionStatusError;
1180 saddr_un.sun_family = AF_UNIX;
1181 ::strncpy(saddr_un.sun_path, socket_name, sizeof(saddr_un.sun_path) - 1);
1182 saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
1183 #if defined(__APPLE__) || defined(__FreeBSD__)
1184 saddr_un.sun_len = SUN_LEN (&saddr_un);
1187 if (::connect (m_fd_send, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) < 0)
1190 error_ptr->SetErrorToErrno();
1192 return eConnectionStatusError;
1196 return eConnectionStatusSuccess;
1200 ConnectionFileDescriptor::SocketListen (uint16_t listen_port_num, Error *error_ptr)
1202 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1204 log->Printf ("%p ConnectionFileDescriptor::SocketListen (port = %i)", this, listen_port_num);
1207 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1208 int listen_port = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1209 if (listen_port == -1)
1212 error_ptr->SetErrorToErrno();
1213 return eConnectionStatusError;
1216 // enable local address reuse
1217 SetSocketOption (listen_port, SOL_SOCKET, SO_REUSEADDR, 1);
1219 SocketAddress localhost;
1220 if (localhost.SetToLocalhost (AF_INET, listen_port_num))
1222 int err = ::bind (listen_port, localhost, localhost.GetLength());
1226 error_ptr->SetErrorToErrno();
1227 Close (listen_port, NULL);
1228 return eConnectionStatusError;
1231 err = ::listen (listen_port, 1);
1235 error_ptr->SetErrorToErrno();
1236 Close (listen_port, NULL);
1237 return eConnectionStatusError;
1240 m_fd_send = m_fd_recv = ::accept (listen_port, NULL, 0);
1241 if (m_fd_send == -1)
1244 error_ptr->SetErrorToErrno();
1245 Close (listen_port, NULL);
1246 return eConnectionStatusError;
1250 // We are done with the listen port
1251 Close (listen_port, NULL);
1253 m_should_close_fd = true;
1255 // Keep our TCP packets coming without any delays.
1256 SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1);
1259 return eConnectionStatusSuccess;
1263 ConnectionFileDescriptor::ConnectTCP (const char *host_and_port, Error *error_ptr)
1265 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1267 log->Printf ("%p ConnectionFileDescriptor::ConnectTCP (host/port = %s)", this, host_and_port);
1270 m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1271 std::string host_str;
1272 std::string port_str;
1273 int32_t port = INT32_MIN;
1274 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr))
1275 return eConnectionStatusError;
1277 // Create the socket
1278 m_fd_send = m_fd_recv = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1279 if (m_fd_send == -1)
1282 error_ptr->SetErrorToErrno();
1283 return eConnectionStatusError;
1286 m_should_close_fd = true;
1288 // Enable local address reuse
1289 SetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, 1);
1291 struct sockaddr_in sa;
1292 ::memset (&sa, 0, sizeof (sa));
1293 sa.sin_family = AF_INET;
1294 sa.sin_port = htons (port);
1296 int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
1298 if (inet_pton_result <= 0)
1300 struct hostent *host_entry = gethostbyname (host_str.c_str());
1302 host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
1303 inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
1304 if (inet_pton_result <= 0)
1309 if (inet_pton_result == -1)
1310 error_ptr->SetErrorToErrno();
1312 error_ptr->SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str());
1316 return eConnectionStatusError;
1320 if (-1 == ::connect (m_fd_send, (const struct sockaddr *)&sa, sizeof(sa)))
1323 error_ptr->SetErrorToErrno();
1326 return eConnectionStatusError;
1329 // Keep our TCP packets coming without any delays.
1330 SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1);
1333 return eConnectionStatusSuccess;
1337 ConnectionFileDescriptor::ConnectUDP (const char *host_and_port, Error *error_ptr)
1339 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1341 log->Printf ("%p ConnectionFileDescriptor::ConnectUDP (host/port = %s)", this, host_and_port);
1344 m_fd_send_type = m_fd_recv_type = eFDTypeSocketUDP;
1346 std::string host_str;
1347 std::string port_str;
1348 int32_t port = INT32_MIN;
1349 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr))
1350 return eConnectionStatusError;
1352 // Setup the receiving end of the UDP connection on this localhost
1353 // on port zero. After we bind to port zero we can read the port.
1354 m_fd_recv = ::socket (AF_INET, SOCK_DGRAM, 0);
1355 if (m_fd_recv == -1)
1357 // Socket creation failed...
1359 error_ptr->SetErrorToErrno();
1363 // Socket was created, now lets bind to the requested port
1365 addr.SetToLocalhost (AF_INET, 0);
1367 if (::bind (m_fd_recv, addr, addr.GetLength()) == -1)
1371 error_ptr->SetErrorToErrno();
1376 if (m_fd_recv == -1)
1377 return eConnectionStatusError;
1379 // At this point we have setup the recieve port, now we need to
1380 // setup the UDP send socket
1382 struct addrinfo hints;
1383 struct addrinfo *service_info_list = NULL;
1385 ::memset (&hints, 0, sizeof(hints));
1386 hints.ai_family = AF_INET;
1387 hints.ai_socktype = SOCK_DGRAM;
1388 int err = ::getaddrinfo (host_str.c_str(), port_str.c_str(), &hints, &service_info_list);
1392 error_ptr->SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)",
1398 return eConnectionStatusError;
1401 for (struct addrinfo *service_info_ptr = service_info_list;
1402 service_info_ptr != NULL;
1403 service_info_ptr = service_info_ptr->ai_next)
1405 m_fd_send = ::socket (service_info_ptr->ai_family,
1406 service_info_ptr->ai_socktype,
1407 service_info_ptr->ai_protocol);
1409 if (m_fd_send != -1)
1411 m_udp_send_sockaddr = service_info_ptr;
1418 :: freeaddrinfo (service_info_list);
1420 if (m_fd_send == -1)
1423 return eConnectionStatusError;
1429 m_should_close_fd = true;
1430 return eConnectionStatusSuccess;
1433 #if defined(__MINGW32__) || defined(__MINGW64__)
1434 typedef const char * set_socket_option_arg_type;
1435 typedef char * get_socket_option_arg_type;
1436 #else // #if defined(__MINGW32__) || defined(__MINGW64__)
1437 typedef const void * set_socket_option_arg_type;
1438 typedef void * get_socket_option_arg_type;
1439 #endif // #if defined(__MINGW32__) || defined(__MINGW64__)
1442 ConnectionFileDescriptor::GetSocketOption(int fd, int level, int option_name, int &option_value)
1444 get_socket_option_arg_type option_value_p = static_cast<get_socket_option_arg_type>(&option_value);
1445 socklen_t option_value_size = sizeof(int);
1446 return ::getsockopt(fd, level, option_name, option_value_p, &option_value_size);
1450 ConnectionFileDescriptor::SetSocketOption(int fd, int level, int option_name, int option_value)
1452 set_socket_option_arg_type option_value_p = static_cast<get_socket_option_arg_type>(&option_value);
1453 return ::setsockopt(fd, level, option_name, option_value_p, sizeof(option_value));
1457 ConnectionFileDescriptor::SetSocketReceiveTimeout (uint32_t timeout_usec)
1459 switch (m_fd_recv_type)
1461 case eFDTypeFile: // Other FD requireing read/write
1464 case eFDTypeSocket: // Socket requiring send/recv
1465 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom
1467 // Check in case timeout for m_fd has already been set to this value
1468 if (timeout_usec == m_socket_timeout_usec)
1470 //printf ("ConnectionFileDescriptor::SetSocketReceiveTimeout (timeout_usec = %u)\n", timeout_usec);
1472 struct timeval timeout;
1473 if (timeout_usec == UINT32_MAX)
1476 timeout.tv_usec = 0;
1478 else if (timeout_usec == 0)
1480 // Sending in zero does an infinite timeout, so set this as low
1481 // as we can go to get an effective zero timeout...
1483 timeout.tv_usec = 1;
1487 timeout.tv_sec = timeout_usec / TimeValue::MicroSecPerSec;
1488 timeout.tv_usec = timeout_usec % TimeValue::MicroSecPerSec;
1490 if (::setsockopt (m_fd_recv, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0)
1492 m_socket_timeout_usec = timeout_usec;
1501 ConnectionFileDescriptor::GetSocketPort (int fd)
1503 // We bound to port zero, so we need to figure out which port we actually bound to
1504 SocketAddress sock_addr;
1505 socklen_t sock_addr_len = sock_addr.GetMaxLength ();
1506 if (::getsockname (fd, sock_addr, &sock_addr_len) == 0)
1507 return sock_addr.GetPort ();
1512 // If the read file descriptor is a socket, then return
1513 // the port number that is being used by the socket.
1515 ConnectionFileDescriptor::GetReadPort () const
1517 return ConnectionFileDescriptor::GetSocketPort (m_fd_recv);
1520 // If the write file descriptor is a socket, then return
1521 // the port number that is being used by the socket.
1523 ConnectionFileDescriptor::GetWritePort () const
1525 return ConnectionFileDescriptor::GetSocketPort (m_fd_send);