1 //===-- Socket.cpp ----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Host/Socket.h"
12 #include "lldb/Core/Log.h"
13 #include "lldb/Core/RegularExpression.h"
14 #include "lldb/Host/Config.h"
15 #include "lldb/Host/Host.h"
16 #include "lldb/Host/SocketAddress.h"
17 #include "lldb/Host/StringConvert.h"
18 #include "lldb/Host/common/TCPSocket.h"
19 #include "lldb/Host/common/UDPSocket.h"
21 #ifndef LLDB_DISABLE_POSIX
22 #include "lldb/Host/posix/DomainSocket.h"
24 #include <arpa/inet.h>
26 #include <netinet/in.h>
27 #include <netinet/tcp.h>
28 #include <sys/socket.h>
33 #include "lldb/Host/linux/AbstractSocket.h"
37 #include <arpa/inet.h>
38 #include <asm-generic/errno-base.h>
40 #include <linux/tcp.h>
41 #if defined(ANDROID_ARM_BUILD_STATIC) || defined(ANDROID_MIPS_BUILD_STATIC)
43 #include <sys/syscall.h>
45 #endif // ANDROID_ARM_BUILD_STATIC || ANDROID_MIPS_BUILD_STATIC
49 using namespace lldb_private;
52 typedef const char *set_socket_option_arg_type;
53 typedef char *get_socket_option_arg_type;
54 const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
55 #else // #if defined(_WIN32)
56 typedef const void *set_socket_option_arg_type;
57 typedef void *get_socket_option_arg_type;
58 const NativeSocket Socket::kInvalidSocketValue = -1;
59 #endif // #if defined(_WIN32)
63 bool IsInterrupted() {
65 return ::WSAGetLastError() == WSAEINTR;
67 return errno == EINTR;
72 Socket::Socket(NativeSocket socket, SocketProtocol protocol, bool should_close)
73 : IOObject(eFDTypeSocket, should_close), m_protocol(protocol),
76 Socket::~Socket() { Close(); }
78 std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
79 bool child_processes_inherit,
83 std::unique_ptr<Socket> socket_up;
86 socket_up.reset(new TCPSocket(child_processes_inherit, error));
89 socket_up.reset(new UDPSocket(child_processes_inherit, error));
91 case ProtocolUnixDomain:
92 #ifndef LLDB_DISABLE_POSIX
93 socket_up.reset(new DomainSocket(child_processes_inherit, error));
96 "Unix domain sockets are not supported on this platform.");
99 case ProtocolUnixAbstract:
101 socket_up.reset(new AbstractSocket(child_processes_inherit, error));
103 error.SetErrorString(
104 "Abstract domain sockets are not supported on this platform.");
115 Error Socket::TcpConnect(llvm::StringRef host_and_port,
116 bool child_processes_inherit, Socket *&socket) {
117 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
119 log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
120 host_and_port.data());
123 std::unique_ptr<Socket> connect_socket(
124 Create(ProtocolTcp, child_processes_inherit, error));
128 error = connect_socket->Connect(host_and_port);
130 socket = connect_socket.release();
135 Error Socket::TcpListen(llvm::StringRef host_and_port,
136 bool child_processes_inherit, Socket *&socket,
137 Predicate<uint16_t> *predicate, int backlog) {
138 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
140 log->Printf("Socket::%s (%s)", __FUNCTION__, host_and_port.data());
143 std::string host_str;
144 std::string port_str;
145 int32_t port = INT32_MIN;
146 if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error))
149 std::unique_ptr<TCPSocket> listen_socket(
150 new TCPSocket(child_processes_inherit, error));
154 error = listen_socket->Listen(host_and_port, backlog);
155 if (error.Success()) {
156 // We were asked to listen on port zero which means we
157 // must now read the actual port that was given to us
158 // as port zero is a special code for "find an open port
161 port = listen_socket->GetLocalPortNumber();
163 // Set the port predicate since when doing a listen://<host>:<port>
164 // it often needs to accept the incoming connection which is a blocking
165 // system call. Allowing access to the bound port using a predicate allows
166 // us to wait for the port predicate to be set to a non-zero value from
167 // another thread in an efficient manor.
169 predicate->SetValue(port, eBroadcastAlways);
170 socket = listen_socket.release();
176 Error Socket::UdpConnect(llvm::StringRef host_and_port,
177 bool child_processes_inherit, Socket *&send_socket,
178 Socket *&recv_socket) {
179 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
181 log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
182 host_and_port.data());
184 return UDPSocket::Connect(host_and_port, child_processes_inherit, send_socket,
188 Error Socket::UnixDomainConnect(llvm::StringRef name,
189 bool child_processes_inherit, Socket *&socket) {
191 std::unique_ptr<Socket> connect_socket(
192 Create(ProtocolUnixDomain, child_processes_inherit, error));
196 error = connect_socket->Connect(name);
198 socket = connect_socket.release();
203 Error Socket::UnixDomainAccept(llvm::StringRef name,
204 bool child_processes_inherit, Socket *&socket) {
206 std::unique_ptr<Socket> listen_socket(
207 Create(ProtocolUnixDomain, child_processes_inherit, error));
211 error = listen_socket->Listen(name, 5);
215 error = listen_socket->Accept(name, child_processes_inherit, socket);
219 Error Socket::UnixAbstractConnect(llvm::StringRef name,
220 bool child_processes_inherit,
223 std::unique_ptr<Socket> connect_socket(
224 Create(ProtocolUnixAbstract, child_processes_inherit, error));
228 error = connect_socket->Connect(name);
230 socket = connect_socket.release();
234 Error Socket::UnixAbstractAccept(llvm::StringRef name,
235 bool child_processes_inherit,
238 std::unique_ptr<Socket> listen_socket(
239 Create(ProtocolUnixAbstract, child_processes_inherit, error));
243 error = listen_socket->Listen(name, 5);
247 error = listen_socket->Accept(name, child_processes_inherit, socket);
251 bool Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
252 std::string &host_str, std::string &port_str,
253 int32_t &port, Error *error_ptr) {
254 static RegularExpression g_regex(llvm::StringRef("([^:]+):([0-9]+)"));
255 RegularExpression::Match regex_match(2);
256 if (g_regex.Execute(host_and_port, ®ex_match)) {
257 if (regex_match.GetMatchAtIndex(host_and_port.data(), 1, host_str) &&
258 regex_match.GetMatchAtIndex(host_and_port.data(), 2, port_str)) {
260 port = StringConvert::ToUInt32(port_str.c_str(), UINT32_MAX, 10, &ok);
261 if (ok && port <= UINT16_MAX) {
268 error_ptr->SetErrorStringWithFormat(
269 "invalid host:port specification: '%s'", host_and_port.data());
274 // If this was unsuccessful, then check if it's simply a signed 32-bit
275 // integer, representing
276 // a port with an empty host.
280 port = StringConvert::ToUInt32(host_and_port.data(), UINT32_MAX, 10, &ok);
281 if (ok && port < UINT16_MAX) {
282 port_str = host_and_port;
289 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'",
290 host_and_port.data());
294 IOObject::WaitableHandle Socket::GetWaitableHandle() {
295 // TODO: On Windows, use WSAEventSelect
299 Error Socket::Read(void *buf, size_t &num_bytes) {
301 int bytes_received = 0;
303 bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
304 } while (bytes_received < 0 && IsInterrupted());
306 if (bytes_received < 0) {
310 num_bytes = bytes_received;
312 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
314 log->Printf("%p Socket::Read() (socket = %" PRIu64
315 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
317 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
318 static_cast<uint64_t>(num_bytes),
319 static_cast<int64_t>(bytes_received), error.AsCString());
325 Error Socket::Write(const void *buf, size_t &num_bytes) {
329 bytes_sent = Send(buf, num_bytes);
330 } while (bytes_sent < 0 && IsInterrupted());
332 if (bytes_sent < 0) {
336 num_bytes = bytes_sent;
338 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
340 log->Printf("%p Socket::Write() (socket = %" PRIu64
341 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
343 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
344 static_cast<uint64_t>(num_bytes),
345 static_cast<int64_t>(bytes_sent), error.AsCString());
351 Error Socket::PreDisconnect() {
356 Error Socket::Close() {
358 if (!IsValid() || !m_should_close_fd)
361 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
363 log->Printf("%p Socket::Close (fd = %i)", static_cast<void *>(this),
367 bool success = !!closesocket(m_socket);
369 bool success = !!::close(m_socket);
371 // A reference to a FD was passed in, set it to an invalid value
372 m_socket = kInvalidSocketValue;
380 int Socket::GetOption(int level, int option_name, int &option_value) {
381 get_socket_option_arg_type option_value_p =
382 reinterpret_cast<get_socket_option_arg_type>(&option_value);
383 socklen_t option_value_size = sizeof(int);
384 return ::getsockopt(m_socket, level, option_name, option_value_p,
388 int Socket::SetOption(int level, int option_name, int option_value) {
389 set_socket_option_arg_type option_value_p =
390 reinterpret_cast<get_socket_option_arg_type>(&option_value);
391 return ::setsockopt(m_socket, level, option_name, option_value_p,
392 sizeof(option_value));
395 size_t Socket::Send(const void *buf, const size_t num_bytes) {
396 return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
399 void Socket::SetLastError(Error &error) {
401 error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
403 error.SetErrorToErrno();
407 NativeSocket Socket::CreateSocket(const int domain, const int type,
409 bool child_processes_inherit, Error &error) {
411 auto socketType = type;
413 if (!child_processes_inherit)
414 socketType |= SOCK_CLOEXEC;
416 auto sock = ::socket(domain, socketType, protocol);
417 if (sock == kInvalidSocketValue)
423 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
425 bool child_processes_inherit, Error &error) {
427 #if defined(ANDROID_ARM_BUILD_STATIC) || defined(ANDROID_MIPS_BUILD_STATIC)
428 // Temporary workaround for statically linking Android lldb-server with the
430 int fd = syscall(__NR_accept, sockfd, addr, addrlen);
431 if (fd >= 0 && !child_processes_inherit) {
432 int flags = ::fcntl(fd, F_GETFD);
433 if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
439 #elif defined(SOCK_CLOEXEC)
441 if (!child_processes_inherit) {
442 flags |= SOCK_CLOEXEC;
444 #if defined(__NetBSD__)
445 NativeSocket fd = ::paccept(sockfd, addr, addrlen, nullptr, flags);
447 NativeSocket fd = ::accept4(sockfd, addr, addrlen, flags);
450 NativeSocket fd = ::accept(sockfd, addr, addrlen);
452 if (fd == kInvalidSocketValue)