Coverage Report

Created: 2022-01-22 13:19

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