1//===-- llvm/Support/raw_socket_stream.cpp - Socket streams --*- C++ -*-===//
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
7//===----------------------------------------------------------------------===//
9// This file contains raw_ostream implementations for streams to communicate
12//===----------------------------------------------------------------------===//
15#include "llvm/Config/config.h"
25#include <sys/socket.h>
29// winsock2.h must be included before afunix.h. Briefly turn off clang-format to
38#if defined(HAVE_UNISTD_H)
45WSABalancer::WSABalancer() {
47 ::memset(&WsaData, 0,
sizeof(WsaData));
48 if (WSAStartup(MAKEWORD(2, 2), &WsaData) != 0) {
53WSABalancer::~WSABalancer() { WSACleanup(); }
58 return std::error_code(::WSAGetLastError(), std::system_category());
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);
74 SOCKET Socket = socket(AF_UNIX, SOCK_STREAM, 0);
75 if (Socket == INVALID_SOCKET) {
77 int Socket = socket(AF_UNIX, SOCK_STREAM, 0);
81 "Create socket failed");
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);
94 if (::connect(Socket, (
struct sockaddr *)&Addr,
sizeof(Addr)) == -1)
96 "Connect socket failed");
99 return _open_osfhandle(Socket, 0);
105ListeningSocket::ListeningSocket(
int SocketFD,
StringRef SocketPath,
107 : FD(SocketFD), SocketPath(SocketPath), PipeFD{PipeFD[0], PipeFD[1]} {}
109 ListeningSocket::ListeningSocket(ListeningSocket &&LS)
110 : FD(LS.FD.
load()), SocketPath(LS.SocketPath),
111 PipeFD{LS.PipeFD[0], LS.PipeFD[1]} {
114 LS.SocketPath.clear();
122 // Handle instances where the target socket address already exists and
123 // differentiate between a preexisting file with and without a bound socket
125 // ::bind will return std::errc:address_in_use if a file at the socket address
126 // already exists (e.g., the file was not properly unlinked due to a crash)
127 // even if another socket has not yet binded to that address
132 // Regardless of the error, notify the caller that a file already exists
133 // at the desired socket address and that there is no bound socket at that
134 // address. The file must be removed before ::bind can use the address
137 std::make_error_code(std::errc::file_exists),
138 "Socket address unavailable");
140 ::close(std::move(*MaybeFD));
142 // Notify caller that the provided socket address already has a bound socket
144 std::make_error_code(std::errc::address_in_use),
145 "Socket address unavailable");
150 SOCKET Socket = socket(AF_UNIX, SOCK_STREAM, 0);
151 if (Socket == INVALID_SOCKET)
153 int Socket = socket(AF_UNIX, SOCK_STREAM, 0);
157 "socket create failed");
160 // On Cygwin, UNIX sockets involve a handshake between connect and accept
161 // to enable SO_PEERCRED/getpeereid handling. This necessitates accept being
162 // called before connect can return, but at least the tests in
163 // llvm/unittests/Support/raw_socket_stream_test do both on the same thread
164 // (first connect and then accept), resulting in a deadlock. This call turns
165 // off the handshake (and SO_PEERCRED/getpeereid support).
166 setsockopt(Socket, SOL_SOCKET, SO_PEERCRED, NULL, 0);
169 if (::bind(Socket, (
struct sockaddr *)&Addr,
sizeof(Addr)) == -1) {
170 // Grab error code from call to ::bind before calling ::close
176 // Mark socket as passive so incoming connections can be accepted
177 if (::listen(Socket, MaxBacklog) == -1)
183 // Reserve 1 byte for the pipe and use default textmode
184 if (::_pipe(PipeFD, 1, 0) == -1)
186 if (::pipe(PipeFD) == -1)
192 return ListeningSocket{_open_osfhandle(Socket, 0), SocketPath, PipeFD};
194 return ListeningSocket{Socket, SocketPath, PipeFD};
198// If a file descriptor being monitored by ::poll is closed by another thread,
199// the result is unspecified. In the case ::poll does not unblock and return,
200// when ActiveFD is closed, you can provide another file descriptor via CancelFD
201// that when written to will cause poll to return. Typically CancelFD is the
202// read end of a unidirectional pipe.
204// Timeout should be -1 to block indefinitly
206// getActiveFD is a callback to handle ActiveFD's of std::atomic<int> and int
207static std::error_code
209 const std::function<
int()> &getActiveFD,
210 const std::optional<int> &CancelFD = std::nullopt) {
212 FD[0].events = POLLIN;
214 SOCKET WinServerSock = _get_osfhandle(getActiveFD());
215 FD[0].fd = WinServerSock;
217 FD[0].fd = getActiveFD();
220 if (CancelFD.has_value()) {
221 FD[1].events = POLLIN;
222 FD[1].fd = CancelFD.value();
226 // Keep track of how much time has passed in case ::poll or WSAPoll are
227 // interupted by a signal and need to be recalled
228 auto Start = std::chrono::steady_clock::now();
229 auto RemainingTimeout =
Timeout;
232 // If Timeout is -1 then poll should block and RemainingTimeout does not
233 // need to be recalculated
234 if (PollStatus != 0 &&
Timeout != std::chrono::milliseconds(-1)) {
235 auto TotalElapsedTime =
236 std::chrono::duration_cast<std::chrono::milliseconds>(
237 std::chrono::steady_clock::now() - Start);
239 if (TotalElapsedTime >=
Timeout)
240 return std::make_error_code(std::errc::operation_would_block);
242 RemainingTimeout =
Timeout - TotalElapsedTime;
245 PollStatus = WSAPoll(FD, FDCount, RemainingTimeout.count());
246 }
while (PollStatus == SOCKET_ERROR &&
249 PollStatus = ::poll(FD, FDCount, RemainingTimeout.count());
250 }
while (PollStatus == -1 &&
254 // If ActiveFD equals -1 or CancelFD has data to be read then the operation
255 // has been canceled by another thread
256 if (getActiveFD() == -1 || (CancelFD.has_value() && FD[1].revents & POLLIN))
257 return std::make_error_code(std::errc::operation_canceled);
259 if (PollStatus == SOCKET_ERROR)
261 if (PollStatus == -1)
265 return std::make_error_code(std::errc::timed_out);
266 if (FD[0].revents & POLLNVAL)
267 return std::make_error_code(std::errc::bad_file_descriptor);
268 return std::error_code();
273 auto getActiveFD = [
this]() ->
int {
return FD; };
280 SOCKET WinAcceptSock =
::accept(_get_osfhandle(FD), NULL, NULL);
281 AcceptFD = _open_osfhandle(WinAcceptSock, 0);
283 AcceptFD =
::accept(FD, NULL, NULL);
288 "Socket accept failed");
289 return std::make_unique<raw_socket_stream>(AcceptFD);
293 int ObservedFD = FD.load();
295 if (ObservedFD == -1)
298 // If FD equals ObservedFD set FD to -1; If FD doesn't equal ObservedFD then
299 // another thread is responsible for shutdown so return
300 if (!FD.compare_exchange_strong(ObservedFD, -1))
304 ::unlink(SocketPath.c_str());
306 // Ensure ::poll returns if shutdown is called by a separate thread
308 ssize_t written =
::write(PipeFD[1], &Byte, 1);
310 // Ignore any write() error
317 // Close the pipe's FDs in the destructor instead of within
318 // ListeningSocket::shutdown to avoid unnecessary synchronization issues that
319 // would occur as PipeFD's values would have to be changed to -1
321 // The move constructor sets PipeFD to -1
328//===----------------------------------------------------------------------===//
330//===----------------------------------------------------------------------===//
344 return FD.takeError();
345 return std::make_unique<raw_socket_stream>(*FD);
349 const std::chrono::milliseconds &
Timeout) {
350 auto getActiveFD = [
this]() ->
int {
return this->
get_fd(); };
352 // Mimic raw_fd_stream::read error handling behavior
AMDGPU Mark last scratch load
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
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 ~ListeningSocket()
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.
std::string str() const
str - Get the contents as an std::string.
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
raw_socket_stream(int SocketFD)
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?
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Error write(MCStreamer &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
@ 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.
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
void consumeError(Error Err)
Consume a Error without doing anything.
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)