Path: blob/main/contrib/llvm-project/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp
39606 views
//===-- ConnectionFileDescriptorPosix.cpp ---------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#if defined(__APPLE__)9// Enable this special support for Apple builds where we can have unlimited10// select bounds. We tried switching to poll() and kqueue and we were panicing11// the kernel, so we have to stick with select for now.12#define _DARWIN_UNLIMITED_SELECT13#endif1415#include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"16#include "lldb/Host/Config.h"17#include "lldb/Host/FileSystem.h"18#include "lldb/Host/Socket.h"19#include "lldb/Host/SocketAddress.h"20#include "lldb/Utility/LLDBLog.h"21#include "lldb/Utility/SelectHelper.h"22#include "lldb/Utility/Timeout.h"2324#include <cerrno>25#include <cstdlib>26#include <cstring>27#include <fcntl.h>28#include <sys/types.h>2930#if LLDB_ENABLE_POSIX31#include <termios.h>32#include <unistd.h>33#endif3435#include <memory>36#include <sstream>3738#include "llvm/Support/Errno.h"39#include "llvm/Support/ErrorHandling.h"40#if defined(__APPLE__)41#include "llvm/ADT/SmallVector.h"42#endif43#include "lldb/Host/Host.h"44#include "lldb/Host/Socket.h"45#include "lldb/Host/common/TCPSocket.h"46#include "lldb/Host/common/UDPSocket.h"47#include "lldb/Utility/Log.h"48#include "lldb/Utility/StreamString.h"49#include "lldb/Utility/Timer.h"5051using namespace lldb;52using namespace lldb_private;5354ConnectionFileDescriptor::ConnectionFileDescriptor(bool child_processes_inherit)55: Connection(), m_pipe(), m_mutex(), m_shutting_down(false),5657m_child_processes_inherit(child_processes_inherit) {58Log *log(GetLog(LLDBLog::Connection | LLDBLog::Object));59LLDB_LOGF(log, "%p ConnectionFileDescriptor::ConnectionFileDescriptor ()",60static_cast<void *>(this));61}6263ConnectionFileDescriptor::ConnectionFileDescriptor(int fd, bool owns_fd)64: Connection(), m_pipe(), m_mutex(), m_shutting_down(false),65m_child_processes_inherit(false) {66m_io_sp =67std::make_shared<NativeFile>(fd, File::eOpenOptionReadWrite, owns_fd);6869Log *log(GetLog(LLDBLog::Connection | LLDBLog::Object));70LLDB_LOGF(log,71"%p ConnectionFileDescriptor::ConnectionFileDescriptor (fd = "72"%i, owns_fd = %i)",73static_cast<void *>(this), fd, owns_fd);74OpenCommandPipe();75}7677ConnectionFileDescriptor::ConnectionFileDescriptor(Socket *socket)78: Connection(), m_pipe(), m_mutex(), m_shutting_down(false),79m_child_processes_inherit(false) {80InitializeSocket(socket);81}8283ConnectionFileDescriptor::~ConnectionFileDescriptor() {84Log *log(GetLog(LLDBLog::Connection | LLDBLog::Object));85LLDB_LOGF(log, "%p ConnectionFileDescriptor::~ConnectionFileDescriptor ()",86static_cast<void *>(this));87Disconnect(nullptr);88CloseCommandPipe();89}9091void ConnectionFileDescriptor::OpenCommandPipe() {92CloseCommandPipe();9394Log *log = GetLog(LLDBLog::Connection);95// Make the command file descriptor here:96Status result = m_pipe.CreateNew(m_child_processes_inherit);97if (!result.Success()) {98LLDB_LOGF(log,99"%p ConnectionFileDescriptor::OpenCommandPipe () - could not "100"make pipe: %s",101static_cast<void *>(this), result.AsCString());102} else {103LLDB_LOGF(log,104"%p ConnectionFileDescriptor::OpenCommandPipe() - success "105"readfd=%d writefd=%d",106static_cast<void *>(this), m_pipe.GetReadFileDescriptor(),107m_pipe.GetWriteFileDescriptor());108}109}110111void ConnectionFileDescriptor::CloseCommandPipe() {112Log *log = GetLog(LLDBLog::Connection);113LLDB_LOGF(log, "%p ConnectionFileDescriptor::CloseCommandPipe()",114static_cast<void *>(this));115116m_pipe.Close();117}118119bool ConnectionFileDescriptor::IsConnected() const {120return m_io_sp && m_io_sp->IsValid();121}122123ConnectionStatus ConnectionFileDescriptor::Connect(llvm::StringRef path,124Status *error_ptr) {125return Connect(126path, [](llvm::StringRef) {}, error_ptr);127}128129ConnectionStatus130ConnectionFileDescriptor::Connect(llvm::StringRef path,131socket_id_callback_type socket_id_callback,132Status *error_ptr) {133std::lock_guard<std::recursive_mutex> guard(m_mutex);134Log *log = GetLog(LLDBLog::Connection);135LLDB_LOGF(log, "%p ConnectionFileDescriptor::Connect (url = '%s')",136static_cast<void *>(this), path.str().c_str());137138OpenCommandPipe();139140if (path.empty()) {141if (error_ptr)142error_ptr->SetErrorString("invalid connect arguments");143return eConnectionStatusError;144}145146llvm::StringRef scheme;147std::tie(scheme, path) = path.split("://");148149if (!path.empty()) {150auto method =151llvm::StringSwitch<ConnectionStatus (ConnectionFileDescriptor::*)(152llvm::StringRef, socket_id_callback_type, Status *)>(scheme)153.Case("listen", &ConnectionFileDescriptor::AcceptTCP)154.Cases("accept", "unix-accept",155&ConnectionFileDescriptor::AcceptNamedSocket)156.Case("unix-abstract-accept",157&ConnectionFileDescriptor::AcceptAbstractSocket)158.Cases("connect", "tcp-connect",159&ConnectionFileDescriptor::ConnectTCP)160.Case("udp", &ConnectionFileDescriptor::ConnectUDP)161.Case("unix-connect", &ConnectionFileDescriptor::ConnectNamedSocket)162.Case("unix-abstract-connect",163&ConnectionFileDescriptor::ConnectAbstractSocket)164#if LLDB_ENABLE_POSIX165.Case("fd", &ConnectionFileDescriptor::ConnectFD)166.Case("file", &ConnectionFileDescriptor::ConnectFile)167.Case("serial", &ConnectionFileDescriptor::ConnectSerialPort)168#endif169.Default(nullptr);170171if (method) {172if (error_ptr)173*error_ptr = Status();174return (this->*method)(path, socket_id_callback, error_ptr);175}176}177178if (error_ptr)179error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'",180path.str().c_str());181return eConnectionStatusError;182}183184bool ConnectionFileDescriptor::InterruptRead() {185size_t bytes_written = 0;186Status result = m_pipe.Write("i", 1, bytes_written);187return result.Success();188}189190ConnectionStatus ConnectionFileDescriptor::Disconnect(Status *error_ptr) {191Log *log = GetLog(LLDBLog::Connection);192LLDB_LOGF(log, "%p ConnectionFileDescriptor::Disconnect ()",193static_cast<void *>(this));194195ConnectionStatus status = eConnectionStatusSuccess;196197if (!IsConnected()) {198LLDB_LOGF(199log, "%p ConnectionFileDescriptor::Disconnect(): Nothing to disconnect",200static_cast<void *>(this));201return eConnectionStatusSuccess;202}203204// Try to get the ConnectionFileDescriptor's mutex. If we fail, that is205// quite likely because somebody is doing a blocking read on our file206// descriptor. If that's the case, then send the "q" char to the command207// file channel so the read will wake up and the connection will then know to208// shut down.209std::unique_lock<std::recursive_mutex> locker(m_mutex, std::defer_lock);210if (!locker.try_lock()) {211if (m_pipe.CanWrite()) {212size_t bytes_written = 0;213Status result = m_pipe.Write("q", 1, bytes_written);214LLDB_LOGF(log,215"%p ConnectionFileDescriptor::Disconnect(): Couldn't get "216"the lock, sent 'q' to %d, error = '%s'.",217static_cast<void *>(this), m_pipe.GetWriteFileDescriptor(),218result.AsCString());219} else if (log) {220LLDB_LOGF(log,221"%p ConnectionFileDescriptor::Disconnect(): Couldn't get the "222"lock, but no command pipe is available.",223static_cast<void *>(this));224}225locker.lock();226}227228// Prevents reads and writes during shutdown.229m_shutting_down = true;230231Status error = m_io_sp->Close();232if (error.Fail())233status = eConnectionStatusError;234if (error_ptr)235*error_ptr = error;236237// Close any pipes we were using for async interrupts238m_pipe.Close();239240m_uri.clear();241m_shutting_down = false;242return status;243}244245size_t ConnectionFileDescriptor::Read(void *dst, size_t dst_len,246const Timeout<std::micro> &timeout,247ConnectionStatus &status,248Status *error_ptr) {249Log *log = GetLog(LLDBLog::Connection);250251std::unique_lock<std::recursive_mutex> locker(m_mutex, std::defer_lock);252if (!locker.try_lock()) {253LLDB_LOGF(log,254"%p ConnectionFileDescriptor::Read () failed to get the "255"connection lock.",256static_cast<void *>(this));257if (error_ptr)258error_ptr->SetErrorString("failed to get the connection lock for read.");259260status = eConnectionStatusTimedOut;261return 0;262}263264if (m_shutting_down) {265if (error_ptr)266error_ptr->SetErrorString("shutting down");267status = eConnectionStatusError;268return 0;269}270271status = BytesAvailable(timeout, error_ptr);272if (status != eConnectionStatusSuccess)273return 0;274275Status error;276size_t bytes_read = dst_len;277error = m_io_sp->Read(dst, bytes_read);278279if (log) {280LLDB_LOGF(log,281"%p ConnectionFileDescriptor::Read() fd = %" PRIu64282", dst = %p, dst_len = %" PRIu64 ") => %" PRIu64 ", error = %s",283static_cast<void *>(this),284static_cast<uint64_t>(m_io_sp->GetWaitableHandle()),285static_cast<void *>(dst), static_cast<uint64_t>(dst_len),286static_cast<uint64_t>(bytes_read), error.AsCString());287}288289if (bytes_read == 0) {290error.Clear(); // End-of-file. Do not automatically close; pass along for291// the end-of-file handlers.292status = eConnectionStatusEndOfFile;293}294295if (error_ptr)296*error_ptr = error;297298if (error.Fail()) {299uint32_t error_value = error.GetError();300switch (error_value) {301case EAGAIN: // The file was marked for non-blocking I/O, and no data were302// ready to be read.303if (m_io_sp->GetFdType() == IOObject::eFDTypeSocket)304status = eConnectionStatusTimedOut;305else306status = eConnectionStatusSuccess;307return 0;308309case EFAULT: // Buf points outside the allocated address space.310case EINTR: // A read from a slow device was interrupted before any data311// arrived by the delivery of a signal.312case EINVAL: // The pointer associated with fildes was negative.313case EIO: // An I/O error occurred while reading from the file system.314// The process group is orphaned.315// The file is a regular file, nbyte is greater than 0, the316// starting position is before the end-of-file, and the317// starting position is greater than or equal to the offset318// maximum established for the open file descriptor319// associated with fildes.320case EISDIR: // An attempt is made to read a directory.321case ENOBUFS: // An attempt to allocate a memory buffer fails.322case ENOMEM: // Insufficient memory is available.323status = eConnectionStatusError;324break; // Break to close....325326case ENOENT: // no such file or directory327case EBADF: // fildes is not a valid file or socket descriptor open for328// reading.329case ENXIO: // An action is requested of a device that does not exist..330// A requested action cannot be performed by the device.331case ECONNRESET: // The connection is closed by the peer during a read332// attempt on a socket.333case ENOTCONN: // A read is attempted on an unconnected socket.334status = eConnectionStatusLostConnection;335break; // Break to close....336337case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a338// socket.339status = eConnectionStatusTimedOut;340return 0;341342default:343LLDB_LOG(log, "this = {0}, unexpected error: {1}", this,344llvm::sys::StrError(error_value));345status = eConnectionStatusError;346break; // Break to close....347}348349return 0;350}351return bytes_read;352}353354size_t ConnectionFileDescriptor::Write(const void *src, size_t src_len,355ConnectionStatus &status,356Status *error_ptr) {357Log *log = GetLog(LLDBLog::Connection);358LLDB_LOGF(log,359"%p ConnectionFileDescriptor::Write (src = %p, src_len = %" PRIu64360")",361static_cast<void *>(this), static_cast<const void *>(src),362static_cast<uint64_t>(src_len));363364if (!IsConnected()) {365if (error_ptr)366error_ptr->SetErrorString("not connected");367status = eConnectionStatusNoConnection;368return 0;369}370371if (m_shutting_down) {372if (error_ptr)373error_ptr->SetErrorString("shutting down");374status = eConnectionStatusError;375return 0;376}377378Status error;379380size_t bytes_sent = src_len;381error = m_io_sp->Write(src, bytes_sent);382383if (log) {384LLDB_LOGF(log,385"%p ConnectionFileDescriptor::Write(fd = %" PRIu64386", src = %p, src_len = %" PRIu64 ") => %" PRIu64 " (error = %s)",387static_cast<void *>(this),388static_cast<uint64_t>(m_io_sp->GetWaitableHandle()),389static_cast<const void *>(src), static_cast<uint64_t>(src_len),390static_cast<uint64_t>(bytes_sent), error.AsCString());391}392393if (error_ptr)394*error_ptr = error;395396if (error.Fail()) {397switch (error.GetError()) {398case EAGAIN:399case EINTR:400status = eConnectionStatusSuccess;401return 0;402403case ECONNRESET: // The connection is closed by the peer during a read404// attempt on a socket.405case ENOTCONN: // A read is attempted on an unconnected socket.406status = eConnectionStatusLostConnection;407break; // Break to close....408409default:410status = eConnectionStatusError;411break; // Break to close....412}413414return 0;415}416417status = eConnectionStatusSuccess;418return bytes_sent;419}420421std::string ConnectionFileDescriptor::GetURI() { return m_uri; }422423// This ConnectionFileDescriptor::BytesAvailable() uses select() via424// SelectHelper425//426// PROS:427// - select is consistent across most unix platforms428// - The Apple specific version allows for unlimited fds in the fd_sets by429// setting the _DARWIN_UNLIMITED_SELECT define prior to including the430// required header files.431// CONS:432// - on non-Apple platforms, only supports file descriptors up to FD_SETSIZE.433// This implementation will assert if it runs into that hard limit to let434// users know that another ConnectionFileDescriptor::BytesAvailable() should435// be used or a new version of ConnectionFileDescriptor::BytesAvailable()436// should be written for the system that is running into the limitations.437438ConnectionStatus439ConnectionFileDescriptor::BytesAvailable(const Timeout<std::micro> &timeout,440Status *error_ptr) {441// Don't need to take the mutex here separately since we are only called from442// Read. If we ever get used more generally we will need to lock here as443// well.444445Log *log = GetLog(LLDBLog::Connection);446LLDB_LOG(log, "this = {0}, timeout = {1}", this, timeout);447448// Make a copy of the file descriptors to make sure we don't have another449// thread change these values out from under us and cause problems in the450// loop below where like in FS_SET()451const IOObject::WaitableHandle handle = m_io_sp->GetWaitableHandle();452const int pipe_fd = m_pipe.GetReadFileDescriptor();453454if (handle != IOObject::kInvalidHandleValue) {455SelectHelper select_helper;456if (timeout)457select_helper.SetTimeout(*timeout);458459select_helper.FDSetRead(handle);460#if defined(_WIN32)461// select() won't accept pipes on Windows. The entire Windows codepath462// needs to be converted over to using WaitForMultipleObjects and event463// HANDLEs, but for now at least this will allow ::select() to not return464// an error.465const bool have_pipe_fd = false;466#else467const bool have_pipe_fd = pipe_fd >= 0;468#endif469if (have_pipe_fd)470select_helper.FDSetRead(pipe_fd);471472while (handle == m_io_sp->GetWaitableHandle()) {473474Status error = select_helper.Select();475476if (error_ptr)477*error_ptr = error;478479if (error.Fail()) {480switch (error.GetError()) {481case EBADF: // One of the descriptor sets specified an invalid482// descriptor.483return eConnectionStatusLostConnection;484485case EINVAL: // The specified time limit is invalid. One of its486// components is negative or too large.487default: // Other unknown error488return eConnectionStatusError;489490case ETIMEDOUT:491return eConnectionStatusTimedOut;492493case EAGAIN: // The kernel was (perhaps temporarily) unable to494// allocate the requested number of file descriptors, or495// we have non-blocking IO496case EINTR: // A signal was delivered before the time limit497// expired and before any of the selected events occurred.498break; // Lets keep reading to until we timeout499}500} else {501if (select_helper.FDIsSetRead(handle))502return eConnectionStatusSuccess;503504if (select_helper.FDIsSetRead(pipe_fd)) {505// There is an interrupt or exit command in the command pipe Read the506// data from that pipe:507char c;508509ssize_t bytes_read =510llvm::sys::RetryAfterSignal(-1, ::read, pipe_fd, &c, 1);511assert(bytes_read == 1);512UNUSED_IF_ASSERT_DISABLED(bytes_read);513switch (c) {514case 'q':515LLDB_LOGF(log,516"%p ConnectionFileDescriptor::BytesAvailable() "517"got data: %c from the command channel.",518static_cast<void *>(this), c);519return eConnectionStatusEndOfFile;520case 'i':521// Interrupt the current read522return eConnectionStatusInterrupted;523}524}525}526}527}528529if (error_ptr)530error_ptr->SetErrorString("not connected");531return eConnectionStatusLostConnection;532}533534lldb::ConnectionStatus ConnectionFileDescriptor::AcceptSocket(535Socket::SocketProtocol socket_protocol, llvm::StringRef socket_name,536llvm::function_ref<void(Socket &)> post_listen_callback,537Status *error_ptr) {538Status error;539std::unique_ptr<Socket> listening_socket =540Socket::Create(socket_protocol, m_child_processes_inherit, error);541Socket *accepted_socket;542543if (!error.Fail())544error = listening_socket->Listen(socket_name, 5);545546if (!error.Fail()) {547post_listen_callback(*listening_socket);548error = listening_socket->Accept(accepted_socket);549}550551if (!error.Fail()) {552m_io_sp.reset(accepted_socket);553m_uri.assign(socket_name.str());554return eConnectionStatusSuccess;555}556557if (error_ptr)558*error_ptr = error;559return eConnectionStatusError;560}561562lldb::ConnectionStatus563ConnectionFileDescriptor::ConnectSocket(Socket::SocketProtocol socket_protocol,564llvm::StringRef socket_name,565Status *error_ptr) {566Status error;567std::unique_ptr<Socket> socket =568Socket::Create(socket_protocol, m_child_processes_inherit, error);569570if (!error.Fail())571error = socket->Connect(socket_name);572573if (!error.Fail()) {574m_io_sp = std::move(socket);575m_uri.assign(socket_name.str());576return eConnectionStatusSuccess;577}578579if (error_ptr)580*error_ptr = error;581return eConnectionStatusError;582}583584ConnectionStatus ConnectionFileDescriptor::AcceptNamedSocket(585llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,586Status *error_ptr) {587return AcceptSocket(588Socket::ProtocolUnixDomain, socket_name,589[socket_id_callback, socket_name](Socket &listening_socket) {590socket_id_callback(socket_name);591},592error_ptr);593}594595ConnectionStatus ConnectionFileDescriptor::ConnectNamedSocket(596llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,597Status *error_ptr) {598return ConnectSocket(Socket::ProtocolUnixDomain, socket_name, error_ptr);599}600601ConnectionStatus ConnectionFileDescriptor::AcceptAbstractSocket(602llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,603Status *error_ptr) {604return AcceptSocket(605Socket::ProtocolUnixAbstract, socket_name,606[socket_id_callback, socket_name](Socket &listening_socket) {607socket_id_callback(socket_name);608},609error_ptr);610}611612lldb::ConnectionStatus ConnectionFileDescriptor::ConnectAbstractSocket(613llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,614Status *error_ptr) {615return ConnectSocket(Socket::ProtocolUnixAbstract, socket_name, error_ptr);616}617618ConnectionStatus619ConnectionFileDescriptor::AcceptTCP(llvm::StringRef socket_name,620socket_id_callback_type socket_id_callback,621Status *error_ptr) {622ConnectionStatus ret = AcceptSocket(623Socket::ProtocolTcp, socket_name,624[socket_id_callback](Socket &listening_socket) {625uint16_t port =626static_cast<TCPSocket &>(listening_socket).GetLocalPortNumber();627socket_id_callback(std::to_string(port));628},629error_ptr);630if (ret == eConnectionStatusSuccess)631m_uri.assign(632static_cast<TCPSocket *>(m_io_sp.get())->GetRemoteConnectionURI());633return ret;634}635636ConnectionStatus637ConnectionFileDescriptor::ConnectTCP(llvm::StringRef socket_name,638socket_id_callback_type socket_id_callback,639Status *error_ptr) {640return ConnectSocket(Socket::ProtocolTcp, socket_name, error_ptr);641}642643ConnectionStatus644ConnectionFileDescriptor::ConnectUDP(llvm::StringRef s,645socket_id_callback_type socket_id_callback,646Status *error_ptr) {647if (error_ptr)648*error_ptr = Status();649llvm::Expected<std::unique_ptr<UDPSocket>> socket =650Socket::UdpConnect(s, m_child_processes_inherit);651if (!socket) {652if (error_ptr)653*error_ptr = socket.takeError();654else655LLDB_LOG_ERROR(GetLog(LLDBLog::Connection), socket.takeError(),656"tcp connect failed: {0}");657return eConnectionStatusError;658}659m_io_sp = std::move(*socket);660m_uri.assign(std::string(s));661return eConnectionStatusSuccess;662}663664ConnectionStatus665ConnectionFileDescriptor::ConnectFD(llvm::StringRef s,666socket_id_callback_type socket_id_callback,667Status *error_ptr) {668#if LLDB_ENABLE_POSIX669// Just passing a native file descriptor within this current process that670// is already opened (possibly from a service or other source).671int fd = -1;672673if (!s.getAsInteger(0, fd)) {674// We have what looks to be a valid file descriptor, but we should make675// sure it is. We currently are doing this by trying to get the flags676// from the file descriptor and making sure it isn't a bad fd.677errno = 0;678int flags = ::fcntl(fd, F_GETFL, 0);679if (flags == -1 || errno == EBADF) {680if (error_ptr)681error_ptr->SetErrorStringWithFormat("stale file descriptor: %s",682s.str().c_str());683m_io_sp.reset();684return eConnectionStatusError;685} else {686// Don't take ownership of a file descriptor that gets passed to us687// since someone else opened the file descriptor and handed it to us.688// TODO: Since are using a URL to open connection we should689// eventually parse options using the web standard where we have690// "fd://123?opt1=value;opt2=value" and we can have an option be691// "owns=1" or "owns=0" or something like this to allow us to specify692// this. For now, we assume we must assume we don't own it.693694std::unique_ptr<TCPSocket> tcp_socket;695tcp_socket = std::make_unique<TCPSocket>(fd, false, false);696// Try and get a socket option from this file descriptor to see if697// this is a socket and set m_is_socket accordingly.698int resuse;699bool is_socket =700!!tcp_socket->GetOption(SOL_SOCKET, SO_REUSEADDR, resuse);701if (is_socket)702m_io_sp = std::move(tcp_socket);703else704m_io_sp =705std::make_shared<NativeFile>(fd, File::eOpenOptionReadWrite, false);706m_uri = s.str();707return eConnectionStatusSuccess;708}709}710711if (error_ptr)712error_ptr->SetErrorStringWithFormat("invalid file descriptor: \"%s\"",713s.str().c_str());714m_io_sp.reset();715return eConnectionStatusError;716#endif // LLDB_ENABLE_POSIX717llvm_unreachable("this function should be only called w/ LLDB_ENABLE_POSIX");718}719720ConnectionStatus ConnectionFileDescriptor::ConnectFile(721llvm::StringRef s, socket_id_callback_type socket_id_callback,722Status *error_ptr) {723#if LLDB_ENABLE_POSIX724std::string addr_str = s.str();725// file:///PATH726int fd = FileSystem::Instance().Open(addr_str.c_str(), O_RDWR);727if (fd == -1) {728if (error_ptr)729error_ptr->SetErrorToErrno();730return eConnectionStatusError;731}732733if (::isatty(fd)) {734// Set up serial terminal emulation735struct termios options;736::tcgetattr(fd, &options);737738// Set port speed to maximum739::cfsetospeed(&options, B115200);740::cfsetispeed(&options, B115200);741742// Raw input, disable echo and signals743options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);744745// Make sure only one character is needed to return from a read746options.c_cc[VMIN] = 1;747options.c_cc[VTIME] = 0;748749llvm::sys::RetryAfterSignal(-1, ::tcsetattr, fd, TCSANOW, &options);750}751752m_io_sp = std::make_shared<NativeFile>(fd, File::eOpenOptionReadWrite, true);753return eConnectionStatusSuccess;754#endif // LLDB_ENABLE_POSIX755llvm_unreachable("this function should be only called w/ LLDB_ENABLE_POSIX");756}757758ConnectionStatus ConnectionFileDescriptor::ConnectSerialPort(759llvm::StringRef s, socket_id_callback_type socket_id_callback,760Status *error_ptr) {761#if LLDB_ENABLE_POSIX762llvm::StringRef path, qs;763// serial:///PATH?k1=v1&k2=v2...764std::tie(path, qs) = s.split('?');765766llvm::Expected<SerialPort::Options> serial_options =767SerialPort::OptionsFromURL(qs);768if (!serial_options) {769if (error_ptr)770*error_ptr = serial_options.takeError();771else772llvm::consumeError(serial_options.takeError());773return eConnectionStatusError;774}775776int fd = FileSystem::Instance().Open(path.str().c_str(), O_RDWR);777if (fd == -1) {778if (error_ptr)779error_ptr->SetErrorToErrno();780return eConnectionStatusError;781}782783llvm::Expected<std::unique_ptr<SerialPort>> serial_sp = SerialPort::Create(784fd, File::eOpenOptionReadWrite, serial_options.get(), true);785if (!serial_sp) {786if (error_ptr)787*error_ptr = serial_sp.takeError();788else789llvm::consumeError(serial_sp.takeError());790return eConnectionStatusError;791}792m_io_sp = std::move(serial_sp.get());793794return eConnectionStatusSuccess;795#endif // LLDB_ENABLE_POSIX796llvm_unreachable("this function should be only called w/ LLDB_ENABLE_POSIX");797}798799bool ConnectionFileDescriptor::GetChildProcessesInherit() const {800return m_child_processes_inherit;801}802803void ConnectionFileDescriptor::SetChildProcessesInherit(804bool child_processes_inherit) {805m_child_processes_inherit = child_processes_inherit;806}807808void ConnectionFileDescriptor::InitializeSocket(Socket *socket) {809m_io_sp.reset(socket);810m_uri = socket->GetRemoteConnectionURI();811}812813814