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