LLVM 23.0.0git
raw_socket_stream.cpp
Go to the documentation of this file.
1//===-- llvm/Support/raw_socket_stream.cpp - Socket streams --*- C++ -*-===//
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// This file contains raw_ostream implementations for streams to communicate
10// via UNIX sockets
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/Config/config.h"
16#include "llvm/Support/Error.h"
18
19#include <atomic>
20#include <fcntl.h>
21#include <functional>
22
23#ifndef _WIN32
24#include <poll.h>
25#include <sys/socket.h>
26#include <sys/un.h>
27#else
29// winsock2.h must be included before afunix.h. Briefly turn off clang-format to
30// avoid error.
31// clang-format off
32#include <winsock2.h>
33#include <afunix.h>
34// clang-format on
35#include <io.h>
36#endif // _WIN32
37
38#if defined(HAVE_UNISTD_H)
39#include <unistd.h>
40#endif
41
42using namespace llvm;
43
44#ifdef _WIN32
45WSABalancer::WSABalancer() {
46 WSADATA WsaData;
47 ::memset(&WsaData, 0, sizeof(WsaData));
48 if (WSAStartup(MAKEWORD(2, 2), &WsaData) != 0) {
49 llvm::report_fatal_error("WSAStartup failed");
50 }
51}
52
53WSABalancer::~WSABalancer() { WSACleanup(); }
54#endif // _WIN32
55
56static std::error_code getLastSocketErrorCode() {
57#ifdef _WIN32
58 return std::error_code(::WSAGetLastError(), std::system_category());
59#else
60 return errnoAsErrorCode();
61#endif
62}
63
64static sockaddr_un setSocketAddr(StringRef SocketPath) {
65 struct sockaddr_un Addr;
66 memset(&Addr, 0, sizeof(Addr));
67 Addr.sun_family = AF_UNIX;
68 strncpy(Addr.sun_path, SocketPath.str().c_str(), sizeof(Addr.sun_path) - 1);
69 return Addr;
70}
71
73#ifdef _WIN32
74 SOCKET Socket = socket(AF_UNIX, SOCK_STREAM, 0);
75 if (Socket == INVALID_SOCKET) {
76#else
77 int Socket = socket(AF_UNIX, SOCK_STREAM, 0);
78 if (Socket == -1) {
79#endif // _WIN32
81 "Create socket failed");
82 }
83
84#ifdef __CYGWIN__
85 // On Cygwin, UNIX sockets involve a handshake between connect and accept
86 // to enable SO_PEERCRED/getpeereid handling. This necessitates accept being
87 // called before connect can return, but at least the tests in
88 // llvm/unittests/Support/raw_socket_stream_test do both on the same thread
89 // (first connect and then accept), resulting in a deadlock. This call turns
90 // off the handshake (and SO_PEERCRED/getpeereid support).
91 setsockopt(Socket, SOL_SOCKET, SO_PEERCRED, NULL, 0);
92#endif
93 struct sockaddr_un Addr = setSocketAddr(SocketPath);
94 if (::connect(Socket, (struct sockaddr *)&Addr, sizeof(Addr)) == -1) {
95 ::close(Socket);
97 "Connect socket failed");
98 }
99
100#ifdef _WIN32
101 return _open_osfhandle(Socket, 0);
102#else
103 return Socket;
104#endif // _WIN32
105}
106
107ListeningSocket::ListeningSocket(int SocketFD, StringRef SocketPath,
108 int PipeFD[2])
109 : FD(SocketFD), SocketPath(SocketPath), PipeFD{PipeFD[0], PipeFD[1]} {}
110
111ListeningSocket::ListeningSocket(ListeningSocket &&LS)
112 : FD(LS.FD.load()), SocketPath(LS.SocketPath),
113 PipeFD{LS.PipeFD[0], LS.PipeFD[1]} {
114
115 LS.FD = -1;
116 LS.SocketPath.clear();
117 LS.PipeFD[0] = -1;
118 LS.PipeFD[1] = -1;
119}
120
122 int MaxBacklog) {
123
124 // Handle instances where the target socket address already exists and
125 // differentiate between a preexisting file with and without a bound socket
126 //
127 // ::bind will return std::errc:address_in_use if a file at the socket address
128 // already exists (e.g., the file was not properly unlinked due to a crash)
129 // even if another socket has not yet binded to that address
130 if (llvm::sys::fs::exists(SocketPath)) {
131 Expected<int> MaybeFD = getSocketFD(SocketPath);
132 if (!MaybeFD) {
133
134 // Regardless of the error, notify the caller that a file already exists
135 // at the desired socket address and that there is no bound socket at that
136 // address. The file must be removed before ::bind can use the address
137 consumeError(MaybeFD.takeError());
139 std::make_error_code(std::errc::file_exists),
140 "Socket address unavailable");
141 }
142 ::close(std::move(*MaybeFD));
143
144 // Notify caller that the provided socket address already has a bound socket
146 std::make_error_code(std::errc::address_in_use),
147 "Socket address unavailable");
148 }
149
150#ifdef _WIN32
151 WSABalancer _;
152 SOCKET Socket = socket(AF_UNIX, SOCK_STREAM, 0);
153 if (Socket == INVALID_SOCKET)
154#else
155 int Socket = socket(AF_UNIX, SOCK_STREAM, 0);
156 if (Socket == -1)
157#endif
159 "socket create failed");
160
161#ifdef __CYGWIN__
162 // On Cygwin, UNIX sockets involve a handshake between connect and accept
163 // to enable SO_PEERCRED/getpeereid handling. This necessitates accept being
164 // called before connect can return, but at least the tests in
165 // llvm/unittests/Support/raw_socket_stream_test do both on the same thread
166 // (first connect and then accept), resulting in a deadlock. This call turns
167 // off the handshake (and SO_PEERCRED/getpeereid support).
168 setsockopt(Socket, SOL_SOCKET, SO_PEERCRED, NULL, 0);
169#endif
170 struct sockaddr_un Addr = setSocketAddr(SocketPath);
171 if (::bind(Socket, (struct sockaddr *)&Addr, sizeof(Addr)) == -1) {
172 // Grab error code from call to ::bind before calling ::close
173 std::error_code EC = getLastSocketErrorCode();
174 ::close(Socket);
175 return llvm::make_error<StringError>(EC, "Bind error");
176 }
177
178 // Mark socket as passive so incoming connections can be accepted
179 if (::listen(Socket, MaxBacklog) == -1)
181 "Listen error");
182
183 int PipeFD[2];
184#ifdef _WIN32
185 // Reserve 1 byte for the pipe and use default textmode
186 if (::_pipe(PipeFD, 1, 0) == -1)
187#else
188 if (::pipe(PipeFD) == -1)
189#endif // _WIN32
191 "pipe failed");
192
193#ifdef _WIN32
194 return ListeningSocket{_open_osfhandle(Socket, 0), SocketPath, PipeFD};
195#else
196 return ListeningSocket{Socket, SocketPath, PipeFD};
197#endif // _WIN32
198}
199
200// If a file descriptor being monitored by ::poll is closed by another thread,
201// the result is unspecified. In the case ::poll does not unblock and return,
202// when ActiveFD is closed, you can provide another file descriptor via CancelFD
203// that when written to will cause poll to return. Typically CancelFD is the
204// read end of a unidirectional pipe.
205//
206// Timeout should be -1 to block indefinitly
207//
208// getActiveFD is a callback to handle ActiveFD's of std::atomic<int> and int
209static std::error_code
210manageTimeout(const std::chrono::milliseconds &Timeout,
211 const std::function<int()> &getActiveFD,
212 const std::optional<int> &CancelFD = std::nullopt) {
213 struct pollfd FD[2];
214 FD[0].events = POLLIN;
215#ifdef _WIN32
216 SOCKET WinServerSock = _get_osfhandle(getActiveFD());
217 FD[0].fd = WinServerSock;
218#else
219 FD[0].fd = getActiveFD();
220#endif
221 uint8_t FDCount = 1;
222 if (CancelFD.has_value()) {
223 FD[1].events = POLLIN;
224 FD[1].fd = CancelFD.value();
225 FDCount++;
226 }
227
228 // Keep track of how much time has passed in case ::poll or WSAPoll are
229 // interupted by a signal and need to be recalled
230 auto Start = std::chrono::steady_clock::now();
231 auto RemainingTimeout = Timeout;
232 int PollStatus = 0;
233 do {
234 // If Timeout is -1 then poll should block and RemainingTimeout does not
235 // need to be recalculated
236 if (PollStatus != 0 && Timeout != std::chrono::milliseconds(-1)) {
237 auto TotalElapsedTime =
238 std::chrono::duration_cast<std::chrono::milliseconds>(
239 std::chrono::steady_clock::now() - Start);
240
241 if (TotalElapsedTime >= Timeout)
242 return std::make_error_code(std::errc::operation_would_block);
243
244 RemainingTimeout = Timeout - TotalElapsedTime;
245 }
246#ifdef _WIN32
247 PollStatus = WSAPoll(FD, FDCount, RemainingTimeout.count());
248 } while (PollStatus == SOCKET_ERROR &&
249 getLastSocketErrorCode() == std::errc::interrupted);
250#else
251 PollStatus = ::poll(FD, FDCount, RemainingTimeout.count());
252 } while (PollStatus == -1 &&
253 getLastSocketErrorCode() == std::errc::interrupted);
254#endif
255
256 // If ActiveFD equals -1 or CancelFD has data to be read then the operation
257 // has been canceled by another thread
258 if (getActiveFD() == -1 || (CancelFD.has_value() && FD[1].revents & POLLIN))
259 return std::make_error_code(std::errc::operation_canceled);
260#ifdef _WIN32
261 if (PollStatus == SOCKET_ERROR)
262#else
263 if (PollStatus == -1)
264#endif
265 return getLastSocketErrorCode();
266 if (PollStatus == 0)
267 return std::make_error_code(std::errc::timed_out);
268 if (FD[0].revents & POLLNVAL)
269 return std::make_error_code(std::errc::bad_file_descriptor);
270 return std::error_code();
271}
272
274ListeningSocket::accept(const std::chrono::milliseconds &Timeout) {
275 auto getActiveFD = [this]() -> int { return FD; };
276 std::error_code TimeoutErr = manageTimeout(Timeout, getActiveFD, PipeFD[0]);
277 if (TimeoutErr)
278 return llvm::make_error<StringError>(TimeoutErr, "Timeout error");
279
280 int AcceptFD;
281#ifdef _WIN32
282 SOCKET WinAcceptSock = ::accept(_get_osfhandle(FD), NULL, NULL);
283 AcceptFD = _open_osfhandle(WinAcceptSock, 0);
284#else
285 AcceptFD = ::accept(FD, NULL, NULL);
286#endif
287
288 if (AcceptFD == -1)
290 "Socket accept failed");
291 return std::make_unique<raw_socket_stream>(AcceptFD);
292}
293
295 int ObservedFD = FD.load();
296
297 if (ObservedFD == -1)
298 return;
299
300 // If FD equals ObservedFD set FD to -1; If FD doesn't equal ObservedFD then
301 // another thread is responsible for shutdown so return
302 if (!FD.compare_exchange_strong(ObservedFD, -1))
303 return;
304
305 ::close(ObservedFD);
306 ::unlink(SocketPath.c_str());
307
308 // Ensure ::poll returns if shutdown is called by a separate thread
309 char Byte = 'A';
310 ssize_t written = ::write(PipeFD[1], &Byte, 1);
311
312 // Ignore any write() error
313 (void)written;
314}
315
317 shutdown();
318
319 // Close the pipe's FDs in the destructor instead of within
320 // ListeningSocket::shutdown to avoid unnecessary synchronization issues that
321 // would occur as PipeFD's values would have to be changed to -1
322 //
323 // The move constructor sets PipeFD to -1
324 if (PipeFD[0] != -1)
325 ::close(PipeFD[0]);
326 if (PipeFD[1] != -1)
327 ::close(PipeFD[1]);
328}
329
330//===----------------------------------------------------------------------===//
331// raw_socket_stream
332//===----------------------------------------------------------------------===//
333
336
338
341#ifdef _WIN32
342 WSABalancer _;
343#endif // _WIN32
344 Expected<int> FD = getSocketFD(SocketPath);
345 if (!FD)
346 return FD.takeError();
347 return std::make_unique<raw_socket_stream>(*FD);
348}
349
350ssize_t raw_socket_stream::read(char *Ptr, size_t Size,
351 const std::chrono::milliseconds &Timeout) {
352 auto getActiveFD = [this]() -> int { return this->get_fd(); };
353 std::error_code Err = manageTimeout(Timeout, getActiveFD);
354 // Mimic raw_fd_stream::read error handling behavior
355 if (Err) {
357 return -1;
358 }
359 return raw_fd_stream::read(Ptr, Size);
360}
AMDGPU Mark last scratch load
#define _
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
static LLVM_ABI Expected< ListeningSocket > createUnix(StringRef SocketPath, int MaxBacklog=llvm::hardware_concurrency().compute_thread_count())
Creates a listening socket bound to the specified file system path.
LLVM_ABI void shutdown()
Closes the FD, unlinks the socket file, and writes to PipeFD.
LLVM_ABI Expected< std::unique_ptr< raw_socket_stream > > accept(const std::chrono::milliseconds &Timeout=std::chrono::milliseconds(-1))
Accepts an incoming connection on the listening socket.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:222
int get_fd() const
Return the file descriptor.
void error_detected(std::error_code EC)
Set the flag indicating that an output error has been encountered.
LLVM_ABI raw_fd_stream(StringRef Filename, std::error_code &EC)
Open the specified file for reading/writing/seeking.
LLVM_ABI ssize_t read(char *Ptr, size_t Size)
This reads the Size bytes into a buffer pointed by Ptr.
static Expected< std::unique_ptr< raw_socket_stream > > createConnectedUnix(StringRef SocketPath)
Create a raw_socket_stream connected to the UNIX domain socket at SocketPath.
~raw_socket_stream() override
ssize_t read(char *Ptr, size_t Size, const std::chrono::milliseconds &Timeout=std::chrono::milliseconds(-1))
Attempt to read from the raw_socket_stream's file descriptor.
LLVM_ABI bool exists(const basic_file_status &status)
Does file exist?
Definition Path.cpp:1091
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
@ Timeout
Reached timeout while waiting for the owner to release the lock.
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI Error write(MCStreamer &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue)
Definition DWP.cpp:677
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
Definition Error.h:1240
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1083
static Expected< int > getSocketFD(StringRef SocketPath)
static std::error_code getLastSocketErrorCode()
static std::error_code manageTimeout(const std::chrono::milliseconds &Timeout, const std::function< int()> &getActiveFD, const std::optional< int > &CancelFD=std::nullopt)
static sockaddr_un setSocketAddr(StringRef SocketPath)