ConnectionFileDescriptor.cpp revision 263367
11539Srgrimes//===-- ConnectionFileDescriptor.cpp ----------------------------*- C++ -*-===//
21539Srgrimes//
31539Srgrimes//                     The LLVM Compiler Infrastructure
41539Srgrimes//
51539Srgrimes// This file is distributed under the University of Illinois Open Source
61539Srgrimes// License. See LICENSE.TXT for details.
71539Srgrimes//
81539Srgrimes//===----------------------------------------------------------------------===//
91539Srgrimes
101539Srgrimes#if defined(__APPLE__)
111539Srgrimes// Enable this special support for Apple builds where we can have unlimited
121539Srgrimes// select bounds. We tried switching to poll() and kqueue and we were panicing
131539Srgrimes// the kernel, so we have to stick with select for now.
141539Srgrimes#define _DARWIN_UNLIMITED_SELECT
151539Srgrimes#endif
161539Srgrimes
171539Srgrimes#include "lldb/Core/ConnectionFileDescriptor.h"
181539Srgrimes#include "lldb/Host/Config.h"
191539Srgrimes#include "lldb/Host/SocketAddress.h"
201539Srgrimes
211539Srgrimes// C Includes
221539Srgrimes#include <errno.h>
231539Srgrimes#include <fcntl.h>
241539Srgrimes#include <string.h>
251539Srgrimes#include <stdlib.h>
261539Srgrimes#include <sys/types.h>
271539Srgrimes#ifndef LLDB_DISABLE_POSIX
281539Srgrimes#include <arpa/inet.h>
291539Srgrimes#include <netdb.h>
301539Srgrimes#include <netinet/in.h>
311539Srgrimes#include <netinet/tcp.h>
321539Srgrimes#include <sys/socket.h>
331539Srgrimes#include <sys/un.h>
341539Srgrimes#include <termios.h>
351539Srgrimes#include <unistd.h>
361539Srgrimes#endif
371539Srgrimes#ifdef _WIN32
381539Srgrimes#include "lldb/Host/windows/windows.h"
391539Srgrimes#include <winsock2.h>
401539Srgrimes#include <WS2tcpip.h>
411539Srgrimes#endif
421539Srgrimes
431539Srgrimes// C++ Includes
441539Srgrimes// Other libraries and framework includes
451539Srgrimes#include "llvm/Support/ErrorHandling.h"
461539Srgrimes#if defined(__APPLE__)
471539Srgrimes#include "llvm/ADT/SmallVector.h"
481539Srgrimes#endif
491539Srgrimes// Project includes
501539Srgrimes#include "lldb/lldb-private-log.h"
511539Srgrimes#include "lldb/Interpreter/Args.h"
521539Srgrimes#include "lldb/Core/Communication.h"
531539Srgrimes#include "lldb/Core/Log.h"
541539Srgrimes#include "lldb/Core/RegularExpression.h"
551539Srgrimes#include "lldb/Core/Timer.h"
561539Srgrimes#include "lldb/Host/Host.h"
571539Srgrimes
581539Srgrimes
591539Srgrimesusing namespace lldb;
601539Srgrimesusing namespace lldb_private;
611539Srgrimes
621539Srgrimesstatic bool
631539SrgrimesDecodeHostAndPort (const char *host_and_port,
641539Srgrimes                   std::string &host_str,
651539Srgrimes                   std::string &port_str,
661539Srgrimes                   int32_t& port,
671539Srgrimes                   Error *error_ptr)
681539Srgrimes{
691539Srgrimes    static RegularExpression g_regex ("([^:]+):([0-9]+)");
701539Srgrimes    RegularExpression::Match regex_match(2);
711539Srgrimes    if (g_regex.Execute (host_and_port, &regex_match))
721539Srgrimes    {
731539Srgrimes        if (regex_match.GetMatchAtIndex (host_and_port, 1, host_str) &&
741539Srgrimes            regex_match.GetMatchAtIndex (host_and_port, 2, port_str))
751539Srgrimes        {
761539Srgrimes            port = Args::StringToSInt32 (port_str.c_str(), INT32_MIN);
771539Srgrimes            if (port != INT32_MIN)
781539Srgrimes            {
791539Srgrimes                if (error_ptr)
801539Srgrimes                    error_ptr->Clear();
811539Srgrimes                return true;
821539Srgrimes            }
831539Srgrimes        }
841539Srgrimes    }
851539Srgrimes    host_str.clear();
861539Srgrimes    port_str.clear();
871539Srgrimes    port = INT32_MIN;
881539Srgrimes    if (error_ptr)
891539Srgrimes        error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port);
901539Srgrimes    return false;
911539Srgrimes}
921539Srgrimes
931539SrgrimesConnectionFileDescriptor::ConnectionFileDescriptor () :
941539Srgrimes    Connection(),
951539Srgrimes    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_should_close_fd (false),
101    m_socket_timeout_usec(0),
102    m_pipe_read(-1),
103    m_pipe_write(-1),
104    m_mutex (Mutex::eMutexTypeRecursive),
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_should_close_fd (owns_fd),
120    m_socket_timeout_usec(0),
121    m_pipe_read(-1),
122    m_pipe_write(-1),
123    m_mutex (Mutex::eMutexTypeRecursive),
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        char *end = NULL;
222        if (strstr(s, "listen://"))
223        {
224            // listen://HOST:PORT
225            unsigned long listen_port = ::strtoul(s + strlen("listen://"), &end, 0);
226            return SocketListen (listen_port, error_ptr);
227        }
228        else if (strstr(s, "unix-accept://"))
229        {
230            // unix://SOCKNAME
231            return NamedSocketAccept (s + strlen("unix-accept://"), error_ptr);
232        }
233        else if (strstr(s, "connect://"))
234        {
235            return ConnectTCP (s + strlen("connect://"), error_ptr);
236        }
237        else if (strstr(s, "tcp-connect://"))
238        {
239            return ConnectTCP (s + strlen("tcp-connect://"), error_ptr);
240        }
241        else if (strstr(s, "udp://"))
242        {
243            return ConnectUDP (s + strlen("udp://"), error_ptr);
244        }
245        else if (strstr(s, "fd://"))
246        {
247            // Just passing a native file descriptor within this current process
248            // that is already opened (possibly from a service or other source).
249            s += strlen ("fd://");
250            bool success = false;
251            m_fd_send = m_fd_recv = Args::StringToSInt32 (s, -1, 0, &success);
252
253            if (success)
254            {
255                // We have what looks to be a valid file descriptor, but we
256                // should make sure it is. We currently are doing this by trying to
257                // get the flags from the file descriptor and making sure it
258                // isn't a bad fd.
259                errno = 0;
260#ifndef LLDB_DISABLE_POSIX
261                int flags = ::fcntl (m_fd_send, F_GETFL, 0);
262#else
263                int flags = -1;
264#endif
265                if (flags == -1 || errno == EBADF)
266                {
267                    if (error_ptr)
268                        error_ptr->SetErrorStringWithFormat ("stale file descriptor: %s", s);
269                    m_fd_send = m_fd_recv = -1;
270                    return eConnectionStatusError;
271                }
272                else
273                {
274                    // Try and get a socket option from this file descriptor to
275                    // see if this is a socket and set m_is_socket accordingly.
276                    int resuse;
277                    bool is_socket = GetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, resuse) == 0;
278                    if (is_socket)
279                        m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
280                    // Don't take ownership of a file descriptor that gets passed
281                    // to us since someone else opened the file descriptor and
282                    // handed it to us.
283                    // TODO: Since are using a URL to open connection we should
284                    // eventually parse options using the web standard where we
285                    // have "fd://123?opt1=value;opt2=value" and we can have an
286                    // option be "owns=1" or "owns=0" or something like this to
287                    // allow us to specify this. For now, we assume we must
288                    // assume we don't own it.
289                    m_should_close_fd = false;
290                    return eConnectionStatusSuccess;
291                }
292            }
293
294            if (error_ptr)
295                error_ptr->SetErrorStringWithFormat ("invalid file descriptor: \"fd://%s\"", s);
296            m_fd_send = m_fd_recv = -1;
297            return eConnectionStatusError;
298        }
299        else if (strstr(s, "file://"))
300        {
301            // file:///PATH
302            const char *path = s + strlen("file://");
303#ifndef LLDB_DISABLE_POSIX
304            do
305            {
306                m_fd_send = m_fd_recv = ::open (path, O_RDWR);
307            } while (m_fd_send == -1 && errno == EINTR);
308            if (m_fd_send == -1)
309            {
310                if (error_ptr)
311                    error_ptr->SetErrorToErrno();
312                return eConnectionStatusError;
313            }
314
315            if (::isatty(m_fd_send))
316            {
317                // Set up serial terminal emulation
318                struct termios options;
319                ::tcgetattr (m_fd_send, &options);
320
321                // Set port speed to maximum
322                ::cfsetospeed (&options, B115200);
323                ::cfsetispeed (&options, B115200);
324
325                // Raw input, disable echo and signals
326                options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
327
328                // Make sure only one character is needed to return from a read
329                options.c_cc[VMIN]  = 1;
330                options.c_cc[VTIME] = 0;
331
332                ::tcsetattr (m_fd_send, TCSANOW, &options);
333            }
334
335            int flags = ::fcntl (m_fd_send, F_GETFL, 0);
336            if (flags >= 0)
337            {
338                if ((flags & O_NONBLOCK) == 0)
339                {
340                    flags |= O_NONBLOCK;
341                    ::fcntl (m_fd_send, F_SETFL, flags);
342                }
343            }
344            m_should_close_fd = true;
345            return eConnectionStatusSuccess;
346#else
347            return eConnectionStatusError;
348#endif
349        }
350        if (error_ptr)
351            error_ptr->SetErrorStringWithFormat ("unsupported connection URL: '%s'", s);
352        return eConnectionStatusError;
353    }
354    if (error_ptr)
355        error_ptr->SetErrorString("invalid connect arguments");
356    return eConnectionStatusError;
357}
358
359ConnectionStatus
360ConnectionFileDescriptor::Disconnect (Error *error_ptr)
361{
362    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
363    if (log)
364        log->Printf ("%p ConnectionFileDescriptor::Disconnect ()", this);
365
366    ConnectionStatus status = eConnectionStatusSuccess;
367
368    if (m_fd_send < 0 && m_fd_recv < 0)
369    {
370        if (log)
371            log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Nothing to disconnect", this);
372        return eConnectionStatusSuccess;
373    }
374
375    // Try to get the ConnectionFileDescriptor's mutex.  If we fail, that is quite likely
376    // because somebody is doing a blocking read on our file descriptor.  If that's the case,
377    // then send the "q" char to the command file channel so the read will wake up and the connection
378    // will then know to shut down.
379
380    m_shutting_down = true;
381
382    Mutex::Locker locker;
383    bool got_lock= locker.TryLock (m_mutex);
384
385    if (!got_lock)
386    {
387        if (m_pipe_write != -1 )
388        {
389            int result;
390            result = write (m_pipe_write, "q", 1);
391            if (log)
392                log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Couldn't get the lock, sent 'q' to %d, result = %d.", this, m_pipe_write, result);
393        }
394        else if (log)
395            log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Couldn't get the lock, but no command pipe is available.", this);
396        locker.Lock (m_mutex);
397    }
398
399    if (m_should_close_fd == true)
400    {
401        if (m_fd_send == m_fd_recv)
402        {
403            status = Close (m_fd_send, m_fd_send_type, error_ptr);
404        }
405        else
406        {
407            // File descriptors are the different, close both if needed
408            if (m_fd_send >= 0)
409                status = Close (m_fd_send, m_fd_send_type, error_ptr);
410            if (m_fd_recv >= 0)
411            {
412                ConnectionStatus recv_status = Close (m_fd_recv, m_fd_recv_type, error_ptr);
413                if (status == eConnectionStatusSuccess)
414                    status = recv_status;
415            }
416        }
417    }
418
419    // Now set all our descriptors to invalid values.
420
421    m_fd_send = m_fd_recv = -1;
422
423    if (status != eConnectionStatusSuccess)
424    {
425
426        return status;
427    }
428
429    m_shutting_down = false;
430    return eConnectionStatusSuccess;
431}
432
433size_t
434ConnectionFileDescriptor::Read (void *dst,
435                                size_t dst_len,
436                                uint32_t timeout_usec,
437                                ConnectionStatus &status,
438                                Error *error_ptr)
439{
440    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
441    if (log)
442        log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %" PRIu64 ")...",
443                     this, m_fd_recv, dst, (uint64_t)dst_len);
444
445    Mutex::Locker locker;
446    bool got_lock = locker.TryLock (m_mutex);
447    if (!got_lock)
448    {
449        if (log)
450            log->Printf ("%p ConnectionFileDescriptor::Read () failed to get the connection lock.",
451                     this);
452        if (error_ptr)
453            error_ptr->SetErrorString ("failed to get the connection lock for read.");
454
455        status = eConnectionStatusTimedOut;
456        return 0;
457    }
458    else if (m_shutting_down)
459        return eConnectionStatusError;
460
461    ssize_t bytes_read = 0;
462
463    status = BytesAvailable (timeout_usec, error_ptr);
464    if (status == eConnectionStatusSuccess)
465    {
466        do
467        {
468#ifndef LLDB_DISABLE_POSIX
469            bytes_read = ::read (m_fd_recv, dst, dst_len);
470#else
471            switch (m_fd_send_type) {
472            case eFDTypeSocket:
473            case eFDTypeSocketUDP:
474                bytes_read = ::recv (m_fd_recv, (char*)dst, dst_len, 0);
475                break;
476            default:
477                bytes_read = -1;
478                break;
479
480            }
481
482#endif
483        } while (bytes_read < 0 && errno == EINTR);
484    }
485
486    if (status != eConnectionStatusSuccess)
487        return 0;
488
489    Error error;
490    if (bytes_read == 0)
491    {
492        error.Clear(); // End-of-file.  Do not automatically close; pass along for the end-of-file handlers.
493        status = eConnectionStatusEndOfFile;
494    }
495    else if (bytes_read < 0)
496    {
497        error.SetErrorToErrno();
498    }
499    else
500    {
501        error.Clear();
502    }
503
504    if (log)
505        log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %" PRIu64 ") => %" PRIi64 ", error = %s",
506                     this,
507                     m_fd_recv,
508                     dst,
509                     (uint64_t)dst_len,
510                     (int64_t)bytes_read,
511                     error.AsCString());
512
513    if (error_ptr)
514        *error_ptr = error;
515
516    if (error.Fail())
517    {
518        uint32_t error_value = error.GetError();
519        switch (error_value)
520        {
521        case EAGAIN:    // The file was marked for non-blocking I/O, and no data were ready to be read.
522            if (m_fd_recv_type == eFDTypeSocket || m_fd_recv_type == eFDTypeSocketUDP)
523                status = eConnectionStatusTimedOut;
524            else
525                status = eConnectionStatusSuccess;
526            return 0;
527
528        case EFAULT:    // Buf points outside the allocated address space.
529        case EINTR:     // A read from a slow device was interrupted before any data arrived by the delivery of a signal.
530        case EINVAL:    // The pointer associated with fildes was negative.
531        case EIO:       // An I/O error occurred while reading from the file system.
532                        // The process group is orphaned.
533                        // The file is a regular file, nbyte is greater than 0,
534                        // the starting position is before the end-of-file, and
535                        // the starting position is greater than or equal to the
536                        // offset maximum established for the open file
537                        // descriptor associated with fildes.
538        case EISDIR:    // An attempt is made to read a directory.
539        case ENOBUFS:   // An attempt to allocate a memory buffer fails.
540        case ENOMEM:    // Insufficient memory is available.
541            status = eConnectionStatusError;
542            break;  // Break to close....
543
544        case ENOENT:    // no such file or directory
545        case EBADF:     // fildes is not a valid file or socket descriptor open for reading.
546        case ENXIO:     // An action is requested of a device that does not exist..
547                        // A requested action cannot be performed by the device.
548        case ECONNRESET:// The connection is closed by the peer during a read attempt on a socket.
549        case ENOTCONN:  // A read is attempted on an unconnected socket.
550            status = eConnectionStatusLostConnection;
551            break;  // Break to close....
552
553        case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a socket.
554            status = eConnectionStatusTimedOut;
555            return 0;
556
557        default:
558            if (log)
559                log->Printf("%p ConnectionFileDescriptor::Read (), unexpected error: %s", this, strerror(error_value));
560            status = eConnectionStatusError;
561            break;  // Break to close....
562
563        }
564
565        return 0;
566    }
567    return bytes_read;
568}
569
570size_t
571ConnectionFileDescriptor::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr)
572{
573    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
574    if (log)
575        log->Printf ("%p ConnectionFileDescriptor::Write (src = %p, src_len = %" PRIu64 ")", this, src, (uint64_t)src_len);
576
577    if (!IsConnected ())
578    {
579        if (error_ptr)
580            error_ptr->SetErrorString("not connected");
581        status = eConnectionStatusNoConnection;
582        return 0;
583    }
584
585
586    Error error;
587
588    ssize_t bytes_sent = 0;
589
590    switch (m_fd_send_type)
591    {
592#ifndef LLDB_DISABLE_POSIX
593        case eFDTypeFile:       // Other FD requireing read/write
594            do
595            {
596                bytes_sent = ::write (m_fd_send, src, src_len);
597            } while (bytes_sent < 0 && errno == EINTR);
598            break;
599#endif
600        case eFDTypeSocket:     // Socket requiring send/recv
601            do
602            {
603                bytes_sent = ::send (m_fd_send, (char*)src, src_len, 0);
604            } while (bytes_sent < 0 && errno == EINTR);
605            break;
606
607        case eFDTypeSocketUDP:  // Unconnected UDP socket requiring sendto/recvfrom
608            assert (m_udp_send_sockaddr->GetFamily() != 0);
609            do
610            {
611                bytes_sent = ::sendto (m_fd_send,
612                                       (char*)src,
613                                       src_len,
614                                       0,
615                                       *m_udp_send_sockaddr,
616                                       m_udp_send_sockaddr->GetLength());
617            } while (bytes_sent < 0 && errno == EINTR);
618            break;
619    }
620
621    if (bytes_sent < 0)
622        error.SetErrorToErrno ();
623    else
624        error.Clear ();
625
626    if (log)
627    {
628        switch (m_fd_send_type)
629        {
630            case eFDTypeFile:       // Other FD requireing read/write
631                log->Printf ("%p ConnectionFileDescriptor::Write()  ::write (fd = %i, src = %p, src_len = %" PRIu64 ") => %" PRIi64 " (error = %s)",
632                             this,
633                             m_fd_send,
634                             src,
635                             (uint64_t)src_len,
636                             (int64_t)bytes_sent,
637                             error.AsCString());
638                break;
639
640            case eFDTypeSocket:     // Socket requiring send/recv
641                log->Printf ("%p ConnectionFileDescriptor::Write()  ::send (socket = %i, src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
642                             this,
643                             m_fd_send,
644                             src,
645                             (uint64_t)src_len,
646                             (int64_t)bytes_sent,
647                             error.AsCString());
648                break;
649
650            case eFDTypeSocketUDP:  // Unconnected UDP socket requiring sendto/recvfrom
651                log->Printf ("%p ConnectionFileDescriptor::Write()  ::sendto (socket = %i, src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
652                             this,
653                             m_fd_send,
654                             src,
655                             (uint64_t)src_len,
656                             (int64_t)bytes_sent,
657                             error.AsCString());
658                break;
659        }
660    }
661
662    if (error_ptr)
663        *error_ptr = error;
664
665    if (error.Fail())
666    {
667        switch (error.GetError())
668        {
669        case EAGAIN:
670        case EINTR:
671            status = eConnectionStatusSuccess;
672            return 0;
673
674        case ECONNRESET:// The connection is closed by the peer during a read attempt on a socket.
675        case ENOTCONN:  // A read is attempted on an unconnected socket.
676            status = eConnectionStatusLostConnection;
677            break;  // Break to close....
678
679        default:
680            status = eConnectionStatusError;
681            break;  // Break to close....
682        }
683
684        return 0;
685    }
686
687    status = eConnectionStatusSuccess;
688    return bytes_sent;
689}
690
691
692
693#if defined(__APPLE__)
694
695// This ConnectionFileDescriptor::BytesAvailable() uses select().
696//
697// PROS:
698//  - select is consistent across most unix platforms
699//  - this Apple specific version allows for unlimited fds in the fd_sets by
700//    setting the _DARWIN_UNLIMITED_SELECT define prior to including the
701//    required header files.
702
703// CONS:
704//  - Darwin only
705
706ConnectionStatus
707ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
708{
709    // Don't need to take the mutex here separately since we are only called from Read.  If we
710    // ever get used more generally we will need to lock here as well.
711
712    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
713    if (log)
714        log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
715    struct timeval *tv_ptr;
716    struct timeval tv;
717    if (timeout_usec == UINT32_MAX)
718    {
719        // Infinite wait...
720        tv_ptr = NULL;
721    }
722    else
723    {
724        TimeValue time_value;
725        time_value.OffsetWithMicroSeconds (timeout_usec);
726        tv.tv_sec = time_value.seconds();
727        tv.tv_usec = time_value.microseconds();
728        tv_ptr = &tv;
729    }
730
731    // Make a copy of the file descriptors to make sure we don't
732    // have another thread change these values out from under us
733    // and cause problems in the loop below where like in FS_SET()
734    const int data_fd = m_fd_recv;
735    const int pipe_fd = m_pipe_read;
736
737    if (data_fd >= 0)
738    {
739        const bool have_pipe_fd = pipe_fd >= 0;
740
741        while (data_fd == m_fd_recv)
742        {
743            const int nfds = std::max<int>(data_fd, pipe_fd) + 1;
744            llvm::SmallVector<fd_set, 1> read_fds;
745            read_fds.resize((nfds/FD_SETSIZE) + 1);
746            for (size_t i=0; i<read_fds.size(); ++i)
747                FD_ZERO (&read_fds[i]);
748            // FD_SET doesn't bounds check, it just happily walks off the end
749            // but we have taken care of making the extra storage with our
750            // SmallVector of fd_set objects
751            FD_SET (data_fd, read_fds.data());
752            if (have_pipe_fd)
753                FD_SET (pipe_fd, read_fds.data());
754
755            Error error;
756
757            if (log)
758            {
759                if (have_pipe_fd)
760                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p)...",
761                                this, nfds, data_fd, pipe_fd, tv_ptr);
762                else
763                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p)...",
764                                this, nfds, data_fd, tv_ptr);
765            }
766
767            const int num_set_fds = ::select (nfds, read_fds.data(), NULL, NULL, tv_ptr);
768            if (num_set_fds < 0)
769                error.SetErrorToErrno();
770            else
771                error.Clear();
772
773            if (log)
774            {
775                if (have_pipe_fd)
776                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p) => %d, error = %s",
777                                this, nfds, data_fd, pipe_fd, tv_ptr, num_set_fds, error.AsCString());
778                else
779                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p) => %d, error = %s",
780                                this, nfds, data_fd, tv_ptr, num_set_fds, error.AsCString());
781            }
782
783            if (error_ptr)
784                *error_ptr = error;
785
786            if (error.Fail())
787            {
788                switch (error.GetError())
789                {
790                    case EBADF:     // One of the descriptor sets specified an invalid descriptor.
791                        return eConnectionStatusLostConnection;
792
793                    case EINVAL:    // The specified time limit is invalid. One of its components is negative or too large.
794                    default:        // Other unknown error
795                        return eConnectionStatusError;
796
797                    case EAGAIN:    // The kernel was (perhaps temporarily) unable to
798                        // allocate the requested number of file descriptors,
799                        // or we have non-blocking IO
800                    case EINTR:     // A signal was delivered before the time limit
801                        // expired and before any of the selected events
802                        // occurred.
803                        break;      // Lets keep reading to until we timeout
804                }
805            }
806            else if (num_set_fds == 0)
807            {
808                return eConnectionStatusTimedOut;
809            }
810            else if (num_set_fds > 0)
811            {
812                // FD_ISSET is happy to deal with a something larger than
813                // a single fd_set.
814                if (FD_ISSET(data_fd, read_fds.data()))
815                    return eConnectionStatusSuccess;
816                if (have_pipe_fd && FD_ISSET(pipe_fd, read_fds.data()))
817                {
818                    // We got a command to exit.  Read the data from that pipe:
819                    char buffer[16];
820                    ssize_t bytes_read;
821
822                    do
823                    {
824                        bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
825                    } while (bytes_read < 0 && errno == EINTR);
826                    assert (bytes_read == 1 && buffer[0] == 'q');
827
828                    if (log)
829                        log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
830                                    this, (int) bytes_read, buffer);
831
832                    return eConnectionStatusEndOfFile;
833                }
834            }
835        }
836    }
837
838    if (error_ptr)
839        error_ptr->SetErrorString("not connected");
840    return eConnectionStatusLostConnection;
841}
842
843#else
844
845// This ConnectionFileDescriptor::BytesAvailable() uses select().
846//
847// PROS:
848//  - select is consistent across most unix platforms
849// CONS:
850//  - only supports file descriptors up to FD_SETSIZE. This implementation
851//    will assert if it runs into that hard limit to let users know that
852//    another ConnectionFileDescriptor::BytesAvailable() should be used
853//    or a new version of ConnectionFileDescriptor::BytesAvailable() should
854//    be written for the system that is running into the limitations. MacOSX
855//    uses kqueues, and there is a poll() based implementation below.
856
857ConnectionStatus
858ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
859{
860    // Don't need to take the mutex here separately since we are only called from Read.  If we
861    // ever get used more generally we will need to lock here as well.
862
863    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
864    if (log)
865        log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
866    struct timeval *tv_ptr;
867    struct timeval tv;
868    if (timeout_usec == UINT32_MAX)
869    {
870        // Infinite wait...
871        tv_ptr = NULL;
872    }
873    else
874    {
875        TimeValue time_value;
876        time_value.OffsetWithMicroSeconds (timeout_usec);
877        tv.tv_sec = time_value.seconds();
878        tv.tv_usec = time_value.microseconds();
879        tv_ptr = &tv;
880    }
881
882    // Make a copy of the file descriptors to make sure we don't
883    // have another thread change these values out from under us
884    // and cause problems in the loop below where like in FS_SET()
885    const int data_fd = m_fd_recv;
886    const int pipe_fd = m_pipe_read;
887
888    if (data_fd >= 0)
889    {
890        // If this assert fires off on MacOSX, we will need to switch to using
891        // libdispatch to read from file descriptors because poll() is causing
892        // kernel panics and if we exceed FD_SETSIZE we will have no choice...
893#ifndef _MSC_VER
894        assert (data_fd < FD_SETSIZE);
895#endif
896
897        const bool have_pipe_fd = pipe_fd >= 0;
898
899        if (have_pipe_fd)
900        {
901            assert (pipe_fd < FD_SETSIZE);
902        }
903
904        while (data_fd == m_fd_recv)
905        {
906            fd_set read_fds;
907            FD_ZERO (&read_fds);
908            FD_SET (data_fd, &read_fds);
909            if (have_pipe_fd)
910                FD_SET (pipe_fd, &read_fds);
911
912            const int nfds = std::max<int>(data_fd, pipe_fd) + 1;
913
914            Error error;
915
916            if (log)
917            {
918                if (have_pipe_fd)
919                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p)...",
920                                this, nfds, data_fd, pipe_fd, tv_ptr);
921                else
922                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p)...",
923                                this, nfds, data_fd, tv_ptr);
924            }
925
926            const int num_set_fds = ::select (nfds, &read_fds, NULL, NULL, tv_ptr);
927            if (num_set_fds < 0)
928                error.SetErrorToErrno();
929            else
930                error.Clear();
931
932            if (log)
933            {
934                if (have_pipe_fd)
935                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p) => %d, error = %s",
936                                this, nfds, data_fd, pipe_fd, tv_ptr, num_set_fds, error.AsCString());
937                else
938                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p) => %d, error = %s",
939                                this, nfds, data_fd, tv_ptr, num_set_fds, error.AsCString());
940            }
941
942            if (error_ptr)
943                *error_ptr = error;
944
945            if (error.Fail())
946            {
947                switch (error.GetError())
948                {
949                    case EBADF:     // One of the descriptor sets specified an invalid descriptor.
950                        return eConnectionStatusLostConnection;
951
952                    case EINVAL:    // The specified time limit is invalid. One of its components is negative or too large.
953                    default:        // Other unknown error
954                        return eConnectionStatusError;
955
956                    case EAGAIN:    // The kernel was (perhaps temporarily) unable to
957                        // allocate the requested number of file descriptors,
958                        // or we have non-blocking IO
959                    case EINTR:     // A signal was delivered before the time limit
960                        // expired and before any of the selected events
961                        // occurred.
962                        break;      // Lets keep reading to until we timeout
963                }
964            }
965            else if (num_set_fds == 0)
966            {
967                return eConnectionStatusTimedOut;
968            }
969            else if (num_set_fds > 0)
970            {
971                if (FD_ISSET(data_fd, &read_fds))
972                    return eConnectionStatusSuccess;
973                if (have_pipe_fd && FD_ISSET(pipe_fd, &read_fds))
974                {
975                    // We got a command to exit.  Read the data from that pipe:
976                    char buffer[16];
977                    ssize_t bytes_read;
978
979                    do
980                    {
981                        bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
982                    } while (bytes_read < 0 && errno == EINTR);
983                    assert (bytes_read == 1 && buffer[0] == 'q');
984
985                    if (log)
986                        log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
987                                    this, (int) bytes_read, buffer);
988
989                    return eConnectionStatusEndOfFile;
990                }
991            }
992        }
993    }
994
995    if (error_ptr)
996        error_ptr->SetErrorString("not connected");
997    return eConnectionStatusLostConnection;
998}
999
1000#endif
1001
1002#if 0
1003#include <poll.h>
1004
1005// This ConnectionFileDescriptor::BytesAvailable() uses poll(). poll() should NOT
1006// be used on MacOSX as it has all sorts of restrictions on the types of file descriptors
1007// that it doesn't support.
1008//
1009// There may be some systems that properly support poll() that could use this
1010// implementation. I will let each system opt into this on their own.
1011//
1012// PROS:
1013//  - no restrictions on the fd value that is used
1014// CONS:
1015//  - varies wildly from platform to platform in its implementation restrictions
1016
1017ConnectionStatus
1018ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
1019{
1020    // Don't need to take the mutex here separately since we are only called from Read.  If we
1021    // ever get used more generally we will need to lock here as well.
1022
1023    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1024    if (log)
1025        log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
1026    int timeout_msec = 0;
1027    if (timeout_usec == UINT32_MAX)
1028    {
1029        // Infinite wait...
1030        timeout_msec = -1;
1031    }
1032    else if (timeout_usec == 0)
1033    {
1034        // Return immediately, don't wait
1035        timeout_msec = 0;
1036    }
1037    else
1038    {
1039        // Convert usec to msec
1040        timeout_msec = (timeout_usec + 999) / 1000;
1041    }
1042
1043    // Make a copy of the file descriptors to make sure we don't
1044    // have another thread change these values out from under us
1045    // and cause problems in the loop below where like in FS_SET()
1046    const int data_fd = m_fd_recv;
1047    const int pipe_fd = m_pipe_read;
1048
1049    // Make sure the file descriptor can be used with select as it
1050    // must be in range
1051    if (data_fd >= 0)
1052    {
1053        const bool have_pipe_fd = pipe_fd >= 0;
1054        struct pollfd fds[2] =
1055        {
1056            { data_fd, POLLIN, 0 },
1057            { pipe_fd, POLLIN, 0 }
1058        };
1059        const int nfds = have_pipe_fd ? 2 : 1;
1060        Error error;
1061        while (data_fd == m_fd_recv)
1062        {
1063            const int num_set_fds = ::poll (fds, nfds, timeout_msec);
1064
1065            if (num_set_fds < 0)
1066                error.SetErrorToErrno();
1067            else
1068                error.Clear();
1069
1070            if (error_ptr)
1071                *error_ptr = error;
1072
1073            if (log)
1074            {
1075                if (have_pipe_fd)
1076                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::poll (fds={{%i,POLLIN},{%i,POLLIN}}, nfds=%i, timeout_ms=%i) => %d, error = %s\n",
1077                                this,
1078                                data_fd,
1079                                pipe_fd,
1080                                nfds,
1081                                timeout_msec,
1082                                num_set_fds,
1083                                error.AsCString());
1084                else
1085                    log->Printf("%p ConnectionFileDescriptor::BytesAvailable()  ::poll (fds={{%i,POLLIN}}, nfds=%i, timeout_ms=%i) => %d, error = %s\n",
1086                                this,
1087                                data_fd,
1088                                nfds,
1089                                timeout_msec,
1090                                num_set_fds,
1091                                error.AsCString());
1092            }
1093
1094            if (error.Fail())
1095            {
1096                switch (error.GetError())
1097                {
1098                    case EBADF:     // One of the descriptor sets specified an invalid descriptor.
1099                        return eConnectionStatusLostConnection;
1100
1101                    case EINVAL:    // The specified time limit is invalid. One of its components is negative or too large.
1102                    default:        // Other unknown error
1103                        return eConnectionStatusError;
1104
1105                    case EAGAIN:    // The kernel was (perhaps temporarily) unable to
1106                        // allocate the requested number of file descriptors,
1107                        // or we have non-blocking IO
1108                    case EINTR:     // A signal was delivered before the time limit
1109                        // expired and before any of the selected events
1110                        // occurred.
1111                        break;      // Lets keep reading to until we timeout
1112                }
1113            }
1114            else if (num_set_fds == 0)
1115            {
1116                return eConnectionStatusTimedOut;
1117            }
1118            else if (num_set_fds > 0)
1119            {
1120                if (fds[0].revents & POLLIN)
1121                    return eConnectionStatusSuccess;
1122                if (fds[1].revents & POLLIN)
1123                {
1124                    // We got a command to exit.  Read the data from that pipe:
1125                    char buffer[16];
1126                    ssize_t bytes_read;
1127
1128                    do
1129                    {
1130                        bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
1131                    } while (bytes_read < 0 && errno == EINTR);
1132                    assert (bytes_read == 1 && buffer[0] == 'q');
1133
1134                    if (log)
1135                        log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
1136                                    this, (int) bytes_read, buffer);
1137
1138                    return eConnectionStatusEndOfFile;
1139                }
1140            }
1141        }
1142    }
1143    if (error_ptr)
1144        error_ptr->SetErrorString("not connected");
1145    return eConnectionStatusLostConnection;
1146}
1147
1148#endif
1149
1150ConnectionStatus
1151ConnectionFileDescriptor::Close (int& fd, FDType type, Error *error_ptr)
1152{
1153    if (error_ptr)
1154        error_ptr->Clear();
1155    bool success = true;
1156    // Avoid taking a lock if we can
1157    if (fd >= 0)
1158    {
1159        Mutex::Locker locker (m_mutex);
1160        // Check the FD after the lock is taken to ensure only one thread
1161        // can get into the close scope below
1162        if (fd >= 0)
1163        {
1164            Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1165            if (log)
1166                log->Printf ("%p ConnectionFileDescriptor::Close (fd = %i)", this,fd);
1167#if _WIN32
1168            if (type != eFDTypeFile)
1169              success = closesocket(fd) == 0;
1170            else
1171#endif
1172            success = ::close (fd) == 0;
1173            // A reference to a FD was passed in, set it to an invalid value
1174            fd = -1;
1175            if (!success && error_ptr)
1176            {
1177                // Only set the error if we have been asked to since something else
1178                // might have caused us to try and shut down the connection and may
1179                // have already set the error.
1180                error_ptr->SetErrorToErrno();
1181            }
1182        }
1183    }
1184    if (success)
1185        return eConnectionStatusSuccess;
1186    else
1187        return eConnectionStatusError;
1188}
1189
1190ConnectionStatus
1191ConnectionFileDescriptor::NamedSocketAccept (const char *socket_name, Error *error_ptr)
1192{
1193#ifndef LLDB_DISABLE_POSIX
1194    ConnectionStatus result = eConnectionStatusError;
1195    struct sockaddr_un saddr_un;
1196
1197    m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1198
1199    int listen_socket = ::socket (AF_UNIX, SOCK_STREAM, 0);
1200    if (listen_socket == -1)
1201    {
1202        if (error_ptr)
1203            error_ptr->SetErrorToErrno();
1204        return eConnectionStatusError;
1205    }
1206
1207    saddr_un.sun_family = AF_UNIX;
1208    ::strncpy(saddr_un.sun_path, socket_name, sizeof(saddr_un.sun_path) - 1);
1209    saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
1210#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
1211    saddr_un.sun_len = SUN_LEN (&saddr_un);
1212#endif
1213
1214    Host::Unlink (socket_name);
1215    if (::bind (listen_socket, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) == 0)
1216    {
1217        if (::listen (listen_socket, 5) == 0)
1218        {
1219            m_fd_send = m_fd_recv = ::accept (listen_socket, NULL, 0);
1220            if (m_fd_send > 0)
1221            {
1222                m_should_close_fd = true;
1223
1224                if (error_ptr)
1225                    error_ptr->Clear();
1226                result = eConnectionStatusSuccess;
1227            }
1228        }
1229    }
1230
1231    if (result != eConnectionStatusSuccess)
1232    {
1233        if (error_ptr)
1234            error_ptr->SetErrorToErrno();
1235    }
1236    // We are done with the listen port
1237    Close (listen_socket, eFDTypeSocket, NULL);
1238    return result;
1239#else
1240    return eConnectionStatusError;
1241#endif
1242}
1243
1244ConnectionStatus
1245ConnectionFileDescriptor::NamedSocketConnect (const char *socket_name, Error *error_ptr)
1246{
1247#ifndef LLDB_DISABLE_POSIX
1248    Disconnect (NULL);
1249    m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1250
1251    // Open the socket that was passed in as an option
1252    struct sockaddr_un saddr_un;
1253    m_fd_send = m_fd_recv = ::socket (AF_UNIX, SOCK_STREAM, 0);
1254    if (m_fd_send == -1)
1255    {
1256        if (error_ptr)
1257            error_ptr->SetErrorToErrno();
1258        return eConnectionStatusError;
1259    }
1260
1261    saddr_un.sun_family = AF_UNIX;
1262    ::strncpy(saddr_un.sun_path, socket_name, sizeof(saddr_un.sun_path) - 1);
1263    saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
1264#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
1265    saddr_un.sun_len = SUN_LEN (&saddr_un);
1266#endif
1267
1268    if (::connect (m_fd_send, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) < 0)
1269    {
1270        if (error_ptr)
1271            error_ptr->SetErrorToErrno();
1272        Disconnect (NULL);
1273        return eConnectionStatusError;
1274    }
1275    if (error_ptr)
1276        error_ptr->Clear();
1277    return eConnectionStatusSuccess;
1278#else
1279    return eConnectionStatusError;
1280#endif
1281}
1282
1283ConnectionStatus
1284ConnectionFileDescriptor::SocketListen (uint16_t listen_port_num, Error *error_ptr)
1285{
1286    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1287    if (log)
1288        log->Printf ("%p ConnectionFileDescriptor::SocketListen (port = %i)", this, listen_port_num);
1289
1290    Disconnect (NULL);
1291    m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1292    int listen_port = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1293    if (listen_port == -1)
1294    {
1295        if (error_ptr)
1296            error_ptr->SetErrorToErrno();
1297        return eConnectionStatusError;
1298    }
1299
1300    // enable local address reuse
1301    SetSocketOption (listen_port, SOL_SOCKET, SO_REUSEADDR, 1);
1302
1303    SocketAddress localhost;
1304    if (localhost.SetToLocalhost (AF_INET, listen_port_num))
1305    {
1306        int err = ::bind (listen_port, localhost, localhost.GetLength());
1307        if (err == -1)
1308        {
1309            if (error_ptr)
1310                error_ptr->SetErrorToErrno();
1311            Close (listen_port, eFDTypeSocket, NULL);
1312            return eConnectionStatusError;
1313        }
1314
1315        err = ::listen (listen_port, 1);
1316        if (err == -1)
1317        {
1318            if (error_ptr)
1319                error_ptr->SetErrorToErrno();
1320            Close (listen_port, eFDTypeSocket, NULL);
1321            return eConnectionStatusError;
1322        }
1323
1324        m_fd_send = m_fd_recv = ::accept (listen_port, NULL, 0);
1325        if (m_fd_send == -1)
1326        {
1327            if (error_ptr)
1328                error_ptr->SetErrorToErrno();
1329            Close (listen_port, eFDTypeSocket, NULL);
1330            return eConnectionStatusError;
1331        }
1332    }
1333
1334    // We are done with the listen port
1335    Close (listen_port, eFDTypeSocket, NULL);
1336
1337    m_should_close_fd = true;
1338
1339    // Keep our TCP packets coming without any delays.
1340    SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1);
1341    if (error_ptr)
1342        error_ptr->Clear();
1343    return eConnectionStatusSuccess;
1344}
1345
1346ConnectionStatus
1347ConnectionFileDescriptor::ConnectTCP (const char *host_and_port, Error *error_ptr)
1348{
1349    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1350    if (log)
1351        log->Printf ("%p ConnectionFileDescriptor::ConnectTCP (host/port = %s)", this, host_and_port);
1352    Disconnect (NULL);
1353
1354    m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
1355    std::string host_str;
1356    std::string port_str;
1357    int32_t port = INT32_MIN;
1358    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr))
1359        return eConnectionStatusError;
1360
1361    // Create the socket
1362    m_fd_send = m_fd_recv = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1363    if (m_fd_send == -1)
1364    {
1365        if (error_ptr)
1366            error_ptr->SetErrorToErrno();
1367        return eConnectionStatusError;
1368    }
1369
1370    m_should_close_fd = true;
1371
1372    // Enable local address reuse
1373    SetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, 1);
1374
1375    struct sockaddr_in sa;
1376    ::memset (&sa, 0, sizeof (sa));
1377    sa.sin_family = AF_INET;
1378    sa.sin_port = htons (port);
1379
1380    int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
1381
1382    if (inet_pton_result <= 0)
1383    {
1384        struct hostent *host_entry = gethostbyname (host_str.c_str());
1385        if (host_entry)
1386            host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
1387        inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
1388        if (inet_pton_result <= 0)
1389        {
1390
1391            if (error_ptr)
1392            {
1393                if (inet_pton_result == -1)
1394                    error_ptr->SetErrorToErrno();
1395                else
1396                    error_ptr->SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str());
1397            }
1398            Disconnect (NULL);
1399
1400            return eConnectionStatusError;
1401        }
1402    }
1403
1404    if (-1 == ::connect (m_fd_send, (const struct sockaddr *)&sa, sizeof(sa)))
1405    {
1406        if (error_ptr)
1407            error_ptr->SetErrorToErrno();
1408        Disconnect (NULL);
1409
1410        return eConnectionStatusError;
1411    }
1412
1413    // Keep our TCP packets coming without any delays.
1414    SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1);
1415    if (error_ptr)
1416        error_ptr->Clear();
1417    return eConnectionStatusSuccess;
1418}
1419
1420ConnectionStatus
1421ConnectionFileDescriptor::ConnectUDP (const char *host_and_port, Error *error_ptr)
1422{
1423    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
1424    if (log)
1425        log->Printf ("%p ConnectionFileDescriptor::ConnectUDP (host/port = %s)", this, host_and_port);
1426    Disconnect (NULL);
1427
1428    m_fd_send_type = m_fd_recv_type = eFDTypeSocketUDP;
1429
1430    std::string host_str;
1431    std::string port_str;
1432    int32_t port = INT32_MIN;
1433    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr))
1434        return eConnectionStatusError;
1435
1436    // Setup the receiving end of the UDP connection on this localhost
1437    // on port zero. After we bind to port zero we can read the port.
1438    m_fd_recv = ::socket (AF_INET, SOCK_DGRAM, 0);
1439    if (m_fd_recv == -1)
1440    {
1441        // Socket creation failed...
1442        if (error_ptr)
1443            error_ptr->SetErrorToErrno();
1444    }
1445    else
1446    {
1447        // Socket was created, now lets bind to the requested port
1448        SocketAddress addr;
1449        addr.SetToLocalhost (AF_INET, 0);
1450
1451        if (::bind (m_fd_recv, addr, addr.GetLength()) == -1)
1452        {
1453            // Bind failed...
1454            if (error_ptr)
1455                error_ptr->SetErrorToErrno();
1456            Disconnect (NULL);
1457        }
1458    }
1459
1460    if (m_fd_recv == -1)
1461        return eConnectionStatusError;
1462
1463    // At this point we have setup the recieve port, now we need to
1464    // setup the UDP send socket
1465
1466    struct addrinfo hints;
1467    struct addrinfo *service_info_list = NULL;
1468
1469    ::memset (&hints, 0, sizeof(hints));
1470    hints.ai_family = AF_INET;
1471    hints.ai_socktype = SOCK_DGRAM;
1472    int err = ::getaddrinfo (host_str.c_str(), port_str.c_str(), &hints, &service_info_list);
1473    if (err != 0)
1474    {
1475        if (error_ptr)
1476            error_ptr->SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)",
1477                                                host_str.c_str(),
1478                                                port_str.c_str(),
1479                                                err,
1480                                                gai_strerror(err));
1481        Disconnect (NULL);
1482        return eConnectionStatusError;
1483    }
1484
1485    for (struct addrinfo *service_info_ptr = service_info_list;
1486         service_info_ptr != NULL;
1487         service_info_ptr = service_info_ptr->ai_next)
1488    {
1489        m_fd_send = ::socket (service_info_ptr->ai_family,
1490                              service_info_ptr->ai_socktype,
1491                              service_info_ptr->ai_protocol);
1492
1493        if (m_fd_send != -1)
1494        {
1495            *m_udp_send_sockaddr = service_info_ptr;
1496            break;
1497        }
1498        else
1499            continue;
1500    }
1501
1502    :: freeaddrinfo (service_info_list);
1503
1504    if (m_fd_send == -1)
1505    {
1506        Disconnect (NULL);
1507        return eConnectionStatusError;
1508    }
1509
1510    if (error_ptr)
1511        error_ptr->Clear();
1512
1513    m_should_close_fd = true;
1514    return eConnectionStatusSuccess;
1515}
1516
1517#if defined(_WIN32)
1518typedef const char * set_socket_option_arg_type;
1519typedef char * get_socket_option_arg_type;
1520#else // #if defined(_WIN32)
1521typedef const void * set_socket_option_arg_type;
1522typedef void * get_socket_option_arg_type;
1523#endif // #if defined(_WIN32)
1524
1525int
1526ConnectionFileDescriptor::GetSocketOption(int fd, int level, int option_name, int &option_value)
1527{
1528    get_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
1529    socklen_t option_value_size = sizeof(int);
1530	return ::getsockopt(fd, level, option_name, option_value_p, &option_value_size);
1531}
1532
1533int
1534ConnectionFileDescriptor::SetSocketOption(int fd, int level, int option_name, int option_value)
1535{
1536    set_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
1537	return ::setsockopt(fd, level, option_name, option_value_p, sizeof(option_value));
1538}
1539
1540bool
1541ConnectionFileDescriptor::SetSocketReceiveTimeout (uint32_t timeout_usec)
1542{
1543    switch (m_fd_recv_type)
1544    {
1545        case eFDTypeFile:       // Other FD requireing read/write
1546            break;
1547
1548        case eFDTypeSocket:     // Socket requiring send/recv
1549        case eFDTypeSocketUDP:  // Unconnected UDP socket requiring sendto/recvfrom
1550        {
1551            // Check in case timeout for m_fd has already been set to this value
1552            if (timeout_usec == m_socket_timeout_usec)
1553                return true;
1554            //printf ("ConnectionFileDescriptor::SetSocketReceiveTimeout (timeout_usec = %u)\n", timeout_usec);
1555
1556            struct timeval timeout;
1557            if (timeout_usec == UINT32_MAX)
1558            {
1559                timeout.tv_sec = 0;
1560                timeout.tv_usec = 0;
1561            }
1562            else if (timeout_usec == 0)
1563            {
1564                // Sending in zero does an infinite timeout, so set this as low
1565                // as we can go to get an effective zero timeout...
1566                timeout.tv_sec = 0;
1567                timeout.tv_usec = 1;
1568            }
1569            else
1570            {
1571                timeout.tv_sec = timeout_usec / TimeValue::MicroSecPerSec;
1572                timeout.tv_usec = timeout_usec % TimeValue::MicroSecPerSec;
1573            }
1574            if (::setsockopt (m_fd_recv, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<get_socket_option_arg_type>(&timeout), sizeof(timeout)) == 0)
1575            {
1576                m_socket_timeout_usec = timeout_usec;
1577                return true;
1578            }
1579        }
1580    }
1581    return false;
1582}
1583
1584in_port_t
1585ConnectionFileDescriptor::GetSocketPort (int fd)
1586{
1587    // We bound to port zero, so we need to figure out which port we actually bound to
1588    SocketAddress sock_addr;
1589    socklen_t sock_addr_len = sock_addr.GetMaxLength ();
1590    if (::getsockname (fd, sock_addr, &sock_addr_len) == 0)
1591        return sock_addr.GetPort ();
1592
1593    return 0;
1594}
1595
1596// If the read file descriptor is a socket, then return
1597// the port number that is being used by the socket.
1598in_port_t
1599ConnectionFileDescriptor::GetReadPort () const
1600{
1601    return ConnectionFileDescriptor::GetSocketPort (m_fd_recv);
1602}
1603
1604// If the write file descriptor is a socket, then return
1605// the port number that is being used by the socket.
1606in_port_t
1607ConnectionFileDescriptor::GetWritePort () const
1608{
1609    return ConnectionFileDescriptor::GetSocketPort (m_fd_send);
1610}
1611
1612
1613