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