11#include "lldb/Host/Config.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Support/Errno.h"
23#include "llvm/Support/Error.h"
24#include "llvm/Support/Regex.h"
25#include "llvm/Support/WindowsError.h"
32#include <netinet/in.h>
33#include <netinet/tcp.h>
34#include <sys/socket.h>
60 return ::WSAGetLastError() == WSAEINTR;
62 return errno == EINTR;
72 error = m_socket_pipe.CreateNew();
76 m_fd = m_socket_pipe.GetReadPipe();
86 m_socket_pipe.CloseReadFileDescriptor();
88 WSAPROTOCOL_INFO protocol_info;
89 if (::WSADuplicateSocket(m_socket, child_pid, &protocol_info) ==
91 int last_error = ::WSAGetLastError();
93 "WSADuplicateSocket() failed, error: %d", last_error);
96 llvm::Expected<size_t> num_bytes = m_socket_pipe.Write(
97 &protocol_info,
sizeof(protocol_info), std::chrono::seconds(10));
100 if (*num_bytes !=
sizeof(protocol_info))
102 "Write(WSAPROTOCOL_INFO) failed: wrote {0}/{1} bytes", *num_bytes,
103 sizeof(protocol_info));
112 WSAPROTOCOL_INFO protocol_info;
115 llvm::Expected<size_t> num_bytes = socket_pipe.
Read(
116 &protocol_info,
sizeof(protocol_info), std::chrono::seconds(10));
119 if (*num_bytes !=
sizeof(protocol_info)) {
121 "Read(WSAPROTOCOL_INFO) failed: read {0}/{1} bytes", *num_bytes,
122 sizeof(protocol_info));
125 socket = ::WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
126 FROM_PROTOCOL_INFO, &protocol_info, 0, 0);
127 if (socket == INVALID_SOCKET) {
129 "WSASocket(FROM_PROTOCOL_INFO) failed: error {0}", ::WSAGetLastError());
153 if (s.m_protocol == protocol)
162 if (!strcmp(s.m_scheme, scheme)) {
163 protocol = s.m_protocol;
178 auto wVersion = WINSOCK_VERSION;
180 int err = ::WSAStartup(wVersion, &wsaData);
182 if (wsaData.wVersion < wVersion) {
184 return llvm::createStringError(
"WSASock version is not expected");
187 return llvm::errorCodeToError(llvm::mapWindowsError(::WSAGetLastError()));
191 return llvm::Error::success();
204 const bool should_close =
true;
205 std::unique_ptr<Socket> socket_up;
208 socket_up = std::make_unique<TCPSocket>(should_close);
211 socket_up = std::make_unique<UDPSocket>(should_close);
215 socket_up = std::make_unique<DomainSocket>(should_close);
218 "Unix domain sockets are not supported on this platform.");
223 socket_up = std::make_unique<AbstractSocket>();
226 "Abstract domain sockets are not supported on this platform.");
237llvm::Expected<Socket::Pair>
241 switch (protocol.value_or(kBestProtocol)) {
248 return llvm::createStringError(
"unsupported protocol");
254 return llvm::createStringError(
"unsupported protocol");
257 return llvm::createStringError(
"unsupported protocol");
261llvm::Expected<std::unique_ptr<Socket>>
264 LLDB_LOG(log,
"host_and_port = {0}", host_and_port);
269 return error.ToError();
271 error = connect_socket->Connect(host_and_port);
273 return std::move(connect_socket);
275 return error.ToError();
278llvm::Expected<std::unique_ptr<TCPSocket>>
281 LLDB_LOG(log,
"host_and_port = {0}", host_and_port);
283 std::unique_ptr<TCPSocket> listen_socket(
286 Status error = listen_socket->Listen(host_and_port, backlog);
288 return error.ToError();
290 return std::move(listen_socket);
293llvm::Expected<std::unique_ptr<UDPSocket>>
298llvm::Expected<Socket::HostAndPort>
305 static llvm::Regex g_regex(
"([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+$)");
307 llvm::SmallVector<llvm::StringRef, 3> matches;
308 if (g_regex.match(host_and_port, &matches)) {
313 if (to_integer(matches[2], ret.
port, 10))
317 return llvm::createStringError(
318 llvm::inconvertibleErrorCode(),
319 "invalid host:port specification: '%s', both IPv4 (e.g., localhost:8080) "
320 "or IPv6 (e.g, [2001:db8::1]:8080) formats are supported",
321 host_and_port.str().c_str());
330 int bytes_received = 0;
332 bytes_received = ::recv(
m_socket,
static_cast<char *
>(buf), num_bytes, 0);
335 if (bytes_received < 0) {
339 num_bytes = bytes_received;
342 "%p Socket::Read() (socket = %" PRIu64
343 ", src = %p, src_len = %" PRIu64
", flags = 0) => %" PRIi64
345 static_cast<void *
>(
this),
static_cast<uint64_t
>(
m_socket), buf,
346 static_cast<uint64_t
>(num_bytes),
347 static_cast<int64_t
>(bytes_received),
error.AsCString());
353 const size_t src_len = num_bytes;
357 bytes_sent =
Send(buf, num_bytes);
360 if (bytes_sent < 0) {
364 num_bytes = bytes_sent;
367 "%p Socket::Write() (socket = %" PRIu64
368 ", src = %p, src_len = %" PRIu64
", flags = 0) => %" PRIi64
370 static_cast<void *
>(
this),
static_cast<uint64_t
>(
m_socket), buf,
371 static_cast<uint64_t
>(src_len),
static_cast<int64_t
>(bytes_sent),
383 LLDB_LOGF(log,
"%p Socket::Close (fd = %" PRIu64
")",
384 static_cast<void *
>(
this),
static_cast<uint64_t
>(
m_socket));
400 socklen_t option_value_size =
sizeof(int);
401 return ::getsockopt(sockfd, level, option_name, option_value_p,
409 return ::setsockopt(sockfd, level, option_name, option_value_p,
410 sizeof(option_value));
415#if defined(MSG_NOSIGNAL)
416 flags |= MSG_NOSIGNAL;
418 return ::send(
m_socket,
static_cast<const char *
>(buf), num_bytes, flags);
432 EC = llvm::mapWindowsError(WSAGetLastError());
434 EC = std::error_code(errno, std::generic_category());
441 return ::closesocket(sockfd);
443 return ::close(sockfd);
450 auto socket_type = type;
452 socket_type |= SOCK_CLOEXEC;
454 auto sock = ::socket(domain, socket_type, protocol);
458#if defined(SO_NOSIGPIPE)
461 sock, llvm::sys::StrError());
470 llvm::Expected<std::vector<MainLoopBase::ReadHandleUP>> expected_handles =
472 [&accept_loop, &socket](std::unique_ptr<Socket> sock) {
473 socket = sock.release();
476 if (!expected_handles)
486 return Status(std::make_error_code(std::errc::timed_out));
492#if defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
493 int flags = SOCK_CLOEXEC;
495 static_cast<NativeSocket>(-1), ::accept4, sockfd, addr, addrlen, flags);
498 static_cast<NativeSocket>(-1), ::accept, sockfd, addr, addrlen);
510std::optional<Socket::ProtocolModePair>
513 return llvm::StringSwitch<std::optional<ProtocolModePair>>(scheme)
516 .Cases({
"accept",
"unix-accept"},
519 .Case(
"unix-abstract-accept",
522 .Cases({
"connect",
"tcp-connect",
"connection"},
529 .Case(
"unix-abstract-connect",
532 .Default(std::nullopt);
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
#define LLDB_LOGF(log,...)
static bool IsInterrupted()
void * get_socket_option_arg_type
const void * set_socket_option_arg_type
static SocketScheme socket_schemes[]
static llvm::Expected< Pair > CreatePair()
Create a connected pair of domain sockets using socketpair(2).
lldb::file_t WaitableHandle
virtual void RequestTermination()
bool AddCallback(const Callback &callback, std::chrono::nanoseconds delay)
llvm::Expected< size_t > Read(void *buf, size_t size, const Timeout< std::micro > &timeout=std::nullopt) override
static const shared_fd_t kInvalidFD
SharedSocket(const Socket *socket, Status &error)
Status CompleteSending(lldb::pid_t child_pid)
static Status GetNativeSocket(shared_fd_t fd, NativeSocket &socket)
static std::unique_ptr< Socket > Create(const SocketProtocol protocol, Status &error)
Status Read(void *buf, size_t &num_bytes) override
NativeSocket GetNativeSocket() const
static const NativeSocket kInvalidSocketValue
WaitableHandle GetWaitableHandle() override
SocketProtocol m_protocol
std::pair< SocketProtocol, SocketMode > ProtocolModePair
static llvm::Expected< std::unique_ptr< UDPSocket > > UdpConnect(llvm::StringRef host_and_port)
virtual llvm::Expected< std::vector< MainLoopBase::ReadHandleUP > > Accept(MainLoopBase &loop, std::function< void(std::unique_ptr< Socket > socket)> sock_cb)=0
static NativeSocket CreateSocket(const int domain, const int type, const int protocol, Status &error)
static int GetOption(NativeSocket sockfd, int level, int option_name, int &option_value)
static llvm::Expected< HostAndPort > DecodeHostAndPort(llvm::StringRef host_and_port)
static NativeSocket AcceptSocket(NativeSocket sockfd, struct sockaddr *addr, socklen_t *addrlen, Status &error)
static bool FindProtocolByScheme(const char *scheme, SocketProtocol &protocol)
bool IsValid() const override
static Status GetLastError()
static llvm::Expected< std::unique_ptr< Socket > > TcpConnect(llvm::StringRef host_and_port)
static void SetLastError(Status &error)
static llvm::Error Initialize()
static int CloseSocket(NativeSocket sockfd)
static const char * FindSchemeByProtocol(const SocketProtocol protocol)
static int SetOption(NativeSocket sockfd, int level, int option_name, int option_value)
virtual ssize_t Send(const void *buf, const size_t num_bytes)
Status Write(const void *buf, size_t &num_bytes) override
static llvm::Expected< std::unique_ptr< TCPSocket > > TcpListen(llvm::StringRef host_and_port, int backlog=5)
static std::optional< ProtocolModePair > GetProtocolAndMode(llvm::StringRef scheme)
static llvm::Expected< Pair > CreatePair(std::optional< SocketProtocol > protocol=std::nullopt)
Socket(SocketProtocol protocol, bool should_close)
static Status FromErrno()
Set the current error to errno.
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
static Status FromErrorString(const char *str)
bool Fail() const
Test for error condition.
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
static llvm::Expected< Pair > CreatePair()
static llvm::Expected< std::unique_ptr< UDPSocket > > CreateConnected(llvm::StringRef name)
#define LLDB_INVALID_PIPE
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Stream & operator<<(Stream &s, const Mangled &obj)
@ eErrorTypeWin32
Standard Win32 error codes.
const Socket::SocketProtocol m_protocol