1 //===-- ConnectionFileDescriptorPosix.cpp ---------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #if defined(__APPLE__)
10 // Enable this special support for Apple builds where we can have unlimited
11 // select bounds. We tried switching to poll() and kqueue and we were panicing
12 // the kernel, so we have to stick with select for now.
13 #define _DARWIN_UNLIMITED_SELECT
14 #endif
15 
16 #include "lldb/Host/Config.h"
17 #include "lldb/Host/Socket.h"
18 #include "lldb/Host/SocketAddress.h"
19 #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
20 #include "lldb/Utility/SelectHelper.h"
21 #include "lldb/Utility/Timeout.h"
22 
23 #include <cerrno>
24 #include <cstdlib>
25 #include <cstring>
26 #include <fcntl.h>
27 #include <sys/types.h>
28 
29 #if LLDB_ENABLE_POSIX
30 #include <termios.h>
31 #include <unistd.h>
32 #endif
33 
34 #include <memory>
35 #include <sstream>
36 
37 #include "llvm/Support/Errno.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #if defined(__APPLE__)
40 #include "llvm/ADT/SmallVector.h"
41 #endif
42 #include "lldb/Host/Host.h"
43 #include "lldb/Host/Socket.h"
44 #include "lldb/Host/common/TCPSocket.h"
45 #include "lldb/Host/common/UDPSocket.h"
46 #include "lldb/Utility/Log.h"
47 #include "lldb/Utility/StreamString.h"
48 #include "lldb/Utility/Timer.h"
49 
50 using namespace lldb;
51 using namespace lldb_private;
52 
53 ConnectionFileDescriptor::ConnectionFileDescriptor(bool child_processes_inherit)
54     : Connection(), m_pipe(), m_mutex(), m_shutting_down(false),
55 
56       m_child_processes_inherit(child_processes_inherit) {
57   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION |
58                                                   LIBLLDB_LOG_OBJECT));
59   LLDB_LOGF(log, "%p ConnectionFileDescriptor::ConnectionFileDescriptor ()",
60             static_cast<void *>(this));
61 }
62 
63 ConnectionFileDescriptor::ConnectionFileDescriptor(int fd, bool owns_fd)
64     : Connection(), m_pipe(), m_mutex(), m_shutting_down(false),
65       m_child_processes_inherit(false) {
66   m_io_sp =
67       std::make_shared<NativeFile>(fd, File::eOpenOptionReadWrite, owns_fd);
68 
69   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION |
70                                                   LIBLLDB_LOG_OBJECT));
71   LLDB_LOGF(log,
72             "%p ConnectionFileDescriptor::ConnectionFileDescriptor (fd = "
73             "%i, owns_fd = %i)",
74             static_cast<void *>(this), fd, owns_fd);
75   OpenCommandPipe();
76 }
77 
78 ConnectionFileDescriptor::ConnectionFileDescriptor(Socket *socket)
79     : Connection(), m_pipe(), m_mutex(), m_shutting_down(false),
80       m_child_processes_inherit(false) {
81   InitializeSocket(socket);
82 }
83 
84 ConnectionFileDescriptor::~ConnectionFileDescriptor() {
85   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION |
86                                                   LIBLLDB_LOG_OBJECT));
87   LLDB_LOGF(log, "%p ConnectionFileDescriptor::~ConnectionFileDescriptor ()",
88             static_cast<void *>(this));
89   Disconnect(nullptr);
90   CloseCommandPipe();
91 }
92 
93 void ConnectionFileDescriptor::OpenCommandPipe() {
94   CloseCommandPipe();
95 
96   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
97   // Make the command file descriptor here:
98   Status result = m_pipe.CreateNew(m_child_processes_inherit);
99   if (!result.Success()) {
100     LLDB_LOGF(log,
101               "%p ConnectionFileDescriptor::OpenCommandPipe () - could not "
102               "make pipe: %s",
103               static_cast<void *>(this), result.AsCString());
104   } else {
105     LLDB_LOGF(log,
106               "%p ConnectionFileDescriptor::OpenCommandPipe() - success "
107               "readfd=%d writefd=%d",
108               static_cast<void *>(this), m_pipe.GetReadFileDescriptor(),
109               m_pipe.GetWriteFileDescriptor());
110   }
111 }
112 
113 void ConnectionFileDescriptor::CloseCommandPipe() {
114   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
115   LLDB_LOGF(log, "%p ConnectionFileDescriptor::CloseCommandPipe()",
116             static_cast<void *>(this));
117 
118   m_pipe.Close();
119 }
120 
121 bool ConnectionFileDescriptor::IsConnected() const {
122   return m_io_sp && m_io_sp->IsValid();
123 }
124 
125 ConnectionStatus ConnectionFileDescriptor::Connect(llvm::StringRef path,
126                                                    Status *error_ptr) {
127   return Connect(path, nullptr, error_ptr);
128 }
129 
130 ConnectionStatus
131 ConnectionFileDescriptor::Connect(llvm::StringRef path,
132                                   socket_id_callback_type socket_id_callback,
133                                   Status *error_ptr) {
134   std::lock_guard<std::recursive_mutex> guard(m_mutex);
135   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
136   LLDB_LOGF(log, "%p ConnectionFileDescriptor::Connect (url = '%s')",
137             static_cast<void *>(this), path.str().c_str());
138 
139   OpenCommandPipe();
140 
141   if (path.empty()) {
142     if (error_ptr)
143       error_ptr->SetErrorString("invalid connect arguments");
144     return eConnectionStatusError;
145   }
146 
147   llvm::StringRef scheme;
148   std::tie(scheme, path) = path.split("://");
149 
150   if (!path.empty()) {
151     auto method =
152         llvm::StringSwitch<ConnectionStatus (ConnectionFileDescriptor::*)(
153             llvm::StringRef, socket_id_callback_type, Status *)>(scheme)
154             .Case("listen", &ConnectionFileDescriptor::SocketListenAndAccept)
155             .Cases("accept", "unix-accept",
156                    &ConnectionFileDescriptor::NamedSocketAccept)
157             .Case("unix-abstract-accept",
158                   &ConnectionFileDescriptor::UnixAbstractSocketAccept)
159             .Cases("connect", "tcp-connect",
160                    &ConnectionFileDescriptor::ConnectTCP)
161             .Case("udp", &ConnectionFileDescriptor::ConnectUDP)
162             .Case("unix-connect", &ConnectionFileDescriptor::NamedSocketConnect)
163             .Case("unix-abstract-connect",
164                   &ConnectionFileDescriptor::UnixAbstractSocketConnect)
165 #if LLDB_ENABLE_POSIX
166             .Case("fd", &ConnectionFileDescriptor::ConnectFD)
167             .Case("file", &ConnectionFileDescriptor::ConnectFile)
168             .Case("serial", &ConnectionFileDescriptor::ConnectSerialPort)
169 #endif
170             .Default(nullptr);
171 
172     if (method)
173       return (this->*method)(path, socket_id_callback, error_ptr);
174   }
175 
176   if (error_ptr)
177     error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'",
178                                         path.str().c_str());
179   return eConnectionStatusError;
180 }
181 
182 bool ConnectionFileDescriptor::InterruptRead() {
183   size_t bytes_written = 0;
184   Status result = m_pipe.Write("i", 1, bytes_written);
185   return result.Success();
186 }
187 
188 ConnectionStatus ConnectionFileDescriptor::Disconnect(Status *error_ptr) {
189   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
190   LLDB_LOGF(log, "%p ConnectionFileDescriptor::Disconnect ()",
191             static_cast<void *>(this));
192 
193   ConnectionStatus status = eConnectionStatusSuccess;
194 
195   if (!IsConnected()) {
196     LLDB_LOGF(
197         log, "%p ConnectionFileDescriptor::Disconnect(): Nothing to disconnect",
198         static_cast<void *>(this));
199     return eConnectionStatusSuccess;
200   }
201 
202   if (m_io_sp->GetFdType() == IOObject::eFDTypeSocket)
203     static_cast<Socket &>(*m_io_sp).PreDisconnect();
204 
205   // Try to get the ConnectionFileDescriptor's mutex.  If we fail, that is
206   // quite likely because somebody is doing a blocking read on our file
207   // descriptor.  If that's the case, then send the "q" char to the command
208   // file channel so the read will wake up and the connection will then know to
209   // shut down.
210   std::unique_lock<std::recursive_mutex> locker(m_mutex, std::defer_lock);
211   if (!locker.try_lock()) {
212     if (m_pipe.CanWrite()) {
213       size_t bytes_written = 0;
214       Status result = m_pipe.Write("q", 1, bytes_written);
215       LLDB_LOGF(log,
216                 "%p ConnectionFileDescriptor::Disconnect(): Couldn't get "
217                 "the lock, sent 'q' to %d, error = '%s'.",
218                 static_cast<void *>(this), m_pipe.GetWriteFileDescriptor(),
219                 result.AsCString());
220     } else if (log) {
221       LLDB_LOGF(log,
222                 "%p ConnectionFileDescriptor::Disconnect(): Couldn't get the "
223                 "lock, but no command pipe is available.",
224                 static_cast<void *>(this));
225     }
226     locker.lock();
227   }
228 
229   // Prevents reads and writes during shutdown.
230   m_shutting_down = true;
231 
232   Status error = m_io_sp->Close();
233   if (error.Fail())
234     status = eConnectionStatusError;
235   if (error_ptr)
236     *error_ptr = error;
237 
238   // Close any pipes we were using for async interrupts
239   m_pipe.Close();
240 
241   m_uri.clear();
242   m_shutting_down = false;
243   return status;
244 }
245 
246 size_t ConnectionFileDescriptor::Read(void *dst, size_t dst_len,
247                                       const Timeout<std::micro> &timeout,
248                                       ConnectionStatus &status,
249                                       Status *error_ptr) {
250   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
251 
252   std::unique_lock<std::recursive_mutex> locker(m_mutex, std::defer_lock);
253   if (!locker.try_lock()) {
254     LLDB_LOGF(log,
255               "%p ConnectionFileDescriptor::Read () failed to get the "
256               "connection lock.",
257               static_cast<void *>(this));
258     if (error_ptr)
259       error_ptr->SetErrorString("failed to get the connection lock for read.");
260 
261     status = eConnectionStatusTimedOut;
262     return 0;
263   }
264 
265   if (m_shutting_down) {
266     if (error_ptr)
267       error_ptr->SetErrorString("shutting down");
268     status = eConnectionStatusError;
269     return 0;
270   }
271 
272   status = BytesAvailable(timeout, error_ptr);
273   if (status != eConnectionStatusSuccess)
274     return 0;
275 
276   Status error;
277   size_t bytes_read = dst_len;
278   error = m_io_sp->Read(dst, bytes_read);
279 
280   if (log) {
281     LLDB_LOGF(log,
282               "%p ConnectionFileDescriptor::Read()  fd = %" PRIu64
283               ", dst = %p, dst_len = %" PRIu64 ") => %" PRIu64 ", error = %s",
284               static_cast<void *>(this),
285               static_cast<uint64_t>(m_io_sp->GetWaitableHandle()),
286               static_cast<void *>(dst), static_cast<uint64_t>(dst_len),
287               static_cast<uint64_t>(bytes_read), error.AsCString());
288   }
289 
290   if (bytes_read == 0) {
291     error.Clear(); // End-of-file.  Do not automatically close; pass along for
292                    // the end-of-file handlers.
293     status = eConnectionStatusEndOfFile;
294   }
295 
296   if (error_ptr)
297     *error_ptr = error;
298 
299   if (error.Fail()) {
300     uint32_t error_value = error.GetError();
301     switch (error_value) {
302     case EAGAIN: // The file was marked for non-blocking I/O, and no data were
303                  // ready to be read.
304       if (m_io_sp->GetFdType() == IOObject::eFDTypeSocket)
305         status = eConnectionStatusTimedOut;
306       else
307         status = eConnectionStatusSuccess;
308       return 0;
309 
310     case EFAULT:  // Buf points outside the allocated address space.
311     case EINTR:   // A read from a slow device was interrupted before any data
312                   // arrived by the delivery of a signal.
313     case EINVAL:  // The pointer associated with fildes was negative.
314     case EIO:     // An I/O error occurred while reading from the file system.
315                   // The process group is orphaned.
316                   // The file is a regular file, nbyte is greater than 0, the
317                   // starting position is before the end-of-file, and the
318                   // starting position is greater than or equal to the offset
319                   // maximum established for the open file descriptor
320                   // associated with fildes.
321     case EISDIR:  // An attempt is made to read a directory.
322     case ENOBUFS: // An attempt to allocate a memory buffer fails.
323     case ENOMEM:  // Insufficient memory is available.
324       status = eConnectionStatusError;
325       break; // Break to close....
326 
327     case ENOENT:     // no such file or directory
328     case EBADF:      // fildes is not a valid file or socket descriptor open for
329                      // reading.
330     case ENXIO:      // An action is requested of a device that does not exist..
331                      // A requested action cannot be performed by the device.
332     case ECONNRESET: // The connection is closed by the peer during a read
333                      // attempt on a socket.
334     case ENOTCONN:   // A read is attempted on an unconnected socket.
335       status = eConnectionStatusLostConnection;
336       break; // Break to close....
337 
338     case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a
339                     // socket.
340       status = eConnectionStatusTimedOut;
341       return 0;
342 
343     default:
344       LLDB_LOG(log, "this = {0}, unexpected error: {1}", this,
345                llvm::sys::StrError(error_value));
346       status = eConnectionStatusError;
347       break; // Break to close....
348     }
349 
350     return 0;
351   }
352   return bytes_read;
353 }
354 
355 size_t ConnectionFileDescriptor::Write(const void *src, size_t src_len,
356                                        ConnectionStatus &status,
357                                        Status *error_ptr) {
358   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
359   LLDB_LOGF(log,
360             "%p ConnectionFileDescriptor::Write (src = %p, src_len = %" PRIu64
361             ")",
362             static_cast<void *>(this), static_cast<const void *>(src),
363             static_cast<uint64_t>(src_len));
364 
365   if (!IsConnected()) {
366     if (error_ptr)
367       error_ptr->SetErrorString("not connected");
368     status = eConnectionStatusNoConnection;
369     return 0;
370   }
371 
372   if (m_shutting_down) {
373     if (error_ptr)
374       error_ptr->SetErrorString("shutting down");
375     status = eConnectionStatusError;
376     return 0;
377   }
378 
379   Status error;
380 
381   size_t bytes_sent = src_len;
382   error = m_io_sp->Write(src, bytes_sent);
383 
384   if (log) {
385     LLDB_LOGF(log,
386               "%p ConnectionFileDescriptor::Write(fd = %" PRIu64
387               ", src = %p, src_len = %" PRIu64 ") => %" PRIu64 " (error = %s)",
388               static_cast<void *>(this),
389               static_cast<uint64_t>(m_io_sp->GetWaitableHandle()),
390               static_cast<const void *>(src), static_cast<uint64_t>(src_len),
391               static_cast<uint64_t>(bytes_sent), error.AsCString());
392   }
393 
394   if (error_ptr)
395     *error_ptr = error;
396 
397   if (error.Fail()) {
398     switch (error.GetError()) {
399     case EAGAIN:
400     case EINTR:
401       status = eConnectionStatusSuccess;
402       return 0;
403 
404     case ECONNRESET: // The connection is closed by the peer during a read
405                      // attempt on a socket.
406     case ENOTCONN:   // A read is attempted on an unconnected socket.
407       status = eConnectionStatusLostConnection;
408       break; // Break to close....
409 
410     default:
411       status = eConnectionStatusError;
412       break; // Break to close....
413     }
414 
415     return 0;
416   }
417 
418   status = eConnectionStatusSuccess;
419   return bytes_sent;
420 }
421 
422 std::string ConnectionFileDescriptor::GetURI() { return m_uri; }
423 
424 // This ConnectionFileDescriptor::BytesAvailable() uses select() via
425 // SelectHelper
426 //
427 // PROS:
428 //  - select is consistent across most unix platforms
429 //  - The Apple specific version allows for unlimited fds in the fd_sets by
430 //    setting the _DARWIN_UNLIMITED_SELECT define prior to including the
431 //    required header files.
432 // CONS:
433 //  - on non-Apple platforms, only supports file descriptors up to FD_SETSIZE.
434 //     This implementation  will assert if it runs into that hard limit to let
435 //     users know that another ConnectionFileDescriptor::BytesAvailable() should
436 //     be used or a new version of ConnectionFileDescriptor::BytesAvailable()
437 //     should be written for the system that is running into the limitations.
438 
439 ConnectionStatus
440 ConnectionFileDescriptor::BytesAvailable(const Timeout<std::micro> &timeout,
441                                          Status *error_ptr) {
442   // Don't need to take the mutex here separately since we are only called from
443   // Read.  If we ever get used more generally we will need to lock here as
444   // well.
445 
446   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_CONNECTION));
447   LLDB_LOG(log, "this = {0}, timeout = {1}", this, timeout);
448 
449   // Make a copy of the file descriptors to make sure we don't have another
450   // thread change these values out from under us and cause problems in the
451   // loop below where like in FS_SET()
452   const IOObject::WaitableHandle handle = m_io_sp->GetWaitableHandle();
453   const int pipe_fd = m_pipe.GetReadFileDescriptor();
454 
455   if (handle != IOObject::kInvalidHandleValue) {
456     SelectHelper select_helper;
457     if (timeout)
458       select_helper.SetTimeout(*timeout);
459 
460     select_helper.FDSetRead(handle);
461 #if defined(_WIN32)
462     // select() won't accept pipes on Windows.  The entire Windows codepath
463     // needs to be converted over to using WaitForMultipleObjects and event
464     // HANDLEs, but for now at least this will allow ::select() to not return
465     // an error.
466     const bool have_pipe_fd = false;
467 #else
468     const bool have_pipe_fd = pipe_fd >= 0;
469 #endif
470     if (have_pipe_fd)
471       select_helper.FDSetRead(pipe_fd);
472 
473     while (handle == m_io_sp->GetWaitableHandle()) {
474 
475       Status error = select_helper.Select();
476 
477       if (error_ptr)
478         *error_ptr = error;
479 
480       if (error.Fail()) {
481         switch (error.GetError()) {
482         case EBADF: // One of the descriptor sets specified an invalid
483                     // descriptor.
484           return eConnectionStatusLostConnection;
485 
486         case EINVAL: // The specified time limit is invalid. One of its
487                      // components is negative or too large.
488         default:     // Other unknown error
489           return eConnectionStatusError;
490 
491         case ETIMEDOUT:
492           return eConnectionStatusTimedOut;
493 
494         case EAGAIN: // The kernel was (perhaps temporarily) unable to
495                      // allocate the requested number of file descriptors, or
496                      // we have non-blocking IO
497         case EINTR:  // A signal was delivered before the time limit
498           // expired and before any of the selected events occurred.
499           break; // Lets keep reading to until we timeout
500         }
501       } else {
502         if (select_helper.FDIsSetRead(handle))
503           return eConnectionStatusSuccess;
504 
505         if (select_helper.FDIsSetRead(pipe_fd)) {
506           // There is an interrupt or exit command in the command pipe Read the
507           // data from that pipe:
508           char c;
509 
510           ssize_t bytes_read =
511               llvm::sys::RetryAfterSignal(-1, ::read, pipe_fd, &c, 1);
512           assert(bytes_read == 1);
513           (void)bytes_read;
514           switch (c) {
515           case 'q':
516             LLDB_LOGF(log,
517                       "%p ConnectionFileDescriptor::BytesAvailable() "
518                       "got data: %c from the command channel.",
519                       static_cast<void *>(this), c);
520             return eConnectionStatusEndOfFile;
521           case 'i':
522             // Interrupt the current read
523             return eConnectionStatusInterrupted;
524           }
525         }
526       }
527     }
528   }
529 
530   if (error_ptr)
531     error_ptr->SetErrorString("not connected");
532   return eConnectionStatusLostConnection;
533 }
534 
535 ConnectionStatus ConnectionFileDescriptor::NamedSocketAccept(
536     llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,
537     Status *error_ptr) {
538   Status error;
539   std::unique_ptr<Socket> listen_socket = Socket::Create(
540       Socket::ProtocolUnixDomain, m_child_processes_inherit, error);
541   Socket *socket = nullptr;
542 
543   if (!error.Fail())
544     error = listen_socket->Listen(socket_name, 5);
545 
546   if (!error.Fail()) {
547     socket_id_callback(socket_name);
548     error = listen_socket->Accept(socket);
549   }
550 
551   if (!error.Fail()) {
552     m_io_sp.reset(socket);
553     m_uri.assign(socket_name.str());
554     return eConnectionStatusSuccess;
555   }
556 
557   if (error_ptr)
558     *error_ptr = error;
559   return eConnectionStatusError;
560 }
561 
562 ConnectionStatus ConnectionFileDescriptor::NamedSocketConnect(
563     llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,
564     Status *error_ptr) {
565   Socket *socket = nullptr;
566   Status error =
567       Socket::UnixDomainConnect(socket_name, m_child_processes_inherit, socket);
568   if (error_ptr)
569     *error_ptr = error;
570   m_io_sp.reset(socket);
571   if (error.Fail())
572     return eConnectionStatusError;
573   m_uri.assign(std::string(socket_name));
574   return eConnectionStatusSuccess;
575 }
576 
577 ConnectionStatus ConnectionFileDescriptor::UnixAbstractSocketAccept(
578     llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,
579     Status *error_ptr) {
580   Status error;
581   std::unique_ptr<Socket> listen_socket = Socket::Create(
582       Socket::ProtocolUnixAbstract, m_child_processes_inherit, error);
583   Socket *socket = nullptr;
584 
585   if (!error.Fail())
586     error = listen_socket->Listen(socket_name, 5);
587 
588   if (!error.Fail())
589     socket_id_callback(socket_name);
590 
591   if (!error.Fail())
592     error = listen_socket->Accept(socket);
593 
594   if (!error.Fail()) {
595     m_io_sp.reset(socket);
596     m_uri.assign(socket_name.str());
597     return eConnectionStatusSuccess;
598   }
599 
600   if (error_ptr)
601     *error_ptr = error;
602   return eConnectionStatusError;
603 }
604 
605 lldb::ConnectionStatus ConnectionFileDescriptor::UnixAbstractSocketConnect(
606     llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,
607     Status *error_ptr) {
608   Socket *socket = nullptr;
609   Status error = Socket::UnixAbstractConnect(socket_name,
610                                              m_child_processes_inherit, socket);
611   if (error_ptr)
612     *error_ptr = error;
613   m_io_sp.reset(socket);
614   if (error.Fail())
615     return eConnectionStatusError;
616   m_uri.assign(std::string(socket_name));
617   return eConnectionStatusSuccess;
618 }
619 
620 ConnectionStatus ConnectionFileDescriptor::SocketListenAndAccept(
621     llvm::StringRef s, socket_id_callback_type socket_id_callback,
622     Status *error_ptr) {
623   if (error_ptr)
624     *error_ptr = Status();
625 
626   llvm::Expected<std::unique_ptr<TCPSocket>> listening_socket =
627       Socket::TcpListen(s, m_child_processes_inherit);
628   if (!listening_socket) {
629     if (error_ptr)
630       *error_ptr = listening_socket.takeError();
631     else
632       LLDB_LOG_ERROR(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION),
633                      listening_socket.takeError(), "tcp listen failed: {0}");
634     return eConnectionStatusError;
635   }
636 
637   uint16_t port = listening_socket.get()->GetLocalPortNumber();
638   socket_id_callback(std::to_string(port));
639 
640   Socket *accepted_socket;
641   Status error = listening_socket.get()->Accept(accepted_socket);
642   if (error_ptr)
643     *error_ptr = error;
644   if (error.Fail())
645     return eConnectionStatusError;
646 
647   InitializeSocket(accepted_socket);
648   return eConnectionStatusSuccess;
649 }
650 
651 ConnectionStatus
652 ConnectionFileDescriptor::ConnectTCP(llvm::StringRef s,
653                                      socket_id_callback_type socket_id_callback,
654                                      Status *error_ptr) {
655   if (error_ptr)
656     *error_ptr = Status();
657 
658   llvm::Expected<std::unique_ptr<Socket>> socket =
659       Socket::TcpConnect(s, m_child_processes_inherit);
660   if (!socket) {
661     if (error_ptr)
662       *error_ptr = socket.takeError();
663     else
664       LLDB_LOG_ERROR(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION),
665                      socket.takeError(), "tcp connect failed: {0}");
666     return eConnectionStatusError;
667   }
668   m_io_sp = std::move(*socket);
669   m_uri.assign(std::string(s));
670   return eConnectionStatusSuccess;
671 }
672 
673 ConnectionStatus
674 ConnectionFileDescriptor::ConnectUDP(llvm::StringRef s,
675                                      socket_id_callback_type socket_id_callback,
676                                      Status *error_ptr) {
677   if (error_ptr)
678     *error_ptr = Status();
679   llvm::Expected<std::unique_ptr<UDPSocket>> socket =
680       Socket::UdpConnect(s, m_child_processes_inherit);
681   if (!socket) {
682     if (error_ptr)
683       *error_ptr = socket.takeError();
684     else
685       LLDB_LOG_ERROR(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION),
686                      socket.takeError(), "tcp connect failed: {0}");
687     return eConnectionStatusError;
688   }
689   m_io_sp = std::move(*socket);
690   m_uri.assign(std::string(s));
691   return eConnectionStatusSuccess;
692 }
693 
694 ConnectionStatus
695 ConnectionFileDescriptor::ConnectFD(llvm::StringRef s,
696                                     socket_id_callback_type socket_id_callback,
697                                     Status *error_ptr) {
698 #if LLDB_ENABLE_POSIX
699   // Just passing a native file descriptor within this current process that
700   // is already opened (possibly from a service or other source).
701   int fd = -1;
702 
703   if (!s.getAsInteger(0, fd)) {
704     // We have what looks to be a valid file descriptor, but we should make
705     // sure it is. We currently are doing this by trying to get the flags
706     // from the file descriptor and making sure it isn't a bad fd.
707     errno = 0;
708     int flags = ::fcntl(fd, F_GETFL, 0);
709     if (flags == -1 || errno == EBADF) {
710       if (error_ptr)
711         error_ptr->SetErrorStringWithFormat("stale file descriptor: %s",
712                                             s.str().c_str());
713       m_io_sp.reset();
714       return eConnectionStatusError;
715     } else {
716       // Don't take ownership of a file descriptor that gets passed to us
717       // since someone else opened the file descriptor and handed it to us.
718       // TODO: Since are using a URL to open connection we should
719       // eventually parse options using the web standard where we have
720       // "fd://123?opt1=value;opt2=value" and we can have an option be
721       // "owns=1" or "owns=0" or something like this to allow us to specify
722       // this. For now, we assume we must assume we don't own it.
723 
724       std::unique_ptr<TCPSocket> tcp_socket;
725       tcp_socket = std::make_unique<TCPSocket>(fd, false, false);
726       // Try and get a socket option from this file descriptor to see if
727       // this is a socket and set m_is_socket accordingly.
728       int resuse;
729       bool is_socket =
730           !!tcp_socket->GetOption(SOL_SOCKET, SO_REUSEADDR, resuse);
731       if (is_socket)
732         m_io_sp = std::move(tcp_socket);
733       else
734         m_io_sp =
735             std::make_shared<NativeFile>(fd, File::eOpenOptionReadWrite, false);
736       m_uri = s.str();
737       return eConnectionStatusSuccess;
738     }
739   }
740 
741   if (error_ptr)
742     error_ptr->SetErrorStringWithFormat("invalid file descriptor: \"%s\"",
743                                         s.str().c_str());
744   m_io_sp.reset();
745   return eConnectionStatusError;
746 #endif // LLDB_ENABLE_POSIX
747   llvm_unreachable("this function should be only called w/ LLDB_ENABLE_POSIX");
748 }
749 
750 ConnectionStatus ConnectionFileDescriptor::ConnectFile(
751     llvm::StringRef s, socket_id_callback_type socket_id_callback,
752     Status *error_ptr) {
753 #if LLDB_ENABLE_POSIX
754   std::string addr_str = s.str();
755   // file:///PATH
756   int fd = llvm::sys::RetryAfterSignal(-1, ::open, addr_str.c_str(), O_RDWR);
757   if (fd == -1) {
758     if (error_ptr)
759       error_ptr->SetErrorToErrno();
760     return eConnectionStatusError;
761   }
762 
763   if (::isatty(fd)) {
764     // Set up serial terminal emulation
765     struct termios options;
766     ::tcgetattr(fd, &options);
767 
768     // Set port speed to maximum
769     ::cfsetospeed(&options, B115200);
770     ::cfsetispeed(&options, B115200);
771 
772     // Raw input, disable echo and signals
773     options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
774 
775     // Make sure only one character is needed to return from a read
776     options.c_cc[VMIN] = 1;
777     options.c_cc[VTIME] = 0;
778 
779     llvm::sys::RetryAfterSignal(-1, ::tcsetattr, fd, TCSANOW, &options);
780   }
781 
782   m_io_sp = std::make_shared<NativeFile>(fd, File::eOpenOptionReadWrite, true);
783   return eConnectionStatusSuccess;
784 #endif // LLDB_ENABLE_POSIX
785   llvm_unreachable("this function should be only called w/ LLDB_ENABLE_POSIX");
786 }
787 
788 ConnectionStatus ConnectionFileDescriptor::ConnectSerialPort(
789     llvm::StringRef s, socket_id_callback_type socket_id_callback,
790     Status *error_ptr) {
791 #if LLDB_ENABLE_POSIX
792   llvm::StringRef path, qs;
793   // serial:///PATH?k1=v1&k2=v2...
794   std::tie(path, qs) = s.split('?');
795 
796   llvm::Expected<SerialPort::Options> serial_options =
797       SerialPort::OptionsFromURL(qs);
798   if (!serial_options) {
799     if (error_ptr)
800       *error_ptr = serial_options.takeError();
801     else
802       llvm::consumeError(serial_options.takeError());
803     return eConnectionStatusError;
804   }
805 
806   int fd = llvm::sys::RetryAfterSignal(-1, ::open, path.str().c_str(), O_RDWR);
807   if (fd == -1) {
808     if (error_ptr)
809       error_ptr->SetErrorToErrno();
810     return eConnectionStatusError;
811   }
812 
813   llvm::Expected<std::unique_ptr<SerialPort>> serial_sp = SerialPort::Create(
814       fd, File::eOpenOptionReadWrite, serial_options.get(), true);
815   if (!serial_sp) {
816     if (error_ptr)
817       *error_ptr = serial_sp.takeError();
818     else
819       llvm::consumeError(serial_sp.takeError());
820     return eConnectionStatusError;
821   }
822   m_io_sp = std::move(serial_sp.get());
823 
824   return eConnectionStatusSuccess;
825 #endif // LLDB_ENABLE_POSIX
826   llvm_unreachable("this function should be only called w/ LLDB_ENABLE_POSIX");
827 }
828 
829 bool ConnectionFileDescriptor::GetChildProcessesInherit() const {
830   return m_child_processes_inherit;
831 }
832 
833 void ConnectionFileDescriptor::SetChildProcessesInherit(
834     bool child_processes_inherit) {
835   m_child_processes_inherit = child_processes_inherit;
836 }
837 
838 void ConnectionFileDescriptor::InitializeSocket(Socket *socket) {
839   m_io_sp.reset(socket);
840   m_uri = socket->GetRemoteConnectionURI();
841 }
842