1//===-- ConnectionFileDescriptor.cpp ----------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#if defined(__APPLE__)
11// Enable this special support for Apple builds where we can have unlimited
12// select bounds. We tried switching to poll() and kqueue and we were panicing
13// the kernel, so we have to stick with select for now.
14#define _DARWIN_UNLIMITED_SELECT
15#endif
16
17#include "lldb/Core/ConnectionFileDescriptor.h"
18#include "lldb/Host/Config.h"
19#include "lldb/Host/SocketAddress.h"
20
21// C Includes
22#include <errno.h>
23#include <fcntl.h>
24#include <string.h>
25#include <stdlib.h>
26#include <sys/types.h>
27#ifndef LLDB_DISABLE_POSIX
28#include <arpa/inet.h>
29#include <netdb.h>
30#include <netinet/in.h>
31#include <netinet/tcp.h>
32#include <sys/socket.h>
33#include <sys/un.h>
34#include <termios.h>
35#include <unistd.h>
36#endif
37#ifdef _WIN32
38#include "lldb/Host/windows/windows.h"
39#include <winsock2.h>
40#include <WS2tcpip.h>
41#endif
42
43// C++ Includes
44// Other libraries and framework includes
45#include "llvm/Support/ErrorHandling.h"
46#if defined(__APPLE__)
47#include "llvm/ADT/SmallVector.h"
48#endif
49// Project includes
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"
57
58
59using namespace lldb;
60using namespace lldb_private;
61
62static bool
63DecodeHostAndPort (const char *host_and_port,
64                   std::string &host_str,
65                   std::string &port_str,
66                   int32_t& port,
67                   Error *error_ptr)
68{
69    static RegularExpression g_regex ("([^:]+):([0-9]+)");
70    RegularExpression::Match regex_match(2);
71    if (g_regex.Execute (host_and_port, &regex_match))
72    {
73        if (regex_match.GetMatchAtIndex (host_and_port, 1, host_str) &&
74            regex_match.GetMatchAtIndex (host_and_port, 2, port_str))
75        {
76            port = Args::StringToSInt32 (port_str.c_str(), INT32_MIN);
77            if (port != INT32_MIN)
78            {
79                if (error_ptr)
80                    error_ptr->Clear();
81                return true;
82            }
83        }
84    }
85    host_str.clear();
86    port_str.clear();
87    port = INT32_MIN;
88    if (error_ptr)
89        error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port);
90    return false;
91}
92
93ConnectionFileDescriptor::ConnectionFileDescriptor () :
94    Connection(),
95    m_fd_send (-1),
96    m_fd_recv (-1),
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),
101    m_pipe_read(-1),
102    m_pipe_write(-1),
103    m_mutex (Mutex::eMutexTypeRecursive),
104    m_should_close_fd (false),
105    m_shutting_down (false)
106{
107    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION |  LIBLLDB_LOG_OBJECT));
108    if (log)
109        log->Printf ("%p ConnectionFileDescriptor::ConnectionFileDescriptor ()", this);
110}
111
112ConnectionFileDescriptor::ConnectionFileDescriptor (int fd, bool owns_fd) :
113    Connection(),
114    m_fd_send (fd),
115    m_fd_recv (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),
120    m_pipe_read(-1),
121    m_pipe_write(-1),
122    m_mutex (Mutex::eMutexTypeRecursive),
123    m_should_close_fd (owns_fd),
124    m_shutting_down (false)
125{
126    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION |  LIBLLDB_LOG_OBJECT));
127    if (log)
128        log->Printf ("%p ConnectionFileDescriptor::ConnectionFileDescriptor (fd = %i, owns_fd = %i)", this, fd, owns_fd);
129    OpenCommandPipe ();
130}
131
132
133ConnectionFileDescriptor::~ConnectionFileDescriptor ()
134{
135    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION |  LIBLLDB_LOG_OBJECT));
136    if (log)
137        log->Printf ("%p ConnectionFileDescriptor::~ConnectionFileDescriptor ()", this);
138    Disconnect (NULL);
139    CloseCommandPipe ();
140}
141
142void
143ConnectionFileDescriptor::OpenCommandPipe ()
144{
145    CloseCommandPipe();
146
147    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
148    // Make the command file descriptor here:
149    int filedes[2];
150#ifndef LLDB_DISABLE_POSIX
151    int result = pipe (filedes);
152#else
153    int result = -1;
154#endif
155    if (result != 0)
156    {
157        if (log)
158            log->Printf ("%p ConnectionFileDescriptor::OpenCommandPipe () - could not make pipe: %s",
159                         this,
160                         strerror(errno));
161    }
162    else
163    {
164        m_pipe_read  = filedes[0];
165        m_pipe_write = filedes[1];
166        if (log)
167            log->Printf ("%p ConnectionFileDescriptor::OpenCommandPipe() - success readfd=%d writefd=%d",
168                         this,
169                         m_pipe_read,
170                         m_pipe_write);
171    }
172}
173
174void
175ConnectionFileDescriptor::CloseCommandPipe ()
176{
177    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
178    if (log)
179        log->Printf ("%p ConnectionFileDescriptor::CloseCommandPipe()",
180                     this);
181
182    if (m_pipe_read != -1)
183    {
184#ifdef _MSC_VER
185        llvm_unreachable("pipe close unsupported in MSVC");
186#else
187        close (m_pipe_read);
188#endif
189        m_pipe_read = -1;
190    }
191
192    if (m_pipe_write != -1)
193    {
194#ifdef _MSC_VER
195        llvm_unreachable("pipe close unsupported in MSVC");
196#else
197        close (m_pipe_write);
198#endif
199        m_pipe_write = -1;
200    }
201}
202
203bool
204ConnectionFileDescriptor::IsConnected () const
205{
206    return m_fd_send >= 0 || m_fd_recv >= 0;
207}
208
209ConnectionStatus
210ConnectionFileDescriptor::Connect (const char *s, Error *error_ptr)
211{
212    Mutex::Locker locker (m_mutex);
213    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
214    if (log)
215        log->Printf ("%p ConnectionFileDescriptor::Connect (url = '%s')", this, s);
216
217    OpenCommandPipe();
218
219    if (s && s[0])
220    {
221        if (strstr(s, "listen://"))
222        {
223            // listen://HOST:PORT
224            return SocketListen (s + strlen("listen://"), error_ptr);
225        }
226        else if (strstr(s, "accept://"))
227        {
228            // unix://SOCKNAME
229            return NamedSocketAccept (s + strlen("accept://"), error_ptr);
230        }
231        else if (strstr(s, "unix-accept://"))
232        {
233            // unix://SOCKNAME
234            return NamedSocketAccept (s + strlen("unix-accept://"), error_ptr);
235        }
236        else if (strstr(s, "connect://"))
237        {
238            return ConnectTCP (s + strlen("connect://"), error_ptr);
239        }
240        else if (strstr(s, "tcp-connect://"))
241        {
242            return ConnectTCP (s + strlen("tcp-connect://"), error_ptr);
243        }
244        else if (strstr(s, "udp://"))
245        {
246            return ConnectUDP (s + strlen("udp://"), error_ptr);
247        }
248        else if (strstr(s, "fd://"))
249        {
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);
255
256            if (success)
257            {
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
261                // isn't a bad fd.
262                errno = 0;
263#ifndef LLDB_DISABLE_POSIX
264                int flags = ::fcntl (m_fd_send, F_GETFL, 0);
265#else
266                int flags = -1;
267#endif
268                if (flags == -1 || errno == EBADF)
269                {
270                    if (error_ptr)
271                        error_ptr->SetErrorStringWithFormat ("stale file descriptor: %s", s);
272                    m_fd_send = m_fd_recv = -1;
273                    return eConnectionStatusError;
274                }
275                else
276                {
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.
279                    int resuse;
280                    bool is_socket = GetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, resuse) == 0;
281                    if (is_socket)
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
285                    // handed it to us.
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;
294                }
295            }
296
297            if (error_ptr)
298                error_ptr->SetErrorStringWithFormat ("invalid file descriptor: \"fd://%s\"", s);
299            m_fd_send = m_fd_recv = -1;
300            return eConnectionStatusError;
301        }
302        else if (strstr(s, "file://"))
303        {
304            // file:///PATH
305            const char *path = s + strlen("file://");
306#ifndef LLDB_DISABLE_POSIX
307            do
308            {
309                m_fd_send = m_fd_recv = ::open (path, O_RDWR);
310            } while (m_fd_send == -1 && errno == EINTR);
311            if (m_fd_send == -1)
312            {
313                if (error_ptr)
314                    error_ptr->SetErrorToErrno();
315                return eConnectionStatusError;
316            }
317
318            if (::isatty(m_fd_send))
319            {
320                // Set up serial terminal emulation
321                struct termios options;
322                ::tcgetattr (m_fd_send, &options);
323
324                // Set port speed to maximum
325                ::cfsetospeed (&options, B115200);
326                ::cfsetispeed (&options, B115200);
327
328                // Raw input, disable echo and signals
329                options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
330
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;
334
335                ::tcsetattr (m_fd_send, TCSANOW, &options);
336            }
337
338            int flags = ::fcntl (m_fd_send, F_GETFL, 0);
339            if (flags >= 0)
340            {
341                if ((flags & O_NONBLOCK) == 0)
342                {
343                    flags |= O_NONBLOCK;
344                    ::fcntl (m_fd_send, F_SETFL, flags);
345                }
346            }
347            m_should_close_fd = true;
348            return eConnectionStatusSuccess;
349#else
350            return eConnectionStatusError;
351#endif
352        }
353        if (error_ptr)
354            error_ptr->SetErrorStringWithFormat ("unsupported connection URL: '%s'", s);
355        return eConnectionStatusError;
356    }
357    if (error_ptr)
358        error_ptr->SetErrorString("invalid connect arguments");
359    return eConnectionStatusError;
360}
361
362ConnectionStatus
363ConnectionFileDescriptor::Disconnect (Error *error_ptr)
364{
365    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
366    if (log)
367        log->Printf ("%p ConnectionFileDescriptor::Disconnect ()", this);
368
369    // Reset the port predicate when disconnecting and don't broadcast
370    m_port_predicate.SetValue(0, eBroadcastNever);
371
372    ConnectionStatus status = eConnectionStatusSuccess;
373
374    if (m_fd_send < 0 && m_fd_recv < 0)
375    {
376        if (log)
377            log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Nothing to disconnect", this);
378        return eConnectionStatusSuccess;
379    }
380
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.
385
386    m_shutting_down = true;
387
388    Mutex::Locker locker;
389    bool got_lock= locker.TryLock (m_mutex);
390
391    if (!got_lock)
392    {
393        if (m_pipe_write != -1 )
394        {
395            int result;
396            result = write (m_pipe_write, "q", 1);
397            if (log)
398                log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Couldn't get the lock, sent 'q' to %d, result = %d.", this, m_pipe_write, result);
399        }
400        else if (log)
401            log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Couldn't get the lock, but no command pipe is available.", this);
402        locker.Lock (m_mutex);
403    }
404
405    if (m_should_close_fd == true)
406    {
407        if (m_fd_send == m_fd_recv)
408        {
409            status = Close (m_fd_send, m_fd_send_type, error_ptr);
410        }
411        else
412        {
413            // File descriptors are the different, close both if needed
414            if (m_fd_send >= 0)
415                status = Close (m_fd_send, m_fd_send_type, error_ptr);
416            if (m_fd_recv >= 0)
417            {
418                ConnectionStatus recv_status = Close (m_fd_recv, m_fd_recv_type, error_ptr);
419                if (status == eConnectionStatusSuccess)
420                    status = recv_status;
421            }
422        }
423    }
424
425    // Now set all our descriptors to invalid values.
426
427    m_fd_send = m_fd_recv = -1;
428
429    if (status != eConnectionStatusSuccess)
430    {
431
432        return status;
433    }
434
435    m_shutting_down = false;
436    return eConnectionStatusSuccess;
437}
438
439size_t
440ConnectionFileDescriptor::Read (void *dst,
441                                size_t dst_len,
442                                uint32_t timeout_usec,
443                                ConnectionStatus &status,
444                                Error *error_ptr)
445{
446    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
447    if (log)
448        log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %" PRIu64 ")...",
449                     this, m_fd_recv, dst, (uint64_t)dst_len);
450
451    Mutex::Locker locker;
452    bool got_lock = locker.TryLock (m_mutex);
453    if (!got_lock)
454    {
455        if (log)
456            log->Printf ("%p ConnectionFileDescriptor::Read () failed to get the connection lock.",
457                     this);
458        if (error_ptr)
459            error_ptr->SetErrorString ("failed to get the connection lock for read.");
460
461        status = eConnectionStatusTimedOut;
462        return 0;
463    }
464    else if (m_shutting_down)
465        return eConnectionStatusError;
466
467    ssize_t bytes_read = 0;
468
469    status = BytesAvailable (timeout_usec, error_ptr);
470    if (status == eConnectionStatusSuccess)
471    {
472        do
473        {
474#ifndef LLDB_DISABLE_POSIX
475            bytes_read = ::read (m_fd_recv, dst, dst_len);
476#else
477            switch (m_fd_send_type) {
478            case eFDTypeSocket:
479            case eFDTypeSocketUDP:
480                bytes_read = ::recv (m_fd_recv, (char*)dst, dst_len, 0);
481                break;
482            default:
483                bytes_read = -1;
484                break;
485
486            }
487
488#endif
489        } while (bytes_read < 0 && errno == EINTR);
490    }
491
492    if (status != eConnectionStatusSuccess)
493        return 0;
494
495    Error error;
496    if (bytes_read == 0)
497    {
498        error.Clear(); // End-of-file.  Do not automatically close; pass along for the end-of-file handlers.
499        status = eConnectionStatusEndOfFile;
500    }
501    else if (bytes_read < 0)
502    {
503        error.SetErrorToErrno();
504    }
505    else
506    {
507        error.Clear();
508    }
509
510    if (log)
511        log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %" PRIu64 ") => %" PRIi64 ", error = %s",
512                     this,
513                     m_fd_recv,
514                     dst,
515                     (uint64_t)dst_len,
516                     (int64_t)bytes_read,
517                     error.AsCString());
518
519    if (error_ptr)
520        *error_ptr = error;
521
522    if (error.Fail())
523    {
524        uint32_t error_value = error.GetError();
525        switch (error_value)
526        {
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;
530            else
531                status = eConnectionStatusSuccess;
532            return 0;
533
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....
549
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....
558
559        case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a socket.
560            status = eConnectionStatusTimedOut;
561            return 0;
562
563        default:
564            if (log)
565                log->Printf("%p ConnectionFileDescriptor::Read (), unexpected error: %s", this, strerror(error_value));
566            status = eConnectionStatusError;
567            break;  // Break to close....
568
569        }
570
571        return 0;
572    }
573    return bytes_read;
574}
575
576size_t
577ConnectionFileDescriptor::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr)
578{
579    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
580    if (log)
581        log->Printf ("%p ConnectionFileDescriptor::Write (src = %p, src_len = %" PRIu64 ")", this, src, (uint64_t)src_len);
582
583    if (!IsConnected ())
584    {
585        if (error_ptr)
586            error_ptr->SetErrorString("not connected");
587        status = eConnectionStatusNoConnection;
588        return 0;
589    }
590
591
592    Error error;
593
594    ssize_t bytes_sent = 0;
595
596    switch (m_fd_send_type)
597    {
598#ifndef LLDB_DISABLE_POSIX
599        case eFDTypeFile:       // Other FD requireing read/write
600            do
601            {
602                bytes_sent = ::write (m_fd_send, src, src_len);
603            } while (bytes_sent < 0 && errno == EINTR);
604            break;
605#endif
606        case eFDTypeSocket:     // Socket requiring send/recv
607            do
608            {
609                bytes_sent = ::send (m_fd_send, (char*)src, src_len, 0);
610            } while (bytes_sent < 0 && errno == EINTR);
611            break;
612
613        case eFDTypeSocketUDP:  // Unconnected UDP socket requiring sendto/recvfrom
614            assert (m_udp_send_sockaddr->GetFamily() != 0);
615            do
616            {
617                bytes_sent = ::sendto (m_fd_send,
618                                       (char*)src,
619                                       src_len,
620                                       0,
621                                       *m_udp_send_sockaddr,
622                                       m_udp_send_sockaddr->GetLength());
623            } while (bytes_sent < 0 && errno == EINTR);
624            break;
625    }
626
627    if (bytes_sent < 0)
628        error.SetErrorToErrno ();
629    else
630        error.Clear ();
631
632    if (log)
633    {
634        switch (m_fd_send_type)
635        {
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)",
638                             this,
639                             m_fd_send,
640                             src,
641                             (uint64_t)src_len,
642                             (int64_t)bytes_sent,
643                             error.AsCString());
644                break;
645
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)",
648                             this,
649                             m_fd_send,
650                             src,
651                             (uint64_t)src_len,
652                             (int64_t)bytes_sent,
653                             error.AsCString());
654                break;
655
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)",
658                             this,
659                             m_fd_send,
660                             src,
661                             (uint64_t)src_len,
662                             (int64_t)bytes_sent,
663                             error.AsCString());
664                break;
665        }
666    }
667
668    if (error_ptr)
669        *error_ptr = error;
670
671    if (error.Fail())
672    {
673        switch (error.GetError())
674        {
675        case EAGAIN:
676        case EINTR:
677            status = eConnectionStatusSuccess;
678            return 0;
679
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....
684
685        default:
686            status = eConnectionStatusError;
687            break;  // Break to close....
688        }
689
690        return 0;
691    }
692
693    status = eConnectionStatusSuccess;
694    return bytes_sent;
695}
696
697
698
699#if defined(__APPLE__)
700
701// This ConnectionFileDescriptor::BytesAvailable() uses select().
702//
703// PROS:
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.
708
709// CONS:
710//  - Darwin only
711
712ConnectionStatus
713ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
714{
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.
717
718    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
719    if (log)
720        log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
721    struct timeval *tv_ptr;
722    struct timeval tv;
723    if (timeout_usec == UINT32_MAX)
724    {
725        // Infinite wait...
726        tv_ptr = NULL;
727    }
728    else
729    {
730        TimeValue time_value;
731        time_value.OffsetWithMicroSeconds (timeout_usec);
732        tv.tv_sec = time_value.seconds();
733        tv.tv_usec = time_value.microseconds();
734        tv_ptr = &tv;
735    }
736
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;
742
743    if (data_fd >= 0)
744    {
745        const bool have_pipe_fd = pipe_fd >= 0;
746
747        while (data_fd == m_fd_recv)
748        {
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());
758            if (have_pipe_fd)
759                FD_SET (pipe_fd, read_fds.data());
760
761            Error error;
762
763            if (log)
764            {
765                if (have_pipe_fd)
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);
768                else
769                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p)...",
770                                this, nfds, data_fd, tv_ptr);
771            }
772
773            const int num_set_fds = ::select (nfds, read_fds.data(), NULL, NULL, tv_ptr);
774            if (num_set_fds < 0)
775                error.SetErrorToErrno();
776            else
777                error.Clear();
778
779            if (log)
780            {
781                if (have_pipe_fd)
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());
784                else
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());
787            }
788
789            if (error_ptr)
790                *error_ptr = error;
791
792            if (error.Fail())
793            {
794                switch (error.GetError())
795                {
796                    case EBADF:     // One of the descriptor sets specified an invalid descriptor.
797                        return eConnectionStatusLostConnection;
798
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;
802
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
808                        // occurred.
809                        break;      // Lets keep reading to until we timeout
810                }
811            }
812            else if (num_set_fds == 0)
813            {
814                return eConnectionStatusTimedOut;
815            }
816            else if (num_set_fds > 0)
817            {
818                // FD_ISSET is happy to deal with a something larger than
819                // a single fd_set.
820                if (FD_ISSET(data_fd, read_fds.data()))
821                    return eConnectionStatusSuccess;
822                if (have_pipe_fd && FD_ISSET(pipe_fd, read_fds.data()))
823                {
824                    // We got a command to exit.  Read the data from that pipe:
825                    char buffer[16];
826                    ssize_t bytes_read;
827
828                    do
829                    {
830                        bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
831                    } while (bytes_read < 0 && errno == EINTR);
832                    assert (bytes_read == 1 && buffer[0] == 'q');
833
834                    if (log)
835                        log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
836                                    this, (int) bytes_read, buffer);
837
838                    return eConnectionStatusEndOfFile;
839                }
840            }
841        }
842    }
843
844    if (error_ptr)
845        error_ptr->SetErrorString("not connected");
846    return eConnectionStatusLostConnection;
847}
848
849#else
850
851// This ConnectionFileDescriptor::BytesAvailable() uses select().
852//
853// PROS:
854//  - select is consistent across most unix platforms
855// CONS:
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.
862
863ConnectionStatus
864ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
865{
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.
868
869    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
870    if (log)
871        log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
872    struct timeval *tv_ptr;
873    struct timeval tv;
874    if (timeout_usec == UINT32_MAX)
875    {
876        // Infinite wait...
877        tv_ptr = NULL;
878    }
879    else
880    {
881        TimeValue time_value;
882        time_value.OffsetWithMicroSeconds (timeout_usec);
883        tv.tv_sec = time_value.seconds();
884        tv.tv_usec = time_value.microseconds();
885        tv_ptr = &tv;
886    }
887
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;
893
894    if (data_fd >= 0)
895    {
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...
899#ifndef _MSC_VER
900        assert (data_fd < FD_SETSIZE);
901#endif
902
903        const bool have_pipe_fd = pipe_fd >= 0;
904
905        if (have_pipe_fd)
906        {
907            assert (pipe_fd < FD_SETSIZE);
908        }
909
910        while (data_fd == m_fd_recv)
911        {
912            fd_set read_fds;
913            FD_ZERO (&read_fds);
914            FD_SET (data_fd, &read_fds);
915            if (have_pipe_fd)
916                FD_SET (pipe_fd, &read_fds);
917
918            const int nfds = std::max<int>(data_fd, pipe_fd) + 1;
919
920            Error error;
921
922            if (log)
923            {
924                if (have_pipe_fd)
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);
927                else
928                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p)...",
929                                this, nfds, data_fd, tv_ptr);
930            }
931
932            const int num_set_fds = ::select (nfds, &read_fds, NULL, NULL, tv_ptr);
933            if (num_set_fds < 0)
934                error.SetErrorToErrno();
935            else
936                error.Clear();
937
938            if (log)
939            {
940                if (have_pipe_fd)
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());
943                else
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());
946            }
947
948            if (error_ptr)
949                *error_ptr = error;
950
951            if (error.Fail())
952            {
953                switch (error.GetError())
954                {
955                    case EBADF:     // One of the descriptor sets specified an invalid descriptor.
956                        return eConnectionStatusLostConnection;
957
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;
961
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
967                        // occurred.
968                        break;      // Lets keep reading to until we timeout
969                }
970            }
971            else if (num_set_fds == 0)
972            {
973                return eConnectionStatusTimedOut;
974            }
975            else if (num_set_fds > 0)
976            {
977                if (FD_ISSET(data_fd, &read_fds))
978                    return eConnectionStatusSuccess;
979                if (have_pipe_fd && FD_ISSET(pipe_fd, &read_fds))
980                {
981                    // We got a command to exit.  Read the data from that pipe:
982                    char buffer[16];
983                    ssize_t bytes_read;
984
985                    do
986                    {
987                        bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
988                    } while (bytes_read < 0 && errno == EINTR);
989                    assert (bytes_read == 1 && buffer[0] == 'q');
990
991                    if (log)
992                        log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
993                                    this, (int) bytes_read, buffer);
994
995                    return eConnectionStatusEndOfFile;
996                }
997            }
998        }
999    }
1000
1001    if (error_ptr)
1002        error_ptr->SetErrorString("not connected");
1003    return eConnectionStatusLostConnection;
1004}
1005
1006#endif
1007
1008#if 0
1009#include <poll.h>
1010
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.
1014//
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.
1017//
1018// PROS:
1019//  - no restrictions on the fd value that is used
1020// CONS:
1021//  - varies wildly from platform to platform in its implementation restrictions
1022
1023ConnectionStatus
1024ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
1025{
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.
1028
1029    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1030    if (log)
1031        log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
1032    int timeout_msec = 0;
1033    if (timeout_usec == UINT32_MAX)
1034    {
1035        // Infinite wait...
1036        timeout_msec = -1;
1037    }
1038    else if (timeout_usec == 0)
1039    {
1040        // Return immediately, don't wait
1041        timeout_msec = 0;
1042    }
1043    else
1044    {
1045        // Convert usec to msec
1046        timeout_msec = (timeout_usec + 999) / 1000;
1047    }
1048
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;
1054
1055    // Make sure the file descriptor can be used with select as it
1056    // must be in range
1057    if (data_fd >= 0)
1058    {
1059        const bool have_pipe_fd = pipe_fd >= 0;
1060        struct pollfd fds[2] =
1061        {
1062            { data_fd, POLLIN, 0 },
1063            { pipe_fd, POLLIN, 0 }
1064        };
1065        const int nfds = have_pipe_fd ? 2 : 1;
1066        Error error;
1067        while (data_fd == m_fd_recv)
1068        {
1069            const int num_set_fds = ::poll (fds, nfds, timeout_msec);
1070
1071            if (num_set_fds < 0)
1072                error.SetErrorToErrno();
1073            else
1074                error.Clear();
1075
1076            if (error_ptr)
1077                *error_ptr = error;
1078
1079            if (log)
1080            {
1081                if (have_pipe_fd)
1082                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::poll (fds={{%i,POLLIN},{%i,POLLIN}}, nfds=%i, timeout_ms=%i) => %d, error = %s\n",
1083                                this,
1084                                data_fd,
1085                                pipe_fd,
1086                                nfds,
1087                                timeout_msec,
1088                                num_set_fds,
1089                                error.AsCString());
1090                else
1091                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::poll (fds={{%i,POLLIN}}, nfds=%i, timeout_ms=%i) => %d, error = %s\n",
1092                                this,
1093                                data_fd,
1094                                nfds,
1095                                timeout_msec,
1096                                num_set_fds,
1097                                error.AsCString());
1098            }
1099
1100            if (error.Fail())
1101            {
1102                switch (error.GetError())
1103                {
1104                    case EBADF:     // One of the descriptor sets specified an invalid descriptor.
1105                        return eConnectionStatusLostConnection;
1106
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;
1110
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
1116                        // occurred.
1117                        break;      // Lets keep reading to until we timeout
1118                }
1119            }
1120            else if (num_set_fds == 0)
1121            {
1122                return eConnectionStatusTimedOut;
1123            }
1124            else if (num_set_fds > 0)
1125            {
1126                if (fds[0].revents & POLLIN)
1127                    return eConnectionStatusSuccess;
1128                if (fds[1].revents & POLLIN)
1129                {
1130                    // We got a command to exit.  Read the data from that pipe:
1131                    char buffer[16];
1132                    ssize_t bytes_read;
1133
1134                    do
1135                    {
1136                        bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
1137                    } while (bytes_read < 0 && errno == EINTR);
1138                    assert (bytes_read == 1 && buffer[0] == 'q');
1139
1140                    if (log)
1141                        log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
1142                                    this, (int) bytes_read, buffer);
1143
1144                    return eConnectionStatusEndOfFile;
1145                }
1146            }
1147        }
1148    }
1149    if (error_ptr)
1150        error_ptr->SetErrorString("not connected");
1151    return eConnectionStatusLostConnection;
1152}
1153
1154#endif
1155
1156ConnectionStatus
1157ConnectionFileDescriptor::Close (int& fd, FDType type, Error *error_ptr)
1158{
1159    if (error_ptr)
1160        error_ptr->Clear();
1161    bool success = true;
1162    // Avoid taking a lock if we can
1163    if (fd >= 0)
1164    {
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
1168        if (fd >= 0)
1169        {
1170            Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1171            if (log)
1172                log->Printf ("%p ConnectionFileDescriptor::Close (fd = %i)", this,fd);
1173#if _WIN32
1174            if (type != eFDTypeFile)
1175              success = closesocket(fd) == 0;
1176            else
1177#endif
1178            success = ::close (fd) == 0;
1179            // A reference to a FD was passed in, set it to an invalid value
1180            fd = -1;
1181            if (!success && error_ptr)
1182            {
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();
1187            }
1188        }
1189    }
1190    if (success)
1191        return eConnectionStatusSuccess;
1192    else
1193        return eConnectionStatusError;
1194}
1195
1196ConnectionStatus
1197ConnectionFileDescriptor::NamedSocketAccept (const char *socket_name, Error *error_ptr)
1198{
1199#ifndef LLDB_DISABLE_POSIX
1200    ConnectionStatus result = eConnectionStatusError;
1201    struct sockaddr_un saddr_un;
1202
1203    m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1204
1205    int listen_socket = ::socket (AF_UNIX, SOCK_STREAM, 0);
1206    if (listen_socket == -1)
1207    {
1208        if (error_ptr)
1209            error_ptr->SetErrorToErrno();
1210        return eConnectionStatusError;
1211    }
1212
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);
1218#endif
1219
1220    Host::Unlink (socket_name);
1221    if (::bind (listen_socket, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) == 0)
1222    {
1223        if (::listen (listen_socket, 5) == 0)
1224        {
1225            m_fd_send = m_fd_recv = ::accept (listen_socket, NULL, 0);
1226            if (m_fd_send > 0)
1227            {
1228                m_should_close_fd = true;
1229
1230                if (error_ptr)
1231                    error_ptr->Clear();
1232                result = eConnectionStatusSuccess;
1233            }
1234        }
1235    }
1236
1237    if (result != eConnectionStatusSuccess)
1238    {
1239        if (error_ptr)
1240            error_ptr->SetErrorToErrno();
1241    }
1242    // We are done with the listen port
1243    Close (listen_socket, eFDTypeSocket, NULL);
1244    return result;
1245#else
1246    return eConnectionStatusError;
1247#endif
1248}
1249
1250ConnectionStatus
1251ConnectionFileDescriptor::NamedSocketConnect (const char *socket_name, Error *error_ptr)
1252{
1253#ifndef LLDB_DISABLE_POSIX
1254    Disconnect (NULL);
1255    m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1256
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)
1261    {
1262        if (error_ptr)
1263            error_ptr->SetErrorToErrno();
1264        return eConnectionStatusError;
1265    }
1266
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);
1272#endif
1273
1274    if (::connect (m_fd_send, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) < 0)
1275    {
1276        if (error_ptr)
1277            error_ptr->SetErrorToErrno();
1278        Disconnect (NULL);
1279        return eConnectionStatusError;
1280    }
1281    if (error_ptr)
1282        error_ptr->Clear();
1283    return eConnectionStatusSuccess;
1284#else
1285    return eConnectionStatusError;
1286#endif
1287}
1288
1289ConnectionStatus
1290ConnectionFileDescriptor::SocketListen (const char *host_and_port, Error *error_ptr)
1291{
1292    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1293    if (log)
1294        log->Printf ("%p ConnectionFileDescriptor::SocketListen (%s)", this, host_and_port);
1295
1296    Disconnect (NULL);
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))
1302    {
1303        // Might be just a port number
1304        port = Args::StringToSInt32(host_and_port, -1);
1305        if (port == -1)
1306            return eConnectionStatusError;
1307        else
1308            host_str.clear();
1309    }
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)
1315    {
1316        if (error_ptr)
1317            error_ptr->SetErrorToErrno();
1318        return eConnectionStatusError;
1319    }
1320
1321    // enable local address reuse
1322    SetSocketOption (listen_fd, SOL_SOCKET, SO_REUSEADDR, 1);
1323
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);
1329    else
1330    {
1331        if (!listen_addr.getaddrinfo(host_str.c_str(), port_str.c_str(), family, socktype, protocol))
1332        {
1333            if (error_ptr)
1334                error_ptr->SetErrorStringWithFormat("unable to resolve hostname '%s'", host_str.c_str());
1335            Close (listen_fd, eFDTypeSocket, NULL);
1336            return eConnectionStatusError;
1337        }
1338    }
1339
1340    SocketAddress anyaddr;
1341    if (anyaddr.SetToAnyAddress (family, port))
1342    {
1343        int err = ::bind (listen_fd, anyaddr, anyaddr.GetLength());
1344        if (err == -1)
1345        {
1346            if (error_ptr)
1347                error_ptr->SetErrorToErrno();
1348            Close (listen_fd, eFDTypeSocket, NULL);
1349            return eConnectionStatusError;
1350        }
1351
1352        err = ::listen (listen_fd, 1);
1353        if (err == -1)
1354        {
1355            if (error_ptr)
1356                error_ptr->SetErrorToErrno();
1357            Close (listen_fd, eFDTypeSocket, NULL);
1358            return eConnectionStatusError;
1359        }
1360
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
1364        // for me".
1365        if (port == 0)
1366            port = GetSocketPort(listen_fd);
1367
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);
1374
1375
1376        bool accept_connection = false;
1377
1378        // Loop until we are happy with our connection
1379        while (!accept_connection)
1380        {
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;
1385#endif
1386            socklen_t accept_addr_len = sizeof accept_addr;
1387
1388            int fd = ::accept (listen_fd, (struct sockaddr *)&accept_addr, &accept_addr_len);
1389
1390            if (fd == -1)
1391            {
1392                if (error_ptr)
1393                    error_ptr->SetErrorToErrno();
1394                break;
1395            }
1396
1397            if (listen_addr.sockaddr_in().sin_addr.s_addr == INADDR_ANY)
1398            {
1399                accept_connection = true;
1400                m_fd_send = m_fd_recv = fd;
1401            }
1402            else
1403            {
1404                if (
1405#if !(defined(__linux__) || (defined(_MSC_VER)))
1406                    accept_addr_len == listen_addr.sockaddr_in().sin_len &&
1407#endif
1408                    accept_addr.sin_addr.s_addr == listen_addr.sockaddr_in().sin_addr.s_addr)
1409                {
1410                    accept_connection = true;
1411                    m_fd_send = m_fd_recv = fd;
1412                }
1413                else
1414                {
1415                    ::close (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]);
1422                }
1423            }
1424        }
1425
1426        if (m_fd_send == -1)
1427        {
1428            Close (listen_fd, eFDTypeSocket, NULL);
1429            return eConnectionStatusError;
1430        }
1431    }
1432
1433    // We are done with the listen port
1434    Close (listen_fd, eFDTypeSocket, NULL);
1435
1436    m_should_close_fd = true;
1437
1438    // Keep our TCP packets coming without any delays.
1439    SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1);
1440    if (error_ptr)
1441        error_ptr->Clear();
1442    return eConnectionStatusSuccess;
1443}
1444
1445ConnectionStatus
1446ConnectionFileDescriptor::ConnectTCP (const char *host_and_port, Error *error_ptr)
1447{
1448    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1449    if (log)
1450        log->Printf ("%p ConnectionFileDescriptor::ConnectTCP (host/port = %s)", this, host_and_port);
1451    Disconnect (NULL);
1452
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;
1459
1460    // Create the socket
1461    m_fd_send = m_fd_recv = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1462    if (m_fd_send == -1)
1463    {
1464        if (error_ptr)
1465            error_ptr->SetErrorToErrno();
1466        return eConnectionStatusError;
1467    }
1468
1469    m_should_close_fd = true;
1470
1471    // Enable local address reuse
1472    SetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, 1);
1473
1474    struct sockaddr_in sa;
1475    ::memset (&sa, 0, sizeof (sa));
1476    sa.sin_family = AF_INET;
1477    sa.sin_port = htons (port);
1478
1479    int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
1480
1481    if (inet_pton_result <= 0)
1482    {
1483        struct hostent *host_entry = gethostbyname (host_str.c_str());
1484        if (host_entry)
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)
1488        {
1489
1490            if (error_ptr)
1491            {
1492                if (inet_pton_result == -1)
1493                    error_ptr->SetErrorToErrno();
1494                else
1495                    error_ptr->SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str());
1496            }
1497            Disconnect (NULL);
1498
1499            return eConnectionStatusError;
1500        }
1501    }
1502
1503    if (-1 == ::connect (m_fd_send, (const struct sockaddr *)&sa, sizeof(sa)))
1504    {
1505        if (error_ptr)
1506            error_ptr->SetErrorToErrno();
1507        Disconnect (NULL);
1508
1509        return eConnectionStatusError;
1510    }
1511
1512    // Keep our TCP packets coming without any delays.
1513    SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1);
1514    if (error_ptr)
1515        error_ptr->Clear();
1516    return eConnectionStatusSuccess;
1517}
1518
1519ConnectionStatus
1520ConnectionFileDescriptor::ConnectUDP (const char *host_and_port, Error *error_ptr)
1521{
1522    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1523    if (log)
1524        log->Printf ("%p ConnectionFileDescriptor::ConnectUDP (host/port = %s)", this, host_and_port);
1525    Disconnect (NULL);
1526
1527    m_fd_send_type = m_fd_recv_type = eFDTypeSocketUDP;
1528
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;
1534
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)
1539    {
1540        // Socket creation failed...
1541        if (error_ptr)
1542            error_ptr->SetErrorToErrno();
1543    }
1544    else
1545    {
1546        // Socket was created, now lets bind to the requested port
1547        SocketAddress addr;
1548        addr.SetToAnyAddress (AF_INET, 0);
1549
1550        if (::bind (m_fd_recv, addr, addr.GetLength()) == -1)
1551        {
1552            // Bind failed...
1553            if (error_ptr)
1554                error_ptr->SetErrorToErrno();
1555            Disconnect (NULL);
1556        }
1557    }
1558
1559    if (m_fd_recv == -1)
1560        return eConnectionStatusError;
1561
1562    // At this point we have setup the recieve port, now we need to
1563    // setup the UDP send socket
1564
1565    struct addrinfo hints;
1566    struct addrinfo *service_info_list = NULL;
1567
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);
1572    if (err != 0)
1573    {
1574        if (error_ptr)
1575            error_ptr->SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)",
1576                                                host_str.c_str(),
1577                                                port_str.c_str(),
1578                                                err,
1579                                                gai_strerror(err));
1580        Disconnect (NULL);
1581        return eConnectionStatusError;
1582    }
1583
1584    for (struct addrinfo *service_info_ptr = service_info_list;
1585         service_info_ptr != NULL;
1586         service_info_ptr = service_info_ptr->ai_next)
1587    {
1588        m_fd_send = ::socket (service_info_ptr->ai_family,
1589                              service_info_ptr->ai_socktype,
1590                              service_info_ptr->ai_protocol);
1591
1592        if (m_fd_send != -1)
1593        {
1594            *m_udp_send_sockaddr = service_info_ptr;
1595            break;
1596        }
1597        else
1598            continue;
1599    }
1600
1601    :: freeaddrinfo (service_info_list);
1602
1603    if (m_fd_send == -1)
1604    {
1605        Disconnect (NULL);
1606        return eConnectionStatusError;
1607    }
1608
1609    if (error_ptr)
1610        error_ptr->Clear();
1611
1612    m_should_close_fd = true;
1613    return eConnectionStatusSuccess;
1614}
1615
1616#if defined(_WIN32)
1617typedef const char * set_socket_option_arg_type;
1618typedef char * get_socket_option_arg_type;
1619#else // #if defined(_WIN32)
1620typedef const void * set_socket_option_arg_type;
1621typedef void * get_socket_option_arg_type;
1622#endif // #if defined(_WIN32)
1623
1624int
1625ConnectionFileDescriptor::GetSocketOption(int fd, int level, int option_name, int &option_value)
1626{
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);
1630}
1631
1632int
1633ConnectionFileDescriptor::SetSocketOption(int fd, int level, int option_name, int option_value)
1634{
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));
1637}
1638
1639bool
1640ConnectionFileDescriptor::SetSocketReceiveTimeout (uint32_t timeout_usec)
1641{
1642    switch (m_fd_recv_type)
1643    {
1644        case eFDTypeFile:       // Other FD requireing read/write
1645            break;
1646
1647        case eFDTypeSocket:     // Socket requiring send/recv
1648        case eFDTypeSocketUDP:  // Unconnected UDP socket requiring sendto/recvfrom
1649        {
1650            // Check in case timeout for m_fd has already been set to this value
1651            if (timeout_usec == m_socket_timeout_usec)
1652                return true;
1653            //printf ("ConnectionFileDescriptor::SetSocketReceiveTimeout (timeout_usec = %u)\n", timeout_usec);
1654
1655            struct timeval timeout;
1656            if (timeout_usec == UINT32_MAX)
1657            {
1658                timeout.tv_sec = 0;
1659                timeout.tv_usec = 0;
1660            }
1661            else if (timeout_usec == 0)
1662            {
1663                // Sending in zero does an infinite timeout, so set this as low
1664                // as we can go to get an effective zero timeout...
1665                timeout.tv_sec = 0;
1666                timeout.tv_usec = 1;
1667            }
1668            else
1669            {
1670                timeout.tv_sec = timeout_usec / TimeValue::MicroSecPerSec;
1671                timeout.tv_usec = timeout_usec % TimeValue::MicroSecPerSec;
1672            }
1673            if (::setsockopt (m_fd_recv, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<get_socket_option_arg_type>(&timeout), sizeof(timeout)) == 0)
1674            {
1675                m_socket_timeout_usec = timeout_usec;
1676                return true;
1677            }
1678        }
1679    }
1680    return false;
1681}
1682
1683uint16_t
1684ConnectionFileDescriptor::GetSocketPort (int fd)
1685{
1686    // We bound to port zero, so we need to figure out which port we actually bound to
1687    if (fd >= 0)
1688    {
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 ();
1693    }
1694    return 0;
1695}
1696
1697// If the read file descriptor is a socket, then return
1698// the port number that is being used by the socket.
1699uint16_t
1700ConnectionFileDescriptor::GetReadPort () const
1701{
1702    return ConnectionFileDescriptor::GetSocketPort (m_fd_recv);
1703}
1704
1705// If the write file descriptor is a socket, then return
1706// the port number that is being used by the socket.
1707uint16_t
1708ConnectionFileDescriptor::GetWritePort () const
1709{
1710    return ConnectionFileDescriptor::GetSocketPort (m_fd_send);
1711}
1712
1713uint16_t
1714ConnectionFileDescriptor::GetBoundPort (uint32_t timeout_sec)
1715{
1716    uint16_t bound_port = 0;
1717    if (timeout_sec == UINT32_MAX)
1718        m_port_predicate.WaitForValueNotEqualTo (0, bound_port);
1719    else
1720    {
1721        TimeValue timeout = TimeValue::Now();
1722        timeout.OffsetWithSeconds(timeout_sec);
1723        m_port_predicate.WaitForValueNotEqualTo (0, bound_port, &timeout);
1724    }
1725    return bound_port;
1726}
1727