xref: /freebsd/contrib/llvm-project/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
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/FileSystem.h"
19 #include "lldb/Host/Socket.h"
20 #include "lldb/Host/SocketAddress.h"
21 #include "lldb/Utility/LLDBLog.h"
22 #include "lldb/Utility/SelectHelper.h"
23 #include "lldb/Utility/Timeout.h"
24 
25 #include <cerrno>
26 #include <cstdlib>
27 #include <cstring>
28 #include <fcntl.h>
29 #include <sys/types.h>
30 
31 #if LLDB_ENABLE_POSIX
32 #include <termios.h>
33 #include <unistd.h>
34 #endif
35 
36 #include <memory>
37 #include <sstream>
38 
39 #include "llvm/Support/Errno.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #if defined(__APPLE__)
42 #include "llvm/ADT/SmallVector.h"
43 #endif
44 #include "lldb/Host/Host.h"
45 #include "lldb/Host/Socket.h"
46 #include "lldb/Host/common/TCPSocket.h"
47 #include "lldb/Host/common/UDPSocket.h"
48 #include "lldb/Utility/Log.h"
49 #include "lldb/Utility/StreamString.h"
50 #include "lldb/Utility/Timer.h"
51 
52 using namespace lldb;
53 using namespace lldb_private;
54 
55 ConnectionFileDescriptor::ConnectionFileDescriptor(bool child_processes_inherit)
56     : Connection(), m_pipe(), m_mutex(), m_shutting_down(false),
57 
58       m_child_processes_inherit(child_processes_inherit) {
59   Log *log(GetLog(LLDBLog::Connection | LLDBLog::Object));
60   LLDB_LOGF(log, "%p ConnectionFileDescriptor::ConnectionFileDescriptor ()",
61             static_cast<void *>(this));
62 }
63 
64 ConnectionFileDescriptor::ConnectionFileDescriptor(int fd, bool owns_fd)
65     : Connection(), m_pipe(), m_mutex(), m_shutting_down(false),
66       m_child_processes_inherit(false) {
67   m_io_sp =
68       std::make_shared<NativeFile>(fd, File::eOpenOptionReadWrite, owns_fd);
69 
70   Log *log(GetLog(LLDBLog::Connection | LLDBLog::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(GetLog(LLDBLog::Connection | LLDBLog::Object));
86   LLDB_LOGF(log, "%p ConnectionFileDescriptor::~ConnectionFileDescriptor ()",
87             static_cast<void *>(this));
88   Disconnect(nullptr);
89   CloseCommandPipe();
90 }
91 
92 void ConnectionFileDescriptor::OpenCommandPipe() {
93   CloseCommandPipe();
94 
95   Log *log = GetLog(LLDBLog::Connection);
96   // Make the command file descriptor here:
97   Status result = m_pipe.CreateNew(m_child_processes_inherit);
98   if (!result.Success()) {
99     LLDB_LOGF(log,
100               "%p ConnectionFileDescriptor::OpenCommandPipe () - could not "
101               "make pipe: %s",
102               static_cast<void *>(this), result.AsCString());
103   } else {
104     LLDB_LOGF(log,
105               "%p ConnectionFileDescriptor::OpenCommandPipe() - success "
106               "readfd=%d writefd=%d",
107               static_cast<void *>(this), m_pipe.GetReadFileDescriptor(),
108               m_pipe.GetWriteFileDescriptor());
109   }
110 }
111 
112 void ConnectionFileDescriptor::CloseCommandPipe() {
113   Log *log = GetLog(LLDBLog::Connection);
114   LLDB_LOGF(log, "%p ConnectionFileDescriptor::CloseCommandPipe()",
115             static_cast<void *>(this));
116 
117   m_pipe.Close();
118 }
119 
120 bool ConnectionFileDescriptor::IsConnected() const {
121   return m_io_sp && m_io_sp->IsValid();
122 }
123 
124 ConnectionStatus ConnectionFileDescriptor::Connect(llvm::StringRef path,
125                                                    Status *error_ptr) {
126   return Connect(
127       path, [](llvm::StringRef) {}, 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 = GetLog(LLDBLog::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::AcceptTCP)
155             .Cases("accept", "unix-accept",
156                    &ConnectionFileDescriptor::AcceptNamedSocket)
157             .Case("unix-abstract-accept",
158                   &ConnectionFileDescriptor::AcceptAbstractSocket)
159             .Cases("connect", "tcp-connect",
160                    &ConnectionFileDescriptor::ConnectTCP)
161             .Case("udp", &ConnectionFileDescriptor::ConnectUDP)
162             .Case("unix-connect", &ConnectionFileDescriptor::ConnectNamedSocket)
163             .Case("unix-abstract-connect",
164                   &ConnectionFileDescriptor::ConnectAbstractSocket)
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       if (error_ptr)
174         *error_ptr = Status();
175       return (this->*method)(path, socket_id_callback, error_ptr);
176     }
177   }
178 
179   if (error_ptr)
180     error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'",
181                                         path.str().c_str());
182   return eConnectionStatusError;
183 }
184 
185 bool ConnectionFileDescriptor::InterruptRead() {
186   size_t bytes_written = 0;
187   Status result = m_pipe.Write("i", 1, bytes_written);
188   return result.Success();
189 }
190 
191 ConnectionStatus ConnectionFileDescriptor::Disconnect(Status *error_ptr) {
192   Log *log = GetLog(LLDBLog::Connection);
193   LLDB_LOGF(log, "%p ConnectionFileDescriptor::Disconnect ()",
194             static_cast<void *>(this));
195 
196   ConnectionStatus status = eConnectionStatusSuccess;
197 
198   if (!IsConnected()) {
199     LLDB_LOGF(
200         log, "%p ConnectionFileDescriptor::Disconnect(): Nothing to disconnect",
201         static_cast<void *>(this));
202     return eConnectionStatusSuccess;
203   }
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 = GetLog(LLDBLog::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 = GetLog(LLDBLog::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 = GetLog(LLDBLog::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           UNUSED_IF_ASSERT_DISABLED(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 lldb::ConnectionStatus ConnectionFileDescriptor::AcceptSocket(
536     Socket::SocketProtocol socket_protocol, llvm::StringRef socket_name,
537     llvm::function_ref<void(Socket &)> post_listen_callback,
538     Status *error_ptr) {
539   Status error;
540   std::unique_ptr<Socket> listening_socket =
541       Socket::Create(socket_protocol, m_child_processes_inherit, error);
542   Socket *accepted_socket;
543 
544   if (!error.Fail())
545     error = listening_socket->Listen(socket_name, 5);
546 
547   if (!error.Fail()) {
548     post_listen_callback(*listening_socket);
549     error = listening_socket->Accept(accepted_socket);
550   }
551 
552   if (!error.Fail()) {
553     m_io_sp.reset(accepted_socket);
554     m_uri.assign(socket_name.str());
555     return eConnectionStatusSuccess;
556   }
557 
558   if (error_ptr)
559     *error_ptr = error;
560   return eConnectionStatusError;
561 }
562 
563 lldb::ConnectionStatus
564 ConnectionFileDescriptor::ConnectSocket(Socket::SocketProtocol socket_protocol,
565                                         llvm::StringRef socket_name,
566                                         Status *error_ptr) {
567   Status error;
568   std::unique_ptr<Socket> socket =
569       Socket::Create(socket_protocol, m_child_processes_inherit, error);
570 
571   if (!error.Fail())
572     error = socket->Connect(socket_name);
573 
574   if (!error.Fail()) {
575     m_io_sp = std::move(socket);
576     m_uri.assign(socket_name.str());
577     return eConnectionStatusSuccess;
578   }
579 
580   if (error_ptr)
581     *error_ptr = error;
582   return eConnectionStatusError;
583 }
584 
585 ConnectionStatus ConnectionFileDescriptor::AcceptNamedSocket(
586     llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,
587     Status *error_ptr) {
588   return AcceptSocket(
589       Socket::ProtocolUnixDomain, socket_name,
590       [socket_id_callback, socket_name](Socket &listening_socket) {
591         socket_id_callback(socket_name);
592       },
593       error_ptr);
594 }
595 
596 ConnectionStatus ConnectionFileDescriptor::ConnectNamedSocket(
597     llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,
598     Status *error_ptr) {
599   return ConnectSocket(Socket::ProtocolUnixDomain, socket_name, error_ptr);
600 }
601 
602 ConnectionStatus ConnectionFileDescriptor::AcceptAbstractSocket(
603     llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,
604     Status *error_ptr) {
605   return AcceptSocket(
606       Socket::ProtocolUnixAbstract, socket_name,
607       [socket_id_callback, socket_name](Socket &listening_socket) {
608         socket_id_callback(socket_name);
609       },
610       error_ptr);
611 }
612 
613 lldb::ConnectionStatus ConnectionFileDescriptor::ConnectAbstractSocket(
614     llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,
615     Status *error_ptr) {
616   return ConnectSocket(Socket::ProtocolUnixAbstract, socket_name, error_ptr);
617 }
618 
619 ConnectionStatus
620 ConnectionFileDescriptor::AcceptTCP(llvm::StringRef socket_name,
621                                     socket_id_callback_type socket_id_callback,
622                                     Status *error_ptr) {
623   ConnectionStatus ret = AcceptSocket(
624       Socket::ProtocolTcp, socket_name,
625       [socket_id_callback](Socket &listening_socket) {
626         uint16_t port =
627             static_cast<TCPSocket &>(listening_socket).GetLocalPortNumber();
628         socket_id_callback(std::to_string(port));
629       },
630       error_ptr);
631   if (ret == eConnectionStatusSuccess)
632     m_uri.assign(
633         static_cast<TCPSocket *>(m_io_sp.get())->GetRemoteConnectionURI());
634   return ret;
635 }
636 
637 ConnectionStatus
638 ConnectionFileDescriptor::ConnectTCP(llvm::StringRef socket_name,
639                                      socket_id_callback_type socket_id_callback,
640                                      Status *error_ptr) {
641   return ConnectSocket(Socket::ProtocolTcp, socket_name, error_ptr);
642 }
643 
644 ConnectionStatus
645 ConnectionFileDescriptor::ConnectUDP(llvm::StringRef s,
646                                      socket_id_callback_type socket_id_callback,
647                                      Status *error_ptr) {
648   if (error_ptr)
649     *error_ptr = Status();
650   llvm::Expected<std::unique_ptr<UDPSocket>> socket =
651       Socket::UdpConnect(s, m_child_processes_inherit);
652   if (!socket) {
653     if (error_ptr)
654       *error_ptr = socket.takeError();
655     else
656       LLDB_LOG_ERROR(GetLog(LLDBLog::Connection), socket.takeError(),
657                      "tcp connect failed: {0}");
658     return eConnectionStatusError;
659   }
660   m_io_sp = std::move(*socket);
661   m_uri.assign(std::string(s));
662   return eConnectionStatusSuccess;
663 }
664 
665 ConnectionStatus
666 ConnectionFileDescriptor::ConnectFD(llvm::StringRef s,
667                                     socket_id_callback_type socket_id_callback,
668                                     Status *error_ptr) {
669 #if LLDB_ENABLE_POSIX
670   // Just passing a native file descriptor within this current process that
671   // is already opened (possibly from a service or other source).
672   int fd = -1;
673 
674   if (!s.getAsInteger(0, fd)) {
675     // We have what looks to be a valid file descriptor, but we should make
676     // sure it is. We currently are doing this by trying to get the flags
677     // from the file descriptor and making sure it isn't a bad fd.
678     errno = 0;
679     int flags = ::fcntl(fd, F_GETFL, 0);
680     if (flags == -1 || errno == EBADF) {
681       if (error_ptr)
682         error_ptr->SetErrorStringWithFormat("stale file descriptor: %s",
683                                             s.str().c_str());
684       m_io_sp.reset();
685       return eConnectionStatusError;
686     } else {
687       // Don't take ownership of a file descriptor that gets passed to us
688       // since someone else opened the file descriptor and handed it to us.
689       // TODO: Since are using a URL to open connection we should
690       // eventually parse options using the web standard where we have
691       // "fd://123?opt1=value;opt2=value" and we can have an option be
692       // "owns=1" or "owns=0" or something like this to allow us to specify
693       // this. For now, we assume we must assume we don't own it.
694 
695       std::unique_ptr<TCPSocket> tcp_socket;
696       tcp_socket = std::make_unique<TCPSocket>(fd, false, false);
697       // Try and get a socket option from this file descriptor to see if
698       // this is a socket and set m_is_socket accordingly.
699       int resuse;
700       bool is_socket =
701           !!tcp_socket->GetOption(SOL_SOCKET, SO_REUSEADDR, resuse);
702       if (is_socket)
703         m_io_sp = std::move(tcp_socket);
704       else
705         m_io_sp =
706             std::make_shared<NativeFile>(fd, File::eOpenOptionReadWrite, false);
707       m_uri = s.str();
708       return eConnectionStatusSuccess;
709     }
710   }
711 
712   if (error_ptr)
713     error_ptr->SetErrorStringWithFormat("invalid file descriptor: \"%s\"",
714                                         s.str().c_str());
715   m_io_sp.reset();
716   return eConnectionStatusError;
717 #endif // LLDB_ENABLE_POSIX
718   llvm_unreachable("this function should be only called w/ LLDB_ENABLE_POSIX");
719 }
720 
721 ConnectionStatus ConnectionFileDescriptor::ConnectFile(
722     llvm::StringRef s, socket_id_callback_type socket_id_callback,
723     Status *error_ptr) {
724 #if LLDB_ENABLE_POSIX
725   std::string addr_str = s.str();
726   // file:///PATH
727   int fd = FileSystem::Instance().Open(addr_str.c_str(), O_RDWR);
728   if (fd == -1) {
729     if (error_ptr)
730       error_ptr->SetErrorToErrno();
731     return eConnectionStatusError;
732   }
733 
734   if (::isatty(fd)) {
735     // Set up serial terminal emulation
736     struct termios options;
737     ::tcgetattr(fd, &options);
738 
739     // Set port speed to maximum
740     ::cfsetospeed(&options, B115200);
741     ::cfsetispeed(&options, B115200);
742 
743     // Raw input, disable echo and signals
744     options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
745 
746     // Make sure only one character is needed to return from a read
747     options.c_cc[VMIN] = 1;
748     options.c_cc[VTIME] = 0;
749 
750     llvm::sys::RetryAfterSignal(-1, ::tcsetattr, fd, TCSANOW, &options);
751   }
752 
753   m_io_sp = std::make_shared<NativeFile>(fd, File::eOpenOptionReadWrite, true);
754   return eConnectionStatusSuccess;
755 #endif // LLDB_ENABLE_POSIX
756   llvm_unreachable("this function should be only called w/ LLDB_ENABLE_POSIX");
757 }
758 
759 ConnectionStatus ConnectionFileDescriptor::ConnectSerialPort(
760     llvm::StringRef s, socket_id_callback_type socket_id_callback,
761     Status *error_ptr) {
762 #if LLDB_ENABLE_POSIX
763   llvm::StringRef path, qs;
764   // serial:///PATH?k1=v1&k2=v2...
765   std::tie(path, qs) = s.split('?');
766 
767   llvm::Expected<SerialPort::Options> serial_options =
768       SerialPort::OptionsFromURL(qs);
769   if (!serial_options) {
770     if (error_ptr)
771       *error_ptr = serial_options.takeError();
772     else
773       llvm::consumeError(serial_options.takeError());
774     return eConnectionStatusError;
775   }
776 
777   int fd = FileSystem::Instance().Open(path.str().c_str(), O_RDWR);
778   if (fd == -1) {
779     if (error_ptr)
780       error_ptr->SetErrorToErrno();
781     return eConnectionStatusError;
782   }
783 
784   llvm::Expected<std::unique_ptr<SerialPort>> serial_sp = SerialPort::Create(
785       fd, File::eOpenOptionReadWrite, serial_options.get(), true);
786   if (!serial_sp) {
787     if (error_ptr)
788       *error_ptr = serial_sp.takeError();
789     else
790       llvm::consumeError(serial_sp.takeError());
791     return eConnectionStatusError;
792   }
793   m_io_sp = std::move(serial_sp.get());
794 
795   return eConnectionStatusSuccess;
796 #endif // LLDB_ENABLE_POSIX
797   llvm_unreachable("this function should be only called w/ LLDB_ENABLE_POSIX");
798 }
799 
800 bool ConnectionFileDescriptor::GetChildProcessesInherit() const {
801   return m_child_processes_inherit;
802 }
803 
804 void ConnectionFileDescriptor::SetChildProcessesInherit(
805     bool child_processes_inherit) {
806   m_child_processes_inherit = child_processes_inherit;
807 }
808 
809 void ConnectionFileDescriptor::InitializeSocket(Socket *socket) {
810   m_io_sp.reset(socket);
811   m_uri = socket->GetRemoteConnectionURI();
812 }
813