Make improvements

- Every unit test now passes on Apple Silicon. The final piece of this
  puzzle was porting our POSIX threads cancelation support, since that
  works differently on ARM64 XNU vs. AMD64. Our semaphore support on
  Apple Silicon is also superior now compared to AMD64, thanks to the
  grand central dispatch library which lets *NSYNC locks go faster.

- The Cosmopolitan runtime is now more stable, particularly on Windows.
  To do this, thread local storage is mandatory at all runtime levels,
  and the innermost packages of the C library is no longer being built
  using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
  process startup phase, and then later on the runtime re-allocates it
  either statically or dynamically to support code using _Thread_local.
  fork() and execve() now do a better job cooperating with threads. We
  can now check how much stack memory is left in the process or thread
  when functions like kprintf() / execve() etc. call alloca(), so that
  ENOMEM can be raised, reduce a buffer size, or just print a warning.

- POSIX signal emulation is now implemented the same way kernels do it
  with pthread_kill() and raise(). Any thread can interrupt any other
  thread, regardless of what it's doing. If it's blocked on read/write
  then the killer thread will cancel its i/o operation so that EINTR can
  be returned in the mark thread immediately. If it's doing a tight CPU
  bound operation, then that's also interrupted by the signal delivery.
  Signal delivery works now by suspending a thread and pushing context
  data structures onto its stack, and redirecting its execution to a
  trampoline function, which calls SetThreadContext(GetCurrentThread())
  when it's done.

- We're now doing a better job managing locks and handles. On NetBSD we
  now close semaphore file descriptors in forked children. Semaphores on
  Windows can now be canceled immediately, which means mutexes/condition
  variables will now go faster. Apple Silicon semaphores can be canceled
  too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
  syscalls are now used on XNU when appropriate to ensure pthread_cancel
  requests aren't lost. The MbedTLS library has been updated to support
  POSIX thread cancelations. See tool/build/runitd.c for an example of
  how it can be used for production multi-threaded tls servers. Handles
  on Windows now leak less often across processes. All i/o operations on
  Windows are now overlapped, which means file pointers can no longer be
  inherited across dup() and fork() for the time being.

- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
  which means, for example, that posix_spawn() now goes 3x faster. POSIX
  spawn is also now more correct. Like Musl, it's now able to report the
  failure code of execve() via a pipe although our approach favors using
  shared memory to do that on systems that have a true vfork() function.

- We now spawn a thread to deliver SIGALRM to threads when setitimer()
  is used. This enables the most precise wakeups the OS makes possible.

- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
  it turned out the kernel would actually commit the PT_GNU_STACK size
  which caused RSS to be 6mb for every process. Now it's down to ~4kb.
  On Apple Silicon, we reduce the mandatory upstream thread size to the
  smallest possible size to reduce the memory overhead of Cosmo threads.
  The examples directory has a program called greenbean which can spawn
  a web server on Linux with 10,000 worker threads and have the memory
  usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
  thread-local storage is now optional; it won't be allocated until the
  pthread_setspecific/getspecific functions are called. On Windows, the
  threads that get spawned which are internal to the libc implementation
  use reserve rather than commit memory, which shaves a few hundred kb.

- sigaltstack() is now supported on Windows, however it's currently not
  able to be used to handle stack overflows, since crash signals are
  still generated by WIN32. However the crash handler will still switch
  to the alt stack, which is helpful in environments with tiny threads.

- Test binaries are now smaller. Many of the mandatory dependencies of
  the test runner have been removed. This ensures many programs can do a
  better job only linking the the thing they're testing. This caused the
  test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb

- long double is no longer used in the implementation details of libc,
  except in the APIs that define it. The old code that used long double
  for time (instead of struct timespec) has now been thoroughly removed.

- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
  backtraces itself, it'll just print a command you can run on the shell
  using our new `cosmoaddr2line` program to view the backtrace.

- Crash report signal handling now works in a much better way. Instead
  of terminating the process, it now relies on SA_RESETHAND so that the
  default SIG_IGN behavior can terminate the process if necessary.

- Our pledge() functionality has now been fully ported to AARCH64 Linux.
This commit is contained in:
Justine Tunney 2023-09-18 20:44:45 -07:00
parent c4eb838516
commit ec480f5aa0
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
638 changed files with 7925 additions and 8282 deletions

View file

@ -49,6 +49,6 @@ textwindows dontasan void WinSockInit(void) {
NTTRACE("WSAStartup()");
if ((rc = WSAStartup(VERSION, &kNtWsaData)) != 0 ||
kNtWsaData.wVersion != VERSION) {
ExitProcess(1 << 8);
_Exit(1);
}
}

View file

@ -1,341 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2022 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/bpf.internal.h"
#include "libc/calls/struct/filter.internal.h"
#include "libc/calls/struct/seccomp.internal.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/sigset.h"
#include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/likely.h"
#include "libc/macros.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/msghdr.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/audit.h"
#include "libc/sysv/consts/nr.h"
#include "libc/sysv/consts/nrlinux.h"
#include "libc/sysv/consts/pr.h"
#include "libc/sysv/consts/ptrace.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/errfuns.h"
#include "net/http/ip.h"
#ifdef __x86_64__
#define ORIG_RAX 120
#define RAX 80
#define RDI 112
#define RSI 104
#define RDX 96
#define R8 72
#define R9 64
#define __WALL 0x40000000
#define OFF(f) offsetof(struct seccomp_data, f)
#if 0
#define DEBUG(...) kprintf(__VA_ARGS__)
#else
#define DEBUG(...) donothing
#endif
#define ORDIE(x) \
do { \
if (UNLIKELY((x) == -1)) { \
DEBUG("%s:%d: %s failed %m\n", __FILE__, __LINE__, #x); \
notpossible; \
} \
} while (0)
static const struct sock_filter kInetBpf[] = {
// cargo culted architecture assertion
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(arch)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_X86_64, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
// block system calls from the future
BPF_STMT(BPF_LD + BPF_W + BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, __NR_linux_memfd_secret, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | 38), // ENOSYS
// only allow local and internet sockets
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_socket, 0, 5),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x001, 2, 0), // AF_UNIX
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x002, 1, 0), // AF_INET
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | 1), // EPERM
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
// support for these not implemented yet
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x133, 0, 1), // sendmmsg
BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ERRNO | 1), // EPERM
// trace syscalls with struct sockaddr
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x02e, 3, 0), // sendmsg
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x02c, 2, 0), // sendto
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x031, 1, 0), // bind
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x02a, 0, 1), // connect
BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_TRACE),
// default course of action
BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ALLOW),
};
static int PeekData(int pid, long addr, void *buf, size_t size) {
long i, j, w;
for (i = 0; i < size; i += sizeof(long)) {
if (sys_ptrace(PTRACE_PEEKTEXT, pid, addr + i, &w) != -1) {
for (j = 0; i + j < size && j < sizeof(long); ++j) {
((char *)buf)[i + j] = w;
w >>= 8;
}
} else {
return -1;
}
}
return 0;
}
static void LogProcessEvent(int main, int pid, int ws) {
DEBUG("trace: %s%06d%s 0x%06x", //
pid == main ? "\e[31;1m" : "", //
pid, //
pid == main ? "\e[0m" : "", //
ws);
if (WIFEXITED(ws)) {
DEBUG(" exit %d", WEXITSTATUS(ws));
}
if (WIFSIGNALED(ws)) {
DEBUG(" sig %d", WTERMSIG(ws));
}
if (WIFSTOPPED(ws)) {
DEBUG(" stop %s %s", strsignal(WSTOPSIG(ws)),
DescribePtraceEvent((ws & 0xff0000) >> 16));
}
if (WIFCONTINUED(ws)) {
DEBUG(" cont");
}
if (WCOREDUMP(ws)) {
DEBUG(" core");
}
DEBUG("\n");
}
static int Raise(int sig) {
sigset_t mask;
sigaction(sig, &(struct sigaction){0}, 0);
sigfillset(&mask);
sigprocmask(SIG_SETMASK, &mask, 0);
kill(getpid(), sig);
sigdelset(&mask, sig);
sigprocmask(SIG_SETMASK, &mask, 0);
_Exit(128 + sig);
}
static bool IsSockaddrAllowed(struct sockaddr_storage *addr) {
uint32_t ip;
if (addr->ss_family == AF_UNIX) {
return true;
}
if (addr->ss_family == AF_INET) {
ip = ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr);
if (IsPrivateIp(ip) || IsLoopbackIp(ip)) {
return true;
} else {
kprintf("warning: attempted to communicate with public ip "
"%hhd.%hhd.%hhd.%hhd\n",
ip >> 24, ip >> 16, ip >> 8, ip);
return false;
}
}
DEBUG("bad family %d\n", addr->ss_family);
return false;
}
static void OnSockaddrSyscall(int pid, int r1, int r2) {
long si, dx;
uint32_t addrlen;
struct sockaddr_storage addr = {0};
ORDIE(sys_ptrace(PTRACE_PEEKUSER, pid, r1, &si));
ORDIE(sys_ptrace(PTRACE_PEEKUSER, pid, r2, &dx));
addrlen = dx;
if (!si) {
// if address isn't supplied, it's probably safe. for example,
// send() is implemented in cosmo using sendto() with 0/0 addr
return;
}
if (PeekData(pid, si, &addr, MIN(addrlen, sizeof(addr))) == -1) {
DEBUG("failed to peek addr\n"); // probably an efault
goto Deny;
}
if (IsSockaddrAllowed(&addr)) {
return;
} else {
goto Deny;
}
Deny:
ORDIE(sys_ptrace(PTRACE_POKEUSER, pid, ORIG_RAX, -1));
}
static void OnSendmsg(int pid) {
long si;
struct msghdr msg = {0};
struct sockaddr_storage addr = {0};
ORDIE(sys_ptrace(PTRACE_PEEKUSER, pid, RSI, &si));
if (PeekData(pid, si, &msg, sizeof(msg)) == -1) {
DEBUG("failed to peek msg\n"); // probably an efault
goto Deny;
}
if (!msg.msg_name) {
// if address isn't supplied, it's probably fine.
return;
}
if (PeekData(pid, (long)msg.msg_name, &addr,
MIN(msg.msg_namelen, sizeof(addr))) == -1) {
DEBUG("failed to peek msg name\n"); // probably an efault
goto Deny;
}
if (IsSockaddrAllowed(&addr)) {
return;
} else {
goto Deny;
}
Deny:
ORDIE(sys_ptrace(PTRACE_POKEUSER, pid, ORIG_RAX, -1));
}
static void HandleSeccompTrace(int pid) {
long ax;
ORDIE(sys_ptrace(PTRACE_PEEKUSER, pid, ORIG_RAX, &ax));
switch (ax) {
case 0x031: // bind
case 0x02a: // connect
OnSockaddrSyscall(pid, RSI, RDX);
break;
case 0x02c: // sendto
OnSockaddrSyscall(pid, R8, R9);
break;
case 0x02e: // sendmsg
OnSendmsg(pid);
break;
default:
break;
}
}
static int WaitForTrace(int main) {
int ws, pid;
for (;;) {
// waits for state change on any child process or thread
// eintr isn't possible since we're blocking all signals
ORDIE(pid = waitpid(-1, &ws, __WALL));
LogProcessEvent(main, pid, ws);
if (WIFEXITED(ws)) {
if (pid == main) {
_Exit(WEXITSTATUS(ws));
}
} else if (WIFSIGNALED(ws)) {
if (pid == main) {
Raise(WTERMSIG(ws));
}
} else if (WIFSTOPPED(ws)) {
if ((ws >> 8) == (SIGTRAP | (PTRACE_EVENT_SECCOMP << 8))) {
return pid;
} else if ((ws >> 8) == (SIGTRAP | (PTRACE_EVENT_EXEC << 8))) {
ORDIE(ptrace(PTRACE_CONT, pid, 0, 0));
} else if ((ws >> 8) == (SIGTRAP | (PTRACE_EVENT_FORK << 8)) ||
(ws >> 8) == (SIGTRAP | (PTRACE_EVENT_VFORK << 8)) ||
(ws >> 8) == (SIGTRAP | (PTRACE_EVENT_CLONE << 8))) {
ORDIE(ptrace(PTRACE_CONT, pid, 0, 0));
} else {
ORDIE(ptrace(PTRACE_CONT, pid, 0, WSTOPSIG(ws)));
}
}
}
}
/**
* Disables internet access.
*
* Warning: This function uses ptrace to react to seccomp filter events.
* This approach is effective, but it's not bulletproof, since a highly
* motivated attacker could theoretically use threads to modify sockaddr
* in the short time between it being monitored and the actual syscall.
*/
int nointernet(void) {
int ws, act, main;
sigset_t set, old;
struct sock_fprog prog = {.filter = kInetBpf, .len = ARRAYLEN(kInetBpf)};
// seccomp bpf and ptrace are pretty much just linux for now.
if (!IsLinux() || !__is_linux_2_6_23()) {
return enosys();
}
// prevent crash handlers from intercepting sigsegv
ORDIE(sigfillset(&set));
ORDIE(sigprocmask(SIG_SETMASK, &set, &old));
// create traced child that'll replace this program
if ((main = fork()) == -1) {
ORDIE(sigprocmask(SIG_SETMASK, &old, 0));
return -1;
}
if (!main) {
if (sys_ptrace(PTRACE_TRACEME, 0, 0, 0) == -1) {
// there can be only one
// throw sigsegv on eperm
// we're already being traced
asm("hlt");
}
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
ORDIE(prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog));
ORDIE(kill(getpid(), SIGSTOP));
ORDIE(sigprocmask(SIG_SETMASK, &old, 0));
// return to caller from child
return 0;
}
// wait for child to stop itself
ORDIE(waitpid(main, &ws, 0));
if (WIFSIGNALED(ws)) {
// child couldn't enable ptrace or seccomp
sigprocmask(SIG_SETMASK, &old, 0);
return eperm();
}
npassert(WIFSTOPPED(ws));
// parent process becomes monitor of subprocess tree. all signals
// continue to be blocked since we assume they'll also be sent to
// children, which will die, and then the monitor dies afterwards
ORDIE(sys_ptrace(PTRACE_SETOPTIONS, main, 0,
PTRACE_O_TRACESECCOMP | PTRACE_O_TRACEFORK |
PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE |
PTRACE_O_TRACEEXEC));
for (act = main;;) {
ORDIE(sys_ptrace(PTRACE_CONT, act, 0, 0));
act = WaitForTrace(main);
HandleSeccompTrace(act);
}
}
#endif /* __x86_64__ */

View file

@ -40,19 +40,25 @@
#include "libc/sock/sendfile.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/posixthread.internal.h"
// sendfile() isn't specified as raising eintr
static textwindows int SendfileBlock(int64_t handle,
struct NtOverlapped *overlapped) {
struct PosixThread *pt;
uint32_t i, got, flags = 0;
if (WSAGetLastError() != kNtErrorIoPending &&
WSAGetLastError() != WSAEINPROGRESS) {
NTTRACE("TransmitFile failed %lm");
return __winsockerr();
}
pt = _pthread_self();
pt->abort_errno = 0;
pt->ioverlap = overlapped;
pt->iohandle = handle;
for (;;) {
i = WSAWaitForMultipleEvents(1, &overlapped->hEvent, true,
__SIG_POLLING_INTERVAL_MS, true);
__SIG_IO_INTERVAL_MS, true);
if (i == kNtWaitFailed) {
NTTRACE("WSAWaitForMultipleEvents failed %lm");
return __winsockerr();
@ -65,9 +71,14 @@ static textwindows int SendfileBlock(int64_t handle,
break;
}
}
pt->ioverlap = 0;
pt->iohandle = 0;
if (WSAGetOverlappedResult(handle, overlapped, &got, false, &flags)) {
return got;
} else {
if (WSAGetLastError() == kNtErrorOperationAborted) {
errno = pt->abort_errno;
}
return -1;
}
}
@ -99,7 +110,7 @@ static dontinline textwindows ssize_t sys_sendfile_nt(
return ebadf();
}
struct NtOverlapped ov = {
.Pointer = (void *)(intptr_t)offset,
.Pointer = offset,
.hEvent = WSACreateEvent(),
};
if (TransmitFile(oh, ih, uptobytes, 0, &ov, 0, 0)) {

View file

@ -2,9 +2,6 @@
#define COSMOPOLITAN_LIBC_SOCK_SOCK_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/*───────────────────────────────────────────────────────────────────────────│─╗
cosmopolitan § system api » berkeley sockets
*/
#define INET_ADDRSTRLEN 22
#define IFHWADDRLEN 6
@ -27,7 +24,6 @@ uint32_t inet_addr(const char *);
int parseport(const char *);
uint32_t *GetHostIps(void);
int nointernet(void);
int socket(int, int, int);
int listen(int, int);
int shutdown(int, int);

View file

@ -20,6 +20,7 @@
#include "libc/calls/bo.internal.h"
#include "libc/calls/internal.h"
#include "libc/calls/sig.internal.h"
#include "libc/calls/struct/timespec.h"
#include "libc/errno.h"
#include "libc/nt/enum/wait.h"
#include "libc/nt/enum/wsa.h"
@ -35,66 +36,91 @@
#include "libc/str/str.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/posixthread.internal.h"
#include "libc/thread/tls.h"
static textwindows void __wsablock_abort(int64_t handle,
struct NtOverlapped *overlapped) {
unassert(CancelIoEx(handle, overlapped) ||
GetLastError() == kNtErrorNotFound);
}
textwindows int __wsablock(struct Fd *fd, struct NtOverlapped *overlapped,
textwindows int __wsablock(struct Fd *f, struct NtOverlapped *overlapped,
uint32_t *flags, int sigops, uint32_t timeout) {
bool nonblock;
int e, rc, err;
uint32_t i, got;
int rc, abort_errno;
uint32_t waitfor;
struct PosixThread *pt;
struct timespec now, remain, interval, deadline;
if (WSAGetLastError() != kNtErrorIoPending) {
// our i/o operation never happened because it failed
return __winsockerr();
}
BEGIN_BLOCKING_OPERATION;
// our i/o operation is in flight and it needs to block
abort_errno = EAGAIN;
if (fd->flags & O_NONBLOCK) {
__wsablock_abort(fd->handle, overlapped);
nonblock = !!(f->flags & O_NONBLOCK);
pt = _pthread_self();
pt->abort_errno = EAGAIN;
interval = timespec_frommillis(__SIG_IO_INTERVAL_MS);
deadline = timeout
? timespec_add(timespec_real(), timespec_frommillis(timeout))
: timespec_max;
e = errno;
BlockingOperation:
if (!nonblock) {
pt->ioverlap = overlapped;
pt->iohandle = f->handle;
}
if (nonblock) {
CancelIoEx(f->handle, overlapped);
} else if (_check_interrupts(sigops)) {
Interrupted:
abort_errno = errno; // EINTR or ECANCELED
__wsablock_abort(fd->handle, overlapped);
pt->abort_errno = errno; // EINTR or ECANCELED
CancelIoEx(f->handle, overlapped);
} else {
for (;;) {
i = WSAWaitForMultipleEvents(1, &overlapped->hEvent, true,
__SIG_POLLING_INTERVAL_MS, true);
if (i == kNtWaitFailed || i == kNtWaitTimeout) {
now = timespec_real();
if (timespec_cmp(now, deadline) >= 0) {
CancelIoEx(f->handle, overlapped);
nonblock = true;
break;
}
remain = timespec_sub(deadline, now);
if (timespec_cmp(remain, interval) >= 0) {
waitfor = __SIG_IO_INTERVAL_MS;
} else {
waitfor = timespec_tomillis(remain);
}
i = WSAWaitForMultipleEvents(1, &overlapped->hEvent, true, waitfor, true);
if (i == kNtWaitFailed) {
// Failure should be an impossible condition, but MSDN lists
// WSAENETDOWN and WSA_NOT_ENOUGH_MEMORY as possible errors.
pt->abort_errno = WSAGetLastError();
CancelIoEx(f->handle, overlapped);
nonblock = true;
break;
} else if (i == kNtWaitTimeout) {
if (_check_interrupts(sigops)) {
goto Interrupted;
}
if (i == kNtWaitFailed) {
// Failure should be an impossible condition, but MSDN lists
// WSAENETDOWN and WSA_NOT_ENOUGH_MEMORY as possible errors,
// which we're going to hope are ephemeral.
SleepEx(__SIG_POLLING_INTERVAL_MS, false);
}
if (timeout) {
if (timeout <= __SIG_POLLING_INTERVAL_MS) {
__wsablock_abort(fd->handle, overlapped);
break;
}
timeout -= __SIG_POLLING_INTERVAL_MS;
}
continue;
} else {
break;
}
}
}
pt->ioverlap = 0;
pt->iohandle = 0;
// overlapped is allocated on stack by caller, so it's important that
// we wait for win32 to acknowledge that it's done using that memory.
if (WSAGetOverlappedResult(fd->handle, overlapped, &got, true, flags)) {
if (WSAGetOverlappedResult(f->handle, overlapped, &got, nonblock, flags)) {
rc = got;
} else {
rc = -1;
if (WSAGetLastError() == kNtErrorOperationAborted) {
errno = abort_errno;
err = WSAGetLastError();
if (err == kNtErrorOperationAborted) {
errno = pt->abort_errno;
} else if (err == kNtErrorIoIncomplete) {
errno = e;
goto BlockingOperation;
}
}
END_BLOCKING_OPERATION;
return rc;
}