LLDB mainline
Socket.cpp
Go to the documentation of this file.
1//===-- Socket.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#include "lldb/Host/Socket.h"
10
11#include "lldb/Host/Config.h"
12#include "lldb/Host/Host.h"
13#include "lldb/Host/MainLoop.h"
18#include "lldb/Utility/Log.h"
19
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"
26
28
29#if LLDB_ENABLE_POSIX
30#include <arpa/inet.h>
31#include <netdb.h>
32#include <netinet/in.h>
33#include <netinet/tcp.h>
34#include <sys/socket.h>
35#include <sys/un.h>
36#include <unistd.h>
37#endif
38
39#ifdef __linux__
41#endif
42
43using namespace lldb;
44using namespace lldb_private;
45
46#if defined(_WIN32)
47typedef const char *set_socket_option_arg_type;
48typedef char *get_socket_option_arg_type;
49const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
51#else // #if defined(_WIN32)
52typedef const void *set_socket_option_arg_type;
56#endif // #if defined(_WIN32)
57
58static bool IsInterrupted() {
59#if defined(_WIN32)
60 return ::WSAGetLastError() == WSAEINTR;
61#else
62 return errno == EINTR;
63#endif
64}
65
67#ifdef _WIN32
68 m_socket = socket->GetNativeSocket();
70
71 // Create a pipe to transfer WSAPROTOCOL_INFO to the child process.
72 error = m_socket_pipe.CreateNew();
73 if (error.Fail())
74 return;
75
76 m_fd = m_socket_pipe.GetReadPipe();
77#else
78 m_fd = socket->GetNativeSocket();
79 error = Status();
80#endif
81}
82
84#ifdef _WIN32
85 // Transfer WSAPROTOCOL_INFO to the child process.
86 m_socket_pipe.CloseReadFileDescriptor();
87
88 WSAPROTOCOL_INFO protocol_info;
89 if (::WSADuplicateSocket(m_socket, child_pid, &protocol_info) ==
90 SOCKET_ERROR) {
91 int last_error = ::WSAGetLastError();
93 "WSADuplicateSocket() failed, error: %d", last_error);
94 }
95
96 llvm::Expected<size_t> num_bytes = m_socket_pipe.Write(
97 &protocol_info, sizeof(protocol_info), std::chrono::seconds(10));
98 if (!num_bytes)
99 return Status::FromError(num_bytes.takeError());
100 if (*num_bytes != sizeof(protocol_info))
102 "Write(WSAPROTOCOL_INFO) failed: wrote {0}/{1} bytes", *num_bytes,
103 sizeof(protocol_info));
104#endif
105 return Status();
106}
107
109#ifdef _WIN32
111 // Read WSAPROTOCOL_INFO from the parent process and create NativeSocket.
112 WSAPROTOCOL_INFO protocol_info;
113 {
114 Pipe socket_pipe(fd, LLDB_INVALID_PIPE);
115 llvm::Expected<size_t> num_bytes = socket_pipe.Read(
116 &protocol_info, sizeof(protocol_info), std::chrono::seconds(10));
117 if (!num_bytes)
118 return Status::FromError(num_bytes.takeError());
119 if (*num_bytes != sizeof(protocol_info)) {
121 "Read(WSAPROTOCOL_INFO) failed: read {0}/{1} bytes", *num_bytes,
122 sizeof(protocol_info));
123 }
124 }
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());
130 }
131 return Status();
132#else
133 socket = fd;
134 return Status();
135#endif
136}
137
142
144 {"tcp", Socket::ProtocolTcp},
145 {"udp", Socket::ProtocolUdp},
147 {"unix-abstract", Socket::ProtocolUnixAbstract},
148};
149
150const char *
152 for (auto s : socket_schemes) {
153 if (s.m_protocol == protocol)
154 return s.m_scheme;
155 }
156 return nullptr;
157}
158
159bool Socket::FindProtocolByScheme(const char *scheme,
160 Socket::SocketProtocol &protocol) {
161 for (auto s : socket_schemes) {
162 if (!strcmp(s.m_scheme, scheme)) {
163 protocol = s.m_protocol;
164 return true;
165 }
166 }
167 return false;
168}
169
170Socket::Socket(SocketProtocol protocol, bool should_close)
171 : IOObject(eFDTypeSocket), m_protocol(protocol),
173
175
176llvm::Error Socket::Initialize() {
177#if defined(_WIN32)
178 auto wVersion = WINSOCK_VERSION;
179 WSADATA wsaData;
180 int err = ::WSAStartup(wVersion, &wsaData);
181 if (err == 0) {
182 if (wsaData.wVersion < wVersion) {
183 WSACleanup();
184 return llvm::createStringError("WSASock version is not expected");
185 }
186 } else {
187 return llvm::errorCodeToError(llvm::mapWindowsError(::WSAGetLastError()));
188 }
189#endif
190
191 return llvm::Error::success();
192}
193
195#if defined(_WIN32)
196 ::WSACleanup();
197#endif
198}
199
200std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
201 Status &error) {
202 error.Clear();
203
204 const bool should_close = true;
205 std::unique_ptr<Socket> socket_up;
206 switch (protocol) {
207 case ProtocolTcp:
208 socket_up = std::make_unique<TCPSocket>(should_close);
209 break;
210 case ProtocolUdp:
211 socket_up = std::make_unique<UDPSocket>(should_close);
212 break;
214#if LLDB_ENABLE_POSIX
215 socket_up = std::make_unique<DomainSocket>(should_close);
216#else
218 "Unix domain sockets are not supported on this platform.");
219#endif
220 break;
222#ifdef __linux__
223 socket_up = std::make_unique<AbstractSocket>();
224#else
226 "Abstract domain sockets are not supported on this platform.");
227#endif
228 break;
229 }
230
231 if (error.Fail())
232 socket_up.reset();
233
234 return socket_up;
235}
236
237llvm::Expected<Socket::Pair>
238Socket::CreatePair(std::optional<SocketProtocol> protocol) {
239 constexpr SocketProtocol kBestProtocol =
240 LLDB_ENABLE_POSIX ? ProtocolUnixDomain : ProtocolTcp;
241 switch (protocol.value_or(kBestProtocol)) {
242 case ProtocolTcp:
243 return TCPSocket::CreatePair();
245#if LLDB_ENABLE_POSIX
247#else
248 return llvm::createStringError("unsupported protocol");
249#endif
251#if LLDB_ENABLE_POSIX
253#else
254 return llvm::createStringError("unsupported protocol");
255#endif
256 default:
257 return llvm::createStringError("unsupported protocol");
258 }
259}
260
261llvm::Expected<std::unique_ptr<Socket>>
262Socket::TcpConnect(llvm::StringRef host_and_port) {
264 LLDB_LOG(log, "host_and_port = {0}", host_and_port);
265
267 std::unique_ptr<Socket> connect_socket = Create(ProtocolTcp, error);
268 if (error.Fail())
269 return error.ToError();
270
271 error = connect_socket->Connect(host_and_port);
272 if (error.Success())
273 return std::move(connect_socket);
274
275 return error.ToError();
276}
277
278llvm::Expected<std::unique_ptr<TCPSocket>>
279Socket::TcpListen(llvm::StringRef host_and_port, int backlog) {
281 LLDB_LOG(log, "host_and_port = {0}", host_and_port);
282
283 std::unique_ptr<TCPSocket> listen_socket(
284 new TCPSocket(/*should_close=*/true));
285
286 Status error = listen_socket->Listen(host_and_port, backlog);
287 if (error.Fail())
288 return error.ToError();
289
290 return std::move(listen_socket);
291}
292
293llvm::Expected<std::unique_ptr<UDPSocket>>
294Socket::UdpConnect(llvm::StringRef host_and_port) {
295 return UDPSocket::CreateConnected(host_and_port);
296}
297
298llvm::Expected<Socket::HostAndPort>
299Socket::DecodeHostAndPort(llvm::StringRef host_and_port) {
300 // This regex parses host:port combinations, supporting:
301 // - IPv4 sockets (e.g., "127.0.0.1:8080")
302 // - IPv6 sockets with host part in square brackets (e.g., "[::1]:80")
303 // Group 1: Address (IPv4, hostname, or IPv6 in [])
304 // Group 2: Port number (digits only)
305 static llvm::Regex g_regex("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+$)");
306 HostAndPort ret;
307 llvm::SmallVector<llvm::StringRef, 3> matches;
308 if (g_regex.match(host_and_port, &matches)) {
309 ret.hostname = matches[1].str();
310 // IPv6 addresses are wrapped in [] when specified with ports
311 if (ret.hostname.front() == '[' && ret.hostname.back() == ']')
312 ret.hostname = ret.hostname.substr(1, ret.hostname.size() - 2);
313 if (to_integer(matches[2], ret.port, 10))
314 return ret;
315 }
316
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());
322}
323
327
328Status Socket::Read(void *buf, size_t &num_bytes) {
330 int bytes_received = 0;
331 do {
332 bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
333 } while (bytes_received < 0 && IsInterrupted());
334
335 if (bytes_received < 0) {
337 num_bytes = 0;
338 } else
339 num_bytes = bytes_received;
340
342 "%p Socket::Read() (socket = %" PRIu64
343 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
344 " (error = %s)",
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());
348
349 return error;
350}
351
352Status Socket::Write(const void *buf, size_t &num_bytes) {
353 const size_t src_len = num_bytes;
355 int bytes_sent = 0;
356 do {
357 bytes_sent = Send(buf, num_bytes);
358 } while (bytes_sent < 0 && IsInterrupted());
359
360 if (bytes_sent < 0) {
362 num_bytes = 0;
363 } else
364 num_bytes = bytes_sent;
365
367 "%p Socket::Write() (socket = %" PRIu64
368 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
369 " (error = %s)",
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),
372 error.AsCString());
373
374 return error;
375}
376
379 if (!IsValid() || !m_should_close_fd)
380 return error;
381
383 LLDB_LOGF(log, "%p Socket::Close (fd = %" PRIu64 ")",
384 static_cast<void *>(this), static_cast<uint64_t>(m_socket));
385
386 bool success = CloseSocket(m_socket) == 0;
387 // A reference to a FD was passed in, set it to an invalid value
389 if (!success) {
391 }
392
393 return error;
394}
395
396int Socket::GetOption(NativeSocket sockfd, int level, int option_name,
397 int &option_value) {
398 get_socket_option_arg_type option_value_p =
399 reinterpret_cast<get_socket_option_arg_type>(&option_value);
400 socklen_t option_value_size = sizeof(int);
401 return ::getsockopt(sockfd, level, option_name, option_value_p,
402 &option_value_size);
403}
404
405int Socket::SetOption(NativeSocket sockfd, int level, int option_name,
406 int option_value) {
407 set_socket_option_arg_type option_value_p =
408 reinterpret_cast<set_socket_option_arg_type>(&option_value);
409 return ::setsockopt(sockfd, level, option_name, option_value_p,
410 sizeof(option_value));
411}
412
413ssize_t Socket::Send(const void *buf, const size_t num_bytes) {
414 int flags = 0;
415#if defined(MSG_NOSIGNAL)
416 flags |= MSG_NOSIGNAL;
417#endif
418 return ::send(m_socket, static_cast<const char *>(buf), num_bytes, flags);
419}
420
422#if defined(_WIN32)
423 error = Status(::WSAGetLastError(), lldb::eErrorTypeWin32);
424#else
426#endif
427}
428
430 std::error_code EC;
431#ifdef _WIN32
432 EC = llvm::mapWindowsError(WSAGetLastError());
433#else
434 EC = std::error_code(errno, std::generic_category());
435#endif
436 return EC;
437}
438
440#ifdef _WIN32
441 return ::closesocket(sockfd);
442#else
443 return ::close(sockfd);
444#endif
445}
446
447NativeSocket Socket::CreateSocket(const int domain, const int type,
448 const int protocol, Status &error) {
449 error.Clear();
450 auto socket_type = type;
451#ifdef SOCK_CLOEXEC
452 socket_type |= SOCK_CLOEXEC;
453#endif
454 auto sock = ::socket(domain, socket_type, protocol);
455 if (sock == kInvalidSocketValue)
457
458#if defined(SO_NOSIGPIPE)
459 if (Socket::SetOption(sock, SOL_SOCKET, SO_NOSIGPIPE, 1) == -1)
460 LLDB_LOG(GetLog(LLDBLog::Host), "failed to set SO_NOSIGPIPE on fd {0}: {1}",
461 sock, llvm::sys::StrError());
462#endif
463
464 return sock;
465}
466
468 socket = nullptr;
469 MainLoop accept_loop;
470 llvm::Expected<std::vector<MainLoopBase::ReadHandleUP>> expected_handles =
471 Accept(accept_loop,
472 [&accept_loop, &socket](std::unique_ptr<Socket> sock) {
473 socket = sock.release();
474 accept_loop.RequestTermination();
475 });
476 if (!expected_handles)
477 return Status::FromError(expected_handles.takeError());
478 if (timeout) {
479 accept_loop.AddCallback(
480 [](MainLoopBase &loop) { loop.RequestTermination(); }, *timeout);
481 }
482 if (Status status = accept_loop.Run(); status.Fail())
483 return status;
484 if (socket)
485 return Status();
486 return Status(std::make_error_code(std::errc::timed_out));
487}
488
489NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
490 socklen_t *addrlen, Status &error) {
491 error.Clear();
492#if defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
493 int flags = SOCK_CLOEXEC;
494 NativeSocket fd = llvm::sys::RetryAfterSignal(
495 static_cast<NativeSocket>(-1), ::accept4, sockfd, addr, addrlen, flags);
496#else
497 NativeSocket fd = llvm::sys::RetryAfterSignal(
498 static_cast<NativeSocket>(-1), ::accept, sockfd, addr, addrlen);
499#endif
500 if (fd == kInvalidSocketValue)
502 return fd;
503}
504
505llvm::raw_ostream &lldb_private::operator<<(llvm::raw_ostream &OS,
506 const Socket::HostAndPort &HP) {
507 return OS << '[' << HP.hostname << ']' << ':' << HP.port;
508}
509
510std::optional<Socket::ProtocolModePair>
511Socket::GetProtocolAndMode(llvm::StringRef scheme) {
512 // Keep in sync with ConnectionFileDescriptor::Connect.
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);
533}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:376
#define LLDB_LOGF(log,...)
Definition Log.h:390
static bool IsInterrupted()
Definition Socket.cpp:58
void * get_socket_option_arg_type
Definition Socket.cpp:53
const void * set_socket_option_arg_type
Definition Socket.cpp:52
static SocketScheme socket_schemes[]
Definition Socket.cpp:143
static llvm::Expected< Pair > CreatePair()
Create a connected pair of domain sockets using socketpair(2).
IOObject(FDType type)
Definition IOObject.h:33
lldb::file_t WaitableHandle
Definition IOObject.h:29
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
Definition Socket.h:50
SharedSocket(const Socket *socket, Status &error)
Definition Socket.cpp:66
Status CompleteSending(lldb::pid_t child_pid)
Definition Socket.cpp:83
static Status GetNativeSocket(shared_fd_t fd, NativeSocket &socket)
Definition Socket.cpp:108
static std::unique_ptr< Socket > Create(const SocketProtocol protocol, Status &error)
Definition Socket.cpp:200
Status Read(void *buf, size_t &num_bytes) override
Definition Socket.cpp:328
NativeSocket GetNativeSocket() const
Definition Socket.h:151
static const NativeSocket kInvalidSocketValue
Definition Socket.h:95
WaitableHandle GetWaitableHandle() override
Definition Socket.cpp:324
SocketProtocol m_protocol
Definition Socket.h:186
std::pair< SocketProtocol, SocketMode > ProtocolModePair
Definition Socket.h:91
static llvm::Expected< std::unique_ptr< UDPSocket > > UdpConnect(llvm::StringRef host_and_port)
Definition Socket.cpp:294
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)
Definition Socket.cpp:447
static int GetOption(NativeSocket sockfd, int level, int option_name, int &option_value)
Definition Socket.cpp:396
static llvm::Expected< HostAndPort > DecodeHostAndPort(llvm::StringRef host_and_port)
Definition Socket.cpp:299
static NativeSocket AcceptSocket(NativeSocket sockfd, struct sockaddr *addr, socklen_t *addrlen, Status &error)
Definition Socket.cpp:489
static bool FindProtocolByScheme(const char *scheme, SocketProtocol &protocol)
Definition Socket.cpp:159
bool IsValid() const override
Definition Socket.h:159
static Status GetLastError()
Definition Socket.cpp:429
static llvm::Expected< std::unique_ptr< Socket > > TcpConnect(llvm::StringRef host_and_port)
Definition Socket.cpp:262
static void SetLastError(Status &error)
Definition Socket.cpp:421
static llvm::Error Initialize()
Definition Socket.cpp:176
static int CloseSocket(NativeSocket sockfd)
Definition Socket.cpp:439
static const char * FindSchemeByProtocol(const SocketProtocol protocol)
Definition Socket.cpp:151
NativeSocket m_socket
Definition Socket.h:187
static int SetOption(NativeSocket sockfd, int level, int option_name, int option_value)
Definition Socket.cpp:405
virtual ssize_t Send(const void *buf, const size_t num_bytes)
Definition Socket.cpp:413
Status Write(const void *buf, size_t &num_bytes) override
Definition Socket.cpp:352
~Socket() override
Definition Socket.cpp:174
static llvm::Expected< std::unique_ptr< TCPSocket > > TcpListen(llvm::StringRef host_and_port, int backlog=5)
Definition Socket.cpp:279
Status Close() override
Definition Socket.cpp:377
static std::optional< ProtocolModePair > GetProtocolAndMode(llvm::StringRef scheme)
Definition Socket.cpp:511
static llvm::Expected< Pair > CreatePair(std::optional< SocketProtocol > protocol=std::nullopt)
Definition Socket.cpp:238
Socket(SocketProtocol protocol, bool should_close)
Definition Socket.cpp:170
static void Terminate()
Definition Socket.cpp:194
An error handling class.
Definition Status.h:118
static Status FromErrno()
Set the current error to errno.
Definition Status.cpp:299
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
static llvm::Expected< Pair > CreatePair()
Definition TCPSocket.cpp:55
static llvm::Expected< std::unique_ptr< UDPSocket > > CreateConnected(llvm::StringRef name)
Definition UDPSocket.cpp:51
#define LLDB_INVALID_PIPE
Definition lldb-types.h:70
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.
Definition Log.h:339
Stream & operator<<(Stream &s, const Mangled &obj)
NativeSocket shared_fd_t
Definition Socket.h:42
PipePosix Pipe
Definition Pipe.h:20
MainLoopPosix MainLoop
Definition MainLoop.h:20
int NativeSocket
Definition Socket.h:41
@ eErrorTypeWin32
Standard Win32 error codes.
uint64_t pid_t
Definition lldb-types.h:83
const Socket::SocketProtocol m_protocol
Definition Socket.cpp:140
const char * m_scheme
Definition Socket.cpp:139