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
27#if LLDB_ENABLE_POSIX
29
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
43#ifdef __ANDROID__
44#include <arpa/inet.h>
45#include <asm-generic/errno-base.h>
46#include <cerrno>
47#include <fcntl.h>
48#include <linux/tcp.h>
49#include <sys/syscall.h>
50#include <unistd.h>
51#endif // __ANDROID__
52
53using namespace lldb;
54using namespace lldb_private;
55
56#if defined(_WIN32)
57typedef const char *set_socket_option_arg_type;
58typedef char *get_socket_option_arg_type;
59const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
61#else // #if defined(_WIN32)
62typedef const void *set_socket_option_arg_type;
66#endif // #if defined(_WIN32)
67
68static bool IsInterrupted() {
69#if defined(_WIN32)
70 return ::WSAGetLastError() == WSAEINTR;
71#else
72 return errno == EINTR;
73#endif
74}
75
77#ifdef _WIN32
78 m_socket = socket->GetNativeSocket();
80
81 // Create a pipe to transfer WSAPROTOCOL_INFO to the child process.
82 error = m_socket_pipe.CreateNew(true);
83 if (error.Fail())
84 return;
85
86 m_fd = m_socket_pipe.GetReadPipe();
87#else
88 m_fd = socket->GetNativeSocket();
89 error = Status();
90#endif
91}
92
94#ifdef _WIN32
95 // Transfer WSAPROTOCOL_INFO to the child process.
96 m_socket_pipe.CloseReadFileDescriptor();
97
98 WSAPROTOCOL_INFO protocol_info;
99 if (::WSADuplicateSocket(m_socket, child_pid, &protocol_info) ==
100 SOCKET_ERROR) {
101 int last_error = ::WSAGetLastError();
103 "WSADuplicateSocket() failed, error: %d", last_error);
104 }
105
106 size_t num_bytes;
107 Status error =
108 m_socket_pipe.WriteWithTimeout(&protocol_info, sizeof(protocol_info),
109 std::chrono::seconds(10), num_bytes);
110 if (error.Fail())
111 return error;
112 if (num_bytes != sizeof(protocol_info))
114 "WriteWithTimeout(WSAPROTOCOL_INFO) failed: {0} bytes", num_bytes);
115#endif
116 return Status();
117}
118
120#ifdef _WIN32
122 // Read WSAPROTOCOL_INFO from the parent process and create NativeSocket.
123 WSAPROTOCOL_INFO protocol_info;
124 {
125 Pipe socket_pipe(fd, LLDB_INVALID_PIPE);
126 size_t num_bytes;
127 Status error =
128 socket_pipe.ReadWithTimeout(&protocol_info, sizeof(protocol_info),
129 std::chrono::seconds(10), num_bytes);
130 if (error.Fail())
131 return error;
132 if (num_bytes != sizeof(protocol_info)) {
134 "socket_pipe.ReadWithTimeout(WSAPROTOCOL_INFO) failed: {0} bytes",
135 num_bytes);
136 }
137 }
138 socket = ::WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
139 FROM_PROTOCOL_INFO, &protocol_info, 0, 0);
140 if (socket == INVALID_SOCKET) {
142 "WSASocket(FROM_PROTOCOL_INFO) failed: error {0}", ::WSAGetLastError());
143 }
144 return Status();
145#else
146 socket = fd;
147 return Status();
148#endif
149}
150
152 const char *m_scheme;
154};
155
157 {"tcp", Socket::ProtocolTcp},
158 {"udp", Socket::ProtocolUdp},
160 {"unix-abstract", Socket::ProtocolUnixAbstract},
161};
162
163const char *
165 for (auto s : socket_schemes) {
166 if (s.m_protocol == protocol)
167 return s.m_scheme;
168 }
169 return nullptr;
170}
171
172bool Socket::FindProtocolByScheme(const char *scheme,
173 Socket::SocketProtocol &protocol) {
174 for (auto s : socket_schemes) {
175 if (!strcmp(s.m_scheme, scheme)) {
176 protocol = s.m_protocol;
177 return true;
178 }
179 }
180 return false;
181}
182
183Socket::Socket(SocketProtocol protocol, bool should_close)
184 : IOObject(eFDTypeSocket), m_protocol(protocol),
185 m_socket(kInvalidSocketValue), m_should_close_fd(should_close) {}
186
188
189llvm::Error Socket::Initialize() {
190#if defined(_WIN32)
191 auto wVersion = WINSOCK_VERSION;
192 WSADATA wsaData;
193 int err = ::WSAStartup(wVersion, &wsaData);
194 if (err == 0) {
195 if (wsaData.wVersion < wVersion) {
196 WSACleanup();
197 return llvm::createStringError("WSASock version is not expected.");
198 }
199 } else {
200 return llvm::errorCodeToError(llvm::mapWindowsError(::WSAGetLastError()));
201 }
202#endif
203
204 return llvm::Error::success();
205}
206
208#if defined(_WIN32)
209 ::WSACleanup();
210#endif
211}
212
213std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
214 Status &error) {
215 error.Clear();
216
217 const bool should_close = true;
218 std::unique_ptr<Socket> socket_up;
219 switch (protocol) {
220 case ProtocolTcp:
221 socket_up = std::make_unique<TCPSocket>(should_close);
222 break;
223 case ProtocolUdp:
224 socket_up = std::make_unique<UDPSocket>(should_close);
225 break;
227#if LLDB_ENABLE_POSIX
228 socket_up = std::make_unique<DomainSocket>(should_close);
229#else
231 "Unix domain sockets are not supported on this platform.");
232#endif
233 break;
235#ifdef __linux__
236 socket_up = std::make_unique<AbstractSocket>();
237#else
239 "Abstract domain sockets are not supported on this platform.");
240#endif
241 break;
242 }
243
244 if (error.Fail())
245 socket_up.reset();
246
247 return socket_up;
248}
249
250llvm::Expected<std::unique_ptr<Socket>>
251Socket::TcpConnect(llvm::StringRef host_and_port) {
253 LLDB_LOG(log, "host_and_port = {0}", host_and_port);
254
256 std::unique_ptr<Socket> connect_socket = Create(ProtocolTcp, error);
257 if (error.Fail())
258 return error.ToError();
259
260 error = connect_socket->Connect(host_and_port);
261 if (error.Success())
262 return std::move(connect_socket);
263
264 return error.ToError();
265}
266
267llvm::Expected<std::unique_ptr<TCPSocket>>
268Socket::TcpListen(llvm::StringRef host_and_port, int backlog) {
270 LLDB_LOG(log, "host_and_port = {0}", host_and_port);
271
272 std::unique_ptr<TCPSocket> listen_socket(
273 new TCPSocket(/*should_close=*/true));
274
275 Status error = listen_socket->Listen(host_and_port, backlog);
276 if (error.Fail())
277 return error.ToError();
278
279 return std::move(listen_socket);
280}
281
282llvm::Expected<std::unique_ptr<UDPSocket>>
283Socket::UdpConnect(llvm::StringRef host_and_port) {
284 return UDPSocket::CreateConnected(host_and_port);
285}
286
287llvm::Expected<Socket::HostAndPort> Socket::DecodeHostAndPort(llvm::StringRef host_and_port) {
288 static llvm::Regex g_regex("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)");
289 HostAndPort ret;
290 llvm::SmallVector<llvm::StringRef, 3> matches;
291 if (g_regex.match(host_and_port, &matches)) {
292 ret.hostname = matches[1].str();
293 // IPv6 addresses are wrapped in [] when specified with ports
294 if (ret.hostname.front() == '[' && ret.hostname.back() == ']')
295 ret.hostname = ret.hostname.substr(1, ret.hostname.size() - 2);
296 if (to_integer(matches[2], ret.port, 10))
297 return ret;
298 } else {
299 // If this was unsuccessful, then check if it's simply an unsigned 16-bit
300 // integer, representing a port with an empty host.
301 if (to_integer(host_and_port, ret.port, 10))
302 return ret;
303 }
304
305 return llvm::createStringError(llvm::inconvertibleErrorCode(),
306 "invalid host:port specification: '%s'",
307 host_and_port.str().c_str());
308}
309
311 // TODO: On Windows, use WSAEventSelect
312 return m_socket;
313}
314
315Status Socket::Read(void *buf, size_t &num_bytes) {
317 int bytes_received = 0;
318 do {
319 bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
320 } while (bytes_received < 0 && IsInterrupted());
321
322 if (bytes_received < 0) {
324 num_bytes = 0;
325 } else
326 num_bytes = bytes_received;
327
329 if (log) {
330 LLDB_LOGF(log,
331 "%p Socket::Read() (socket = %" PRIu64
332 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
333 " (error = %s)",
334 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
335 static_cast<uint64_t>(num_bytes),
336 static_cast<int64_t>(bytes_received), error.AsCString());
337 }
338
339 return error;
340}
341
342Status Socket::Write(const void *buf, size_t &num_bytes) {
343 const size_t src_len = num_bytes;
345 int bytes_sent = 0;
346 do {
347 bytes_sent = Send(buf, num_bytes);
348 } while (bytes_sent < 0 && IsInterrupted());
349
350 if (bytes_sent < 0) {
352 num_bytes = 0;
353 } else
354 num_bytes = bytes_sent;
355
357 if (log) {
358 LLDB_LOGF(log,
359 "%p Socket::Write() (socket = %" PRIu64
360 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
361 " (error = %s)",
362 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
363 static_cast<uint64_t>(src_len),
364 static_cast<int64_t>(bytes_sent), error.AsCString());
365 }
366
367 return error;
368}
369
372 if (!IsValid() || !m_should_close_fd)
373 return error;
374
376 LLDB_LOGF(log, "%p Socket::Close (fd = %" PRIu64 ")",
377 static_cast<void *>(this), static_cast<uint64_t>(m_socket));
378
379 bool success = CloseSocket(m_socket) == 0;
380 // A reference to a FD was passed in, set it to an invalid value
382 if (!success) {
384 }
385
386 return error;
387}
388
389int Socket::GetOption(NativeSocket sockfd, int level, int option_name,
390 int &option_value) {
391 get_socket_option_arg_type option_value_p =
392 reinterpret_cast<get_socket_option_arg_type>(&option_value);
393 socklen_t option_value_size = sizeof(int);
394 return ::getsockopt(sockfd, level, option_name, option_value_p,
395 &option_value_size);
396}
397
398int Socket::SetOption(NativeSocket sockfd, int level, int option_name,
399 int option_value) {
400 set_socket_option_arg_type option_value_p =
401 reinterpret_cast<set_socket_option_arg_type>(&option_value);
402 return ::setsockopt(sockfd, level, option_name, option_value_p,
403 sizeof(option_value));
404}
405
406size_t Socket::Send(const void *buf, const size_t num_bytes) {
407 return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
408}
409
411#if defined(_WIN32)
412 error = Status(::WSAGetLastError(), lldb::eErrorTypeWin32);
413#else
415#endif
416}
417
419 std::error_code EC;
420#ifdef _WIN32
421 EC = llvm::mapWindowsError(WSAGetLastError());
422#else
423 EC = std::error_code(errno, std::generic_category());
424#endif
425 return EC;
426}
427
429#ifdef _WIN32
430 return ::closesocket(sockfd);
431#else
432 return ::close(sockfd);
433#endif
434}
435
436NativeSocket Socket::CreateSocket(const int domain, const int type,
437 const int protocol, Status &error) {
438 error.Clear();
439 auto socket_type = type;
440#ifdef SOCK_CLOEXEC
441 socket_type |= SOCK_CLOEXEC;
442#endif
443 auto sock = ::socket(domain, socket_type, protocol);
444 if (sock == kInvalidSocketValue)
446
447 return sock;
448}
449
451 socket = nullptr;
452 MainLoop accept_loop;
453 llvm::Expected<std::vector<MainLoopBase::ReadHandleUP>> expected_handles =
454 Accept(accept_loop,
455 [&accept_loop, &socket](std::unique_ptr<Socket> sock) {
456 socket = sock.release();
457 accept_loop.RequestTermination();
458 });
459 if (!expected_handles)
460 return Status::FromError(expected_handles.takeError());
461 if (timeout) {
462 accept_loop.AddCallback(
463 [](MainLoopBase &loop) { loop.RequestTermination(); }, *timeout);
464 }
465 if (Status status = accept_loop.Run(); status.Fail())
466 return status;
467 if (socket)
468 return Status();
469 return Status(std::make_error_code(std::errc::timed_out));
470}
471
472NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
473 socklen_t *addrlen, Status &error) {
474 error.Clear();
475#if defined(ANDROID_USE_ACCEPT_WORKAROUND)
476 // Hack:
477 // This enables static linking lldb-server to an API 21 libc, but still
478 // having it run on older devices. It is necessary because API 21 libc's
479 // implementation of accept() uses the accept4 syscall(), which is not
480 // available in older kernels. Using an older libc would fix this issue, but
481 // introduce other ones, as the old libraries were quite buggy.
482 int fd = syscall(__NR_accept, sockfd, addr, addrlen);
483 if (fd >= 0) {
484 int flags = ::fcntl(fd, F_GETFD);
485 if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
486 return fd;
488 close(fd);
489 }
490 return fd;
491#elif defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
492 int flags = SOCK_CLOEXEC;
493 NativeSocket fd = llvm::sys::RetryAfterSignal(
494 static_cast<NativeSocket>(-1), ::accept4, sockfd, addr, addrlen, flags);
495#else
496 NativeSocket fd = llvm::sys::RetryAfterSignal(
497 static_cast<NativeSocket>(-1), ::accept, sockfd, addr, addrlen);
498#endif
499 if (fd == kInvalidSocketValue)
501 return fd;
502}
503
504llvm::raw_ostream &lldb_private::operator<<(llvm::raw_ostream &OS,
505 const Socket::HostAndPort &HP) {
506 return OS << '[' << HP.hostname << ']' << ':' << HP.port;
507}
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:369
#define LLDB_LOGF(log,...)
Definition: Log.h:376
static bool IsInterrupted()
Definition: Socket.cpp:68
void * get_socket_option_arg_type
Definition: Socket.cpp:63
const void * set_socket_option_arg_type
Definition: Socket.cpp:62
static SocketScheme socket_schemes[]
Definition: Socket.cpp:156
void AddCallback(const Callback &callback, std::chrono::nanoseconds delay)
Definition: MainLoopBase.h:66
virtual void RequestTermination()
Definition: MainLoopBase.h:79
A posix-based implementation of Pipe, a class that abtracts unix style pipes.
Definition: PipePosix.h:21
Status ReadWithTimeout(void *buf, size_t size, const std::chrono::microseconds &timeout, size_t &bytes_read) override
Definition: PipePosix.cpp:303
static const shared_fd_t kInvalidFD
Definition: Socket.h:50
SharedSocket(const Socket *socket, Status &error)
Definition: Socket.cpp:76
Status CompleteSending(lldb::pid_t child_pid)
Definition: Socket.cpp:93
static Status GetNativeSocket(shared_fd_t fd, NativeSocket &socket)
Definition: Socket.cpp:119
static std::unique_ptr< Socket > Create(const SocketProtocol protocol, Status &error)
Definition: Socket.cpp:213
Status Read(void *buf, size_t &num_bytes) override
Definition: Socket.cpp:315
NativeSocket GetNativeSocket() const
Definition: Socket.h:138
static const NativeSocket kInvalidSocketValue
Definition: Socket.h:86
WaitableHandle GetWaitableHandle() override
Definition: Socket.cpp:310
virtual size_t Send(const void *buf, const size_t num_bytes)
Definition: Socket.cpp:406
static llvm::Expected< std::unique_ptr< UDPSocket > > UdpConnect(llvm::StringRef host_and_port)
Definition: Socket.cpp:283
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:436
static int GetOption(NativeSocket sockfd, int level, int option_name, int &option_value)
Definition: Socket.cpp:389
static llvm::Expected< HostAndPort > DecodeHostAndPort(llvm::StringRef host_and_port)
Definition: Socket.cpp:287
static NativeSocket AcceptSocket(NativeSocket sockfd, struct sockaddr *addr, socklen_t *addrlen, Status &error)
Definition: Socket.cpp:472
static bool FindProtocolByScheme(const char *scheme, SocketProtocol &protocol)
Definition: Socket.cpp:172
bool IsValid() const override
Definition: Socket.h:146
static Status GetLastError()
Definition: Socket.cpp:418
static llvm::Expected< std::unique_ptr< Socket > > TcpConnect(llvm::StringRef host_and_port)
Definition: Socket.cpp:251
static void SetLastError(Status &error)
Definition: Socket.cpp:410
static llvm::Error Initialize()
Definition: Socket.cpp:189
bool m_should_close_fd
Definition: Socket.h:175
static int CloseSocket(NativeSocket sockfd)
Definition: Socket.cpp:428
static const char * FindSchemeByProtocol(const SocketProtocol protocol)
Definition: Socket.cpp:164
NativeSocket m_socket
Definition: Socket.h:174
static int SetOption(NativeSocket sockfd, int level, int option_name, int option_value)
Definition: Socket.cpp:398
Status Write(const void *buf, size_t &num_bytes) override
Definition: Socket.cpp:342
~Socket() override
Definition: Socket.cpp:187
static llvm::Expected< std::unique_ptr< TCPSocket > > TcpListen(llvm::StringRef host_and_port, int backlog=5)
Definition: Socket.cpp:268
Status Close() override
Definition: Socket.cpp:370
Socket(SocketProtocol protocol, bool should_close)
Definition: Socket.cpp:183
static void Terminate()
Definition: Socket.cpp:207
An error handling class.
Definition: Status.h:118
static Status FromErrno()
Set the current error to errno.
Definition: Status.cpp:300
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:294
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:137
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:332
Stream & operator<<(Stream &s, const Mangled &obj)
NativeSocket shared_fd_t
Definition: Socket.h:42
int NativeSocket
Definition: Socket.h:41
Definition: SBAddress.h:15
@ eErrorTypeWin32
Standard Win32 error codes.
uint64_t pid_t
Definition: lldb-types.h:83
const Socket::SocketProtocol m_protocol
Definition: Socket.cpp:153
const char * m_scheme
Definition: Socket.cpp:152