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"
17#include "lldb/Utility/Log.h"
18
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/Support/Errno.h"
22#include "llvm/Support/Error.h"
23#include "llvm/Support/Regex.h"
24#include "llvm/Support/WindowsError.h"
25
26#if LLDB_ENABLE_POSIX
28
29#include <arpa/inet.h>
30#include <netdb.h>
31#include <netinet/in.h>
32#include <netinet/tcp.h>
33#include <sys/socket.h>
34#include <sys/un.h>
35#include <unistd.h>
36#endif
37
38#ifdef __linux__
40#endif
41
42#ifdef __ANDROID__
43#include <arpa/inet.h>
44#include <asm-generic/errno-base.h>
45#include <cerrno>
46#include <fcntl.h>
47#include <linux/tcp.h>
48#include <sys/syscall.h>
49#include <unistd.h>
50#endif // __ANDROID__
51
52using namespace lldb;
53using namespace lldb_private;
54
55#if defined(_WIN32)
56typedef const char *set_socket_option_arg_type;
57typedef char *get_socket_option_arg_type;
58const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
59#else // #if defined(_WIN32)
60typedef const void *set_socket_option_arg_type;
63#endif // #if defined(_WIN32)
64
65static bool IsInterrupted() {
66#if defined(_WIN32)
67 return ::WSAGetLastError() == WSAEINTR;
68#else
69 return errno == EINTR;
70#endif
71}
72
74 const char *m_scheme;
76};
77
79 {"tcp", Socket::ProtocolTcp},
80 {"udp", Socket::ProtocolUdp},
82 {"unix-abstract", Socket::ProtocolUnixAbstract},
83};
84
85const char *
87 for (auto s : socket_schemes) {
88 if (s.m_protocol == protocol)
89 return s.m_scheme;
90 }
91 return nullptr;
92}
93
94bool Socket::FindProtocolByScheme(const char *scheme,
95 Socket::SocketProtocol &protocol) {
96 for (auto s : socket_schemes) {
97 if (!strcmp(s.m_scheme, scheme)) {
98 protocol = s.m_protocol;
99 return true;
100 }
101 }
102 return false;
103}
104
105Socket::Socket(SocketProtocol protocol, bool should_close,
106 bool child_processes_inherit)
107 : IOObject(eFDTypeSocket), m_protocol(protocol),
108 m_socket(kInvalidSocketValue),
109 m_child_processes_inherit(child_processes_inherit),
110 m_should_close_fd(should_close) {}
111
113
114llvm::Error Socket::Initialize() {
115#if defined(_WIN32)
116 auto wVersion = WINSOCK_VERSION;
117 WSADATA wsaData;
118 int err = ::WSAStartup(wVersion, &wsaData);
119 if (err == 0) {
120 if (wsaData.wVersion < wVersion) {
121 WSACleanup();
122 return llvm::createStringError("WSASock version is not expected.");
123 }
124 } else {
125 return llvm::errorCodeToError(llvm::mapWindowsError(::WSAGetLastError()));
126 }
127#endif
128
129 return llvm::Error::success();
130}
131
133#if defined(_WIN32)
134 ::WSACleanup();
135#endif
136}
137
138std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
139 bool child_processes_inherit,
140 Status &error) {
141 error.Clear();
142
143 std::unique_ptr<Socket> socket_up;
144 switch (protocol) {
145 case ProtocolTcp:
146 socket_up =
147 std::make_unique<TCPSocket>(true, child_processes_inherit);
148 break;
149 case ProtocolUdp:
150 socket_up =
151 std::make_unique<UDPSocket>(true, child_processes_inherit);
152 break;
154#if LLDB_ENABLE_POSIX
155 socket_up =
156 std::make_unique<DomainSocket>(true, child_processes_inherit);
157#else
158 error.SetErrorString(
159 "Unix domain sockets are not supported on this platform.");
160#endif
161 break;
163#ifdef __linux__
164 socket_up =
165 std::make_unique<AbstractSocket>(child_processes_inherit);
166#else
167 error.SetErrorString(
168 "Abstract domain sockets are not supported on this platform.");
169#endif
170 break;
171 }
172
173 if (error.Fail())
174 socket_up.reset();
175
176 return socket_up;
177}
178
179llvm::Expected<std::unique_ptr<Socket>>
180Socket::TcpConnect(llvm::StringRef host_and_port,
181 bool child_processes_inherit) {
183 LLDB_LOG(log, "host_and_port = {0}", host_and_port);
184
186 std::unique_ptr<Socket> connect_socket(
187 Create(ProtocolTcp, child_processes_inherit, error));
188 if (error.Fail())
189 return error.ToError();
190
191 error = connect_socket->Connect(host_and_port);
192 if (error.Success())
193 return std::move(connect_socket);
194
195 return error.ToError();
196}
197
198llvm::Expected<std::unique_ptr<TCPSocket>>
199Socket::TcpListen(llvm::StringRef host_and_port, bool child_processes_inherit,
200 int backlog) {
202 LLDB_LOG(log, "host_and_port = {0}", host_and_port);
203
204 std::unique_ptr<TCPSocket> listen_socket(
205 new TCPSocket(true, child_processes_inherit));
206
207 Status error = listen_socket->Listen(host_and_port, backlog);
208 if (error.Fail())
209 return error.ToError();
210
211 return std::move(listen_socket);
212}
213
214llvm::Expected<std::unique_ptr<UDPSocket>>
215Socket::UdpConnect(llvm::StringRef host_and_port,
216 bool child_processes_inherit) {
217 return UDPSocket::Connect(host_and_port, child_processes_inherit);
218}
219
220llvm::Expected<Socket::HostAndPort> Socket::DecodeHostAndPort(llvm::StringRef host_and_port) {
221 static llvm::Regex g_regex("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)");
222 HostAndPort ret;
223 llvm::SmallVector<llvm::StringRef, 3> matches;
224 if (g_regex.match(host_and_port, &matches)) {
225 ret.hostname = matches[1].str();
226 // IPv6 addresses are wrapped in [] when specified with ports
227 if (ret.hostname.front() == '[' && ret.hostname.back() == ']')
228 ret.hostname = ret.hostname.substr(1, ret.hostname.size() - 2);
229 if (to_integer(matches[2], ret.port, 10))
230 return ret;
231 } else {
232 // If this was unsuccessful, then check if it's simply an unsigned 16-bit
233 // integer, representing a port with an empty host.
234 if (to_integer(host_and_port, ret.port, 10))
235 return ret;
236 }
237
238 return llvm::createStringError(llvm::inconvertibleErrorCode(),
239 "invalid host:port specification: '%s'",
240 host_and_port.str().c_str());
241}
242
244 // TODO: On Windows, use WSAEventSelect
245 return m_socket;
246}
247
248Status Socket::Read(void *buf, size_t &num_bytes) {
250 int bytes_received = 0;
251 do {
252 bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
253 } while (bytes_received < 0 && IsInterrupted());
254
255 if (bytes_received < 0) {
257 num_bytes = 0;
258 } else
259 num_bytes = bytes_received;
260
262 if (log) {
263 LLDB_LOGF(log,
264 "%p Socket::Read() (socket = %" PRIu64
265 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
266 " (error = %s)",
267 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
268 static_cast<uint64_t>(num_bytes),
269 static_cast<int64_t>(bytes_received), error.AsCString());
270 }
271
272 return error;
273}
274
275Status Socket::Write(const void *buf, size_t &num_bytes) {
276 const size_t src_len = num_bytes;
278 int bytes_sent = 0;
279 do {
280 bytes_sent = Send(buf, num_bytes);
281 } while (bytes_sent < 0 && IsInterrupted());
282
283 if (bytes_sent < 0) {
285 num_bytes = 0;
286 } else
287 num_bytes = bytes_sent;
288
290 if (log) {
291 LLDB_LOGF(log,
292 "%p Socket::Write() (socket = %" PRIu64
293 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
294 " (error = %s)",
295 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
296 static_cast<uint64_t>(src_len),
297 static_cast<int64_t>(bytes_sent), error.AsCString());
298 }
299
300 return error;
301}
302
305 if (!IsValid() || !m_should_close_fd)
306 return error;
307
309 LLDB_LOGF(log, "%p Socket::Close (fd = %" PRIu64 ")",
310 static_cast<void *>(this), static_cast<uint64_t>(m_socket));
311
312#if defined(_WIN32)
313 bool success = closesocket(m_socket) == 0;
314#else
315 bool success = ::close(m_socket) == 0;
316#endif
317 // A reference to a FD was passed in, set it to an invalid value
319 if (!success) {
321 }
322
323 return error;
324}
325
326int Socket::GetOption(int level, int option_name, int &option_value) {
327 get_socket_option_arg_type option_value_p =
328 reinterpret_cast<get_socket_option_arg_type>(&option_value);
329 socklen_t option_value_size = sizeof(int);
330 return ::getsockopt(m_socket, level, option_name, option_value_p,
331 &option_value_size);
332}
333
334int Socket::SetOption(int level, int option_name, int option_value) {
335 set_socket_option_arg_type option_value_p =
336 reinterpret_cast<get_socket_option_arg_type>(&option_value);
337 return ::setsockopt(m_socket, level, option_name, option_value_p,
338 sizeof(option_value));
339}
340
341size_t Socket::Send(const void *buf, const size_t num_bytes) {
342 return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
343}
344
346#if defined(_WIN32)
347 error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
348#else
349 error.SetErrorToErrno();
350#endif
351}
352
353NativeSocket Socket::CreateSocket(const int domain, const int type,
354 const int protocol,
355 bool child_processes_inherit, Status &error) {
356 error.Clear();
357 auto socket_type = type;
358#ifdef SOCK_CLOEXEC
359 if (!child_processes_inherit)
360 socket_type |= SOCK_CLOEXEC;
361#endif
362 auto sock = ::socket(domain, socket_type, protocol);
363 if (sock == kInvalidSocketValue)
365
366 return sock;
367}
368
369NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
370 socklen_t *addrlen,
371 bool child_processes_inherit, Status &error) {
372 error.Clear();
373#if defined(ANDROID_USE_ACCEPT_WORKAROUND)
374 // Hack:
375 // This enables static linking lldb-server to an API 21 libc, but still
376 // having it run on older devices. It is necessary because API 21 libc's
377 // implementation of accept() uses the accept4 syscall(), which is not
378 // available in older kernels. Using an older libc would fix this issue, but
379 // introduce other ones, as the old libraries were quite buggy.
380 int fd = syscall(__NR_accept, sockfd, addr, addrlen);
381 if (fd >= 0 && !child_processes_inherit) {
382 int flags = ::fcntl(fd, F_GETFD);
383 if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
384 return fd;
386 close(fd);
387 }
388 return fd;
389#elif defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
390 int flags = 0;
391 if (!child_processes_inherit) {
392 flags |= SOCK_CLOEXEC;
393 }
394 NativeSocket fd = llvm::sys::RetryAfterSignal(
395 static_cast<NativeSocket>(-1), ::accept4, sockfd, addr, addrlen, flags);
396#else
397 NativeSocket fd = llvm::sys::RetryAfterSignal(
398 static_cast<NativeSocket>(-1), ::accept, sockfd, addr, addrlen);
399#endif
400 if (fd == kInvalidSocketValue)
402 return fd;
403}
404
405llvm::raw_ostream &lldb_private::operator<<(llvm::raw_ostream &OS,
406 const Socket::HostAndPort &HP) {
407 return OS << '[' << HP.hostname << ']' << ':' << HP.port;
408}
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:359
#define LLDB_LOGF(log,...)
Definition: Log.h:366
static bool IsInterrupted()
Definition: Socket.cpp:65
void * get_socket_option_arg_type
Definition: Socket.cpp:61
const void * set_socket_option_arg_type
Definition: Socket.cpp:60
static SocketScheme socket_schemes[]
Definition: Socket.cpp:78
Status Read(void *buf, size_t &num_bytes) override
Definition: Socket.cpp:248
static llvm::Expected< std::unique_ptr< UDPSocket > > UdpConnect(llvm::StringRef host_and_port, bool child_processes_inherit)
Definition: Socket.cpp:215
static const NativeSocket kInvalidSocketValue
Definition: Socket.h:59
WaitableHandle GetWaitableHandle() override
Definition: Socket.cpp:243
static NativeSocket CreateSocket(const int domain, const int type, const int protocol, bool child_processes_inherit, Status &error)
Definition: Socket.cpp:353
virtual size_t Send(const void *buf, const size_t num_bytes)
Definition: Socket.cpp:341
int SetOption(int level, int option_name, int option_value)
Definition: Socket.cpp:334
static llvm::Expected< HostAndPort > DecodeHostAndPort(llvm::StringRef host_and_port)
Definition: Socket.cpp:220
int GetOption(int level, int option_name, int &option_value)
Definition: Socket.cpp:326
Socket(SocketProtocol protocol, bool should_close, bool m_child_process_inherit)
Definition: Socket.cpp:105
static bool FindProtocolByScheme(const char *scheme, SocketProtocol &protocol)
Definition: Socket.cpp:94
static NativeSocket AcceptSocket(NativeSocket sockfd, struct sockaddr *addr, socklen_t *addrlen, bool child_processes_inherit, Status &error)
Definition: Socket.cpp:369
bool IsValid() const override
Definition: Socket.h:102
static void SetLastError(Status &error)
Definition: Socket.cpp:345
static llvm::Error Initialize()
Definition: Socket.cpp:114
bool m_should_close_fd
Definition: Socket.h:128
static const char * FindSchemeByProtocol(const SocketProtocol protocol)
Definition: Socket.cpp:86
NativeSocket m_socket
Definition: Socket.h:126
static llvm::Expected< std::unique_ptr< Socket > > TcpConnect(llvm::StringRef host_and_port, bool child_processes_inherit)
Definition: Socket.cpp:180
Status Write(const void *buf, size_t &num_bytes) override
Definition: Socket.cpp:275
~Socket() override
Definition: Socket.cpp:112
Status Close() override
Definition: Socket.cpp:303
static std::unique_ptr< Socket > Create(const SocketProtocol protocol, bool child_processes_inherit, Status &error)
Definition: Socket.cpp:138
static llvm::Expected< std::unique_ptr< TCPSocket > > TcpListen(llvm::StringRef host_and_port, bool child_processes_inherit, int backlog=5)
Definition: Socket.cpp:199
static void Terminate()
Definition: Socket.cpp:132
An error handling class.
Definition: Status.h:44
static llvm::Expected< std::unique_ptr< UDPSocket > > Connect(llvm::StringRef name, bool child_processes_inherit)
Definition: UDPSocket.cpp:55
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:331
Stream & operator<<(Stream &s, const Mangled &obj)
int NativeSocket
Definition: Socket.h:36
Definition: SBAddress.h:15
@ eErrorTypeWin32
Standard Win32 error codes.
const Socket::SocketProtocol m_protocol
Definition: Socket.cpp:75
const char * m_scheme
Definition: Socket.cpp:74