15#include "llvm/Config/config.h"
25#include <sys/socket.h>
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());
68#define INVALID_SOCKET -1
73 return ::closesocket(Socket);
75 return ::close(Socket);
80 struct sockaddr_un Addr;
81 memset(&Addr, 0,
sizeof(Addr));
82 Addr.sun_family = AF_UNIX;
84 if (
sizeof(sockaddr_un::sun_path) <= SocketPath.
size())
86 std::make_error_code(std::errc::filename_too_long),
87 "Socket path exceeds sockaddr_un::sun_path size limit");
89 strncpy(Addr.sun_path, SocketPath.
str().c_str(),
sizeof(Addr.sun_path) - 1);
97 "Create socket failed");
107 setsockopt(Socket, SOL_SOCKET, SO_PEERCRED, NULL, 0);
115 if (::connect(Socket, (
struct sockaddr *)&*Addr,
sizeof(*Addr)) == -1) {
123 return _open_osfhandle(Socket, 0);
129ListeningSocket::ListeningSocket(
int SocketFD,
StringRef SocketPath,
131 : FD(SocketFD), SocketPath(SocketPath), PipeFD{PipeFD[0], PipeFD[1]} {}
133ListeningSocket::ListeningSocket(ListeningSocket &&LS)
134 : FD(LS.FD.
load()), SocketPath(LS.SocketPath),
135 PipeFD{LS.PipeFD[0], LS.PipeFD[1]} {
138 LS.SocketPath.clear();
161 std::make_error_code(std::errc::file_exists),
162 "Socket address unavailable");
164 ::close(std::move(*MaybeFD));
168 std::make_error_code(std::errc::address_in_use),
169 "Socket address unavailable");
178 "socket create failed");
187 setsockopt(Socket, SOL_SOCKET, SO_PEERCRED, NULL, 0);
195 if (::bind(Socket, (
struct sockaddr *)&*Addr,
sizeof(*Addr)) == -1) {
203 if (::listen(Socket, MaxBacklog) == -1)
210 if (::_pipe(PipeFD, 1, 0) == -1)
212 if (::pipe(PipeFD) == -1)
218 return ListeningSocket{_open_osfhandle(Socket, 0), SocketPath, PipeFD};
220 return ListeningSocket{Socket, SocketPath, PipeFD};
233static std::error_code
235 const std::function<
int()> &getActiveFD,
236 const std::optional<int> &CancelFD = std::nullopt) {
238 FD[0].events = POLLIN;
240 SOCKET WinServerSock = _get_osfhandle(getActiveFD());
241 FD[0].fd = WinServerSock;
243 FD[0].fd = getActiveFD();
246 if (CancelFD.has_value()) {
247 FD[1].events = POLLIN;
248 FD[1].fd = CancelFD.value();
254 auto Start = std::chrono::steady_clock::now();
255 auto RemainingTimeout =
Timeout;
260 if (PollStatus != 0 &&
Timeout != std::chrono::milliseconds(-1)) {
261 auto TotalElapsedTime =
262 std::chrono::duration_cast<std::chrono::milliseconds>(
263 std::chrono::steady_clock::now() - Start);
265 if (TotalElapsedTime >=
Timeout)
266 return std::make_error_code(std::errc::operation_would_block);
268 RemainingTimeout =
Timeout - TotalElapsedTime;
271 PollStatus = WSAPoll(FD, FDCount, RemainingTimeout.count());
272 }
while (PollStatus == SOCKET_ERROR &&
275 PollStatus = ::poll(FD, FDCount, RemainingTimeout.count());
276 }
while (PollStatus == -1 &&
282 if (getActiveFD() == -1 || (CancelFD.has_value() && FD[1].revents & POLLIN))
283 return std::make_error_code(std::errc::operation_canceled);
285 if (PollStatus == SOCKET_ERROR)
287 if (PollStatus == -1)
291 return std::make_error_code(std::errc::timed_out);
292 if (FD[0].revents & POLLNVAL)
293 return std::make_error_code(std::errc::bad_file_descriptor);
294 return std::error_code();
299 auto getActiveFD = [
this]() ->
int {
return FD; };
306 SOCKET WinAcceptSock =
::accept(_get_osfhandle(FD), NULL, NULL);
307 AcceptFD = _open_osfhandle(WinAcceptSock, 0);
309 AcceptFD =
::accept(FD, NULL, NULL);
314 "Socket accept failed");
315 return std::make_unique<raw_socket_stream>(AcceptFD);
319 int ObservedFD = FD.load();
321 if (ObservedFD == -1)
326 if (!FD.compare_exchange_strong(ObservedFD, -1))
330 ::unlink(SocketPath.c_str());
334 ssize_t written =
::write(PipeFD[1], &Byte, 1);
370 return FD.takeError();
371 return std::make_unique<raw_socket_stream>(*FD);
375 const std::chrono::milliseconds &
Timeout) {
376 auto getActiveFD = [
this]() ->
int {
return this->
get_fd(); };
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.
Represent a constant reference to a string, i.e.
std::string str() const
Get the contents as an std::string.
constexpr size_t size() const
Get the string size.
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 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.
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
static Expected< int > getSocketFD(StringRef SocketPath)
static Expected< sockaddr_un > setSocketAddr(StringRef SocketPath)
static int closeSocket(NativeSocket Socket)
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)