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