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
73Socket::Socket(SocketProtocol protocol, bool should_close,
74 bool child_processes_inherit)
75 : IOObject(eFDTypeSocket), m_protocol(protocol),
76 m_socket(kInvalidSocketValue),
77 m_child_processes_inherit(child_processes_inherit),
78 m_should_close_fd(should_close) {}
79
81
82llvm::Error Socket::Initialize() {
83#if defined(_WIN32)
84 auto wVersion = WINSOCK_VERSION;
85 WSADATA wsaData;
86 int err = ::WSAStartup(wVersion, &wsaData);
87 if (err == 0) {
88 if (wsaData.wVersion < wVersion) {
89 WSACleanup();
90 return llvm::make_error<llvm::StringError>(
91 "WSASock version is not expected.", llvm::inconvertibleErrorCode());
92 }
93 } else {
94 return llvm::errorCodeToError(llvm::mapWindowsError(::WSAGetLastError()));
95 }
96#endif
97
98 return llvm::Error::success();
99}
100
102#if defined(_WIN32)
103 ::WSACleanup();
104#endif
105}
106
107std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
108 bool child_processes_inherit,
109 Status &error) {
110 error.Clear();
111
112 std::unique_ptr<Socket> socket_up;
113 switch (protocol) {
114 case ProtocolTcp:
115 socket_up =
116 std::make_unique<TCPSocket>(true, child_processes_inherit);
117 break;
118 case ProtocolUdp:
119 socket_up =
120 std::make_unique<UDPSocket>(true, child_processes_inherit);
121 break;
123#if LLDB_ENABLE_POSIX
124 socket_up =
125 std::make_unique<DomainSocket>(true, child_processes_inherit);
126#else
127 error.SetErrorString(
128 "Unix domain sockets are not supported on this platform.");
129#endif
130 break;
132#ifdef __linux__
133 socket_up =
134 std::make_unique<AbstractSocket>(child_processes_inherit);
135#else
136 error.SetErrorString(
137 "Abstract domain sockets are not supported on this platform.");
138#endif
139 break;
140 }
141
142 if (error.Fail())
143 socket_up.reset();
144
145 return socket_up;
146}
147
148llvm::Expected<std::unique_ptr<Socket>>
149Socket::TcpConnect(llvm::StringRef host_and_port,
150 bool child_processes_inherit) {
152 LLDB_LOG(log, "host_and_port = {0}", host_and_port);
153
155 std::unique_ptr<Socket> connect_socket(
156 Create(ProtocolTcp, child_processes_inherit, error));
157 if (error.Fail())
158 return error.ToError();
159
160 error = connect_socket->Connect(host_and_port);
161 if (error.Success())
162 return std::move(connect_socket);
163
164 return error.ToError();
165}
166
167llvm::Expected<std::unique_ptr<TCPSocket>>
168Socket::TcpListen(llvm::StringRef host_and_port, bool child_processes_inherit,
169 int backlog) {
171 LLDB_LOG(log, "host_and_port = {0}", host_and_port);
172
173 std::unique_ptr<TCPSocket> listen_socket(
174 new TCPSocket(true, child_processes_inherit));
175
176 Status error = listen_socket->Listen(host_and_port, backlog);
177 if (error.Fail())
178 return error.ToError();
179
180 return std::move(listen_socket);
181}
182
183llvm::Expected<std::unique_ptr<UDPSocket>>
184Socket::UdpConnect(llvm::StringRef host_and_port,
185 bool child_processes_inherit) {
186 return UDPSocket::Connect(host_and_port, child_processes_inherit);
187}
188
189llvm::Expected<Socket::HostAndPort> Socket::DecodeHostAndPort(llvm::StringRef host_and_port) {
190 static llvm::Regex g_regex("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)");
191 HostAndPort ret;
192 llvm::SmallVector<llvm::StringRef, 3> matches;
193 if (g_regex.match(host_and_port, &matches)) {
194 ret.hostname = matches[1].str();
195 // IPv6 addresses are wrapped in [] when specified with ports
196 if (ret.hostname.front() == '[' && ret.hostname.back() == ']')
197 ret.hostname = ret.hostname.substr(1, ret.hostname.size() - 2);
198 if (to_integer(matches[2], ret.port, 10))
199 return ret;
200 } else {
201 // If this was unsuccessful, then check if it's simply an unsigned 16-bit
202 // integer, representing a port with an empty host.
203 if (to_integer(host_and_port, ret.port, 10))
204 return ret;
205 }
206
207 return llvm::createStringError(llvm::inconvertibleErrorCode(),
208 "invalid host:port specification: '%s'",
209 host_and_port.str().c_str());
210}
211
213 // TODO: On Windows, use WSAEventSelect
214 return m_socket;
215}
216
217Status Socket::Read(void *buf, size_t &num_bytes) {
219 int bytes_received = 0;
220 do {
221 bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
222 } while (bytes_received < 0 && IsInterrupted());
223
224 if (bytes_received < 0) {
226 num_bytes = 0;
227 } else
228 num_bytes = bytes_received;
229
231 if (log) {
232 LLDB_LOGF(log,
233 "%p Socket::Read() (socket = %" PRIu64
234 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
235 " (error = %s)",
236 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
237 static_cast<uint64_t>(num_bytes),
238 static_cast<int64_t>(bytes_received), error.AsCString());
239 }
240
241 return error;
242}
243
244Status Socket::Write(const void *buf, size_t &num_bytes) {
245 const size_t src_len = num_bytes;
247 int bytes_sent = 0;
248 do {
249 bytes_sent = Send(buf, num_bytes);
250 } while (bytes_sent < 0 && IsInterrupted());
251
252 if (bytes_sent < 0) {
254 num_bytes = 0;
255 } else
256 num_bytes = bytes_sent;
257
259 if (log) {
260 LLDB_LOGF(log,
261 "%p Socket::Write() (socket = %" PRIu64
262 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
263 " (error = %s)",
264 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
265 static_cast<uint64_t>(src_len),
266 static_cast<int64_t>(bytes_sent), error.AsCString());
267 }
268
269 return error;
270}
271
274 if (!IsValid() || !m_should_close_fd)
275 return error;
276
278 LLDB_LOGF(log, "%p Socket::Close (fd = %" PRIu64 ")",
279 static_cast<void *>(this), static_cast<uint64_t>(m_socket));
280
281#if defined(_WIN32)
282 bool success = closesocket(m_socket) == 0;
283#else
284 bool success = ::close(m_socket) == 0;
285#endif
286 // A reference to a FD was passed in, set it to an invalid value
288 if (!success) {
290 }
291
292 return error;
293}
294
295int Socket::GetOption(int level, int option_name, int &option_value) {
296 get_socket_option_arg_type option_value_p =
297 reinterpret_cast<get_socket_option_arg_type>(&option_value);
298 socklen_t option_value_size = sizeof(int);
299 return ::getsockopt(m_socket, level, option_name, option_value_p,
300 &option_value_size);
301}
302
303int Socket::SetOption(int level, int option_name, int option_value) {
304 set_socket_option_arg_type option_value_p =
305 reinterpret_cast<get_socket_option_arg_type>(&option_value);
306 return ::setsockopt(m_socket, level, option_name, option_value_p,
307 sizeof(option_value));
308}
309
310size_t Socket::Send(const void *buf, const size_t num_bytes) {
311 return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
312}
313
315#if defined(_WIN32)
316 error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
317#else
318 error.SetErrorToErrno();
319#endif
320}
321
322NativeSocket Socket::CreateSocket(const int domain, const int type,
323 const int protocol,
324 bool child_processes_inherit, Status &error) {
325 error.Clear();
326 auto socket_type = type;
327#ifdef SOCK_CLOEXEC
328 if (!child_processes_inherit)
329 socket_type |= SOCK_CLOEXEC;
330#endif
331 auto sock = ::socket(domain, socket_type, protocol);
332 if (sock == kInvalidSocketValue)
334
335 return sock;
336}
337
338NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
339 socklen_t *addrlen,
340 bool child_processes_inherit, Status &error) {
341 error.Clear();
342#if defined(ANDROID_USE_ACCEPT_WORKAROUND)
343 // Hack:
344 // This enables static linking lldb-server to an API 21 libc, but still
345 // having it run on older devices. It is necessary because API 21 libc's
346 // implementation of accept() uses the accept4 syscall(), which is not
347 // available in older kernels. Using an older libc would fix this issue, but
348 // introduce other ones, as the old libraries were quite buggy.
349 int fd = syscall(__NR_accept, sockfd, addr, addrlen);
350 if (fd >= 0 && !child_processes_inherit) {
351 int flags = ::fcntl(fd, F_GETFD);
352 if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
353 return fd;
355 close(fd);
356 }
357 return fd;
358#elif defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
359 int flags = 0;
360 if (!child_processes_inherit) {
361 flags |= SOCK_CLOEXEC;
362 }
363 NativeSocket fd = llvm::sys::RetryAfterSignal(
364 static_cast<NativeSocket>(-1), ::accept4, sockfd, addr, addrlen, flags);
365#else
366 NativeSocket fd = llvm::sys::RetryAfterSignal(
367 static_cast<NativeSocket>(-1), ::accept, sockfd, addr, addrlen);
368#endif
369 if (fd == kInvalidSocketValue)
371 return fd;
372}
373
374llvm::raw_ostream &lldb_private::operator<<(llvm::raw_ostream &OS,
375 const Socket::HostAndPort &HP) {
376 return OS << '[' << HP.hostname << ']' << ':' << HP.port;
377}
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:342
#define LLDB_LOGF(log,...)
Definition: Log.h:349
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
Status Read(void *buf, size_t &num_bytes) override
Definition: Socket.cpp:217
static llvm::Expected< std::unique_ptr< UDPSocket > > UdpConnect(llvm::StringRef host_and_port, bool child_processes_inherit)
Definition: Socket.cpp:184
static const NativeSocket kInvalidSocketValue
Definition: Socket.h:59
WaitableHandle GetWaitableHandle() override
Definition: Socket.cpp:212
static NativeSocket CreateSocket(const int domain, const int type, const int protocol, bool child_processes_inherit, Status &error)
Definition: Socket.cpp:322
virtual size_t Send(const void *buf, const size_t num_bytes)
Definition: Socket.cpp:310
int SetOption(int level, int option_name, int option_value)
Definition: Socket.cpp:303
static llvm::Expected< HostAndPort > DecodeHostAndPort(llvm::StringRef host_and_port)
Definition: Socket.cpp:189
int GetOption(int level, int option_name, int &option_value)
Definition: Socket.cpp:295
Socket(SocketProtocol protocol, bool should_close, bool m_child_process_inherit)
Definition: Socket.cpp:73
static NativeSocket AcceptSocket(NativeSocket sockfd, struct sockaddr *addr, socklen_t *addrlen, bool child_processes_inherit, Status &error)
Definition: Socket.cpp:338
bool IsValid() const override
Definition: Socket.h:98
static void SetLastError(Status &error)
Definition: Socket.cpp:314
static llvm::Error Initialize()
Definition: Socket.cpp:82
bool m_should_close_fd
Definition: Socket.h:124
NativeSocket m_socket
Definition: Socket.h:122
static llvm::Expected< std::unique_ptr< Socket > > TcpConnect(llvm::StringRef host_and_port, bool child_processes_inherit)
Definition: Socket.cpp:149
Status Write(const void *buf, size_t &num_bytes) override
Definition: Socket.cpp:244
~Socket() override
Definition: Socket.cpp:80
Status Close() override
Definition: Socket.cpp:272
static std::unique_ptr< Socket > Create(const SocketProtocol protocol, bool child_processes_inherit, Status &error)
Definition: Socket.cpp:107
static llvm::Expected< std::unique_ptr< TCPSocket > > TcpListen(llvm::StringRef host_and_port, bool child_processes_inherit, int backlog=5)
Definition: Socket.cpp:168
static void Terminate()
Definition: Socket.cpp:101
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.
Definition: SBAttachInfo.h:14
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:314
Stream & operator<<(Stream &s, const Mangled &obj)
int NativeSocket
Definition: Socket.h:36
Definition: SBAddress.h:15
@ eErrorTypeWin32
Standard Win32 error codes.