Skip to content

Commit c260144

Browse files
committed
Introduce sigtimedwait() on Windows
1 parent 37e2660 commit c260144

17 files changed

+280
-130
lines changed

libc/calls/poll-nt.c

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,6 @@
4444
#include "libc/thread/posixthread.internal.h"
4545
#ifdef __x86_64__
4646

47-
#define POLL_INTERVAL_MS 10
48-
4947
// <sync libc/sysv/consts.sh>
5048
#define POLLERR_ 0x0001 // implied in events
5149
#define POLLHUP_ 0x0002 // implied in events

libc/calls/poll.c

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@
5858
* @return fds[𝑖].revents is always zero initializaed and then will
5959
* be populated with POLL{IN,OUT,PRI,HUP,ERR,NVAL} if something
6060
* was determined about the file descriptor
61-
* @raise EINVAL if we exceeded the 64 socket limit on Windows
6261
* @raise ECANCELED if thread was cancelled in masked mode
6362
* @raise EINVAL if `nfds` exceeded `RLIMIT_NOFILE`
6463
* @raise ENOMEM on failure to allocate memory

libc/calls/ppoll.c

Lines changed: 75 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -35,80 +35,14 @@
3535
#include "libc/sysv/consts/sig.h"
3636
#include "libc/sysv/errfuns.h"
3737

38-
/**
39-
* Checks status on multiple file descriptors at once.
40-
*
41-
* This function is the same as saying:
42-
*
43-
* sigset_t old;
44-
* sigprocmask(SIG_SETMASK, sigmask, &old);
45-
* poll(fds, nfds, timeout);
46-
* sigprocmask(SIG_SETMASK, old, 0);
47-
*
48-
* Except it happens atomically when the kernel supports doing that. On
49-
* kernels such as XNU and NetBSD which don't, this wrapper will fall
50-
* back to using the example above. If you need ironclad assurances of
51-
* signal mask atomicity, then consider using pselect() which Cosmo Libc
52-
* guarantees to be atomic on all supported platforms.
53-
*
54-
* Servers that need to handle an unbounded number of client connections
55-
* should just create a separate thread for each client. poll(), ppoll()
56-
* and select() aren't scalable i/o solutions on any platform.
57-
*
58-
* On Windows it's only possible to poll 64 file descriptors at a time;
59-
* it's a limitation imposed by WSAPoll(). Cosmopolitan Libc's ppoll()
60-
* polyfill can go higher in some cases; for example, It's possible to
61-
* poll 64 sockets and 64 pipes/terminals at the same time. Furthermore,
62-
* elements whose fd field is set to a negative number are ignored and
63-
* will not count against this limit.
64-
*
65-
* One of the use cases for poll() is to quickly check if a number of
66-
* file descriptors are valid. The canonical way to do this is to set
67-
* events to 0 which prevents blocking and causes only the invalid,
68-
* hangup, and error statuses to be checked.
69-
*
70-
* On XNU, the POLLHUP and POLLERR statuses aren't checked unless either
71-
* POLLIN, POLLOUT, or POLLPRI are specified in the events field. Cosmo
72-
* will however polyfill the checking of POLLNVAL on XNU with the events
73-
* doesn't specify any of the above i/o events.
74-
*
75-
* When XNU and BSD OSes report POLLHUP, they will always set POLLIN too
76-
* when POLLIN is requested, even in cases when there isn't unread data.
77-
*
78-
* @param fds[𝑖].fd should be a socket, input pipe, or conosle input
79-
* and if it's a negative number then the entry is ignored, plus
80-
* revents will be set to zero
81-
* @param fds[𝑖].events flags can have POLLIN, POLLOUT, POLLPRI,
82-
* POLLRDNORM, POLLWRNORM, POLLRDBAND, POLLWRBAND as well as
83-
* POLLERR, POLLHUP, and POLLNVAL although the latter are
84-
* always implied (assuming fd≥0) so they're ignored here
85-
* @param timeout_ms if 0 means don't wait and negative waits forever
86-
* @return number of `fds` whose revents field has been set to a nonzero
87-
* number, 0 if the timeout elapsed without events, or -1 w/ errno
88-
* @return fds[𝑖].revents is always zero initializaed and then will
89-
* be populated with POLL{IN,OUT,PRI,HUP,ERR,NVAL} if something
90-
* was determined about the file descriptor
91-
* @param timeout if null will block indefinitely
92-
* @param sigmask may be null in which case no mask change happens
93-
* @raise EINVAL if we exceeded the 64 socket limit on Windows
94-
* @raise ECANCELED if thread was cancelled in masked mode
95-
* @raise EINVAL if `nfds` exceeded `RLIMIT_NOFILE`
96-
* @raise ENOMEM on failure to allocate memory
97-
* @raise EINVAL if `*timeout` is invalid
98-
* @raise EINTR if signal was delivered
99-
* @cancelationpoint
100-
* @asyncsignalsafe
101-
* @norestart
102-
*/
103-
int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout,
104-
const sigset_t *sigmask) {
38+
static int ppoll_impl(struct pollfd *fds, size_t nfds,
39+
const struct timespec *timeout, const sigset_t *sigmask) {
10540
int e, fdcount;
10641
sigset_t oldmask;
10742
struct timespec ts, *tsp;
108-
BEGIN_CANCELATION_POINT;
10943

11044
// validate timeout
111-
if (timeout && timeout->tv_nsec >= 1000000000)
45+
if (timeout && timeout->tv_nsec >= 1000000000ull)
11246
return einval();
11347

11448
// The OpenBSD poll() man pages claims it'll ignore POLLERR, POLLHUP,
@@ -192,6 +126,78 @@ int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout,
192126
}
193127
}
194128

129+
return fdcount;
130+
}
131+
132+
/**
133+
* Checks status on multiple file descriptors at once.
134+
*
135+
* This function is the same as saying:
136+
*
137+
* sigset_t old;
138+
* sigprocmask(SIG_SETMASK, sigmask, &old);
139+
* poll(fds, nfds, timeout);
140+
* sigprocmask(SIG_SETMASK, old, 0);
141+
*
142+
* Except it happens atomically when the kernel supports doing that. On
143+
* kernels such as XNU and NetBSD which don't, this wrapper will fall
144+
* back to using the example above. If you need ironclad assurances of
145+
* signal mask atomicity, then consider using pselect() which Cosmo Libc
146+
* guarantees to be atomic on all supported platforms.
147+
*
148+
* Servers that need to handle an unbounded number of client connections
149+
* should just create a separate thread for each client. poll(), ppoll()
150+
* and select() aren't scalable i/o solutions on any platform.
151+
*
152+
* On Windows it's only possible to poll 64 file descriptors at a time;
153+
* it's a limitation imposed by WSAPoll(). Cosmopolitan Libc's ppoll()
154+
* polyfill can go higher in some cases; for example, It's possible to
155+
* poll 64 sockets and 64 pipes/terminals at the same time. Furthermore,
156+
* elements whose fd field is set to a negative number are ignored and
157+
* will not count against this limit.
158+
*
159+
* One of the use cases for poll() is to quickly check if a number of
160+
* file descriptors are valid. The canonical way to do this is to set
161+
* events to 0 which prevents blocking and causes only the invalid,
162+
* hangup, and error statuses to be checked.
163+
*
164+
* On XNU, the POLLHUP and POLLERR statuses aren't checked unless either
165+
* POLLIN, POLLOUT, or POLLPRI are specified in the events field. Cosmo
166+
* will however polyfill the checking of POLLNVAL on XNU with the events
167+
* doesn't specify any of the above i/o events.
168+
*
169+
* When XNU and BSD OSes report POLLHUP, they will always set POLLIN too
170+
* when POLLIN is requested, even in cases when there isn't unread data.
171+
*
172+
* @param fds[𝑖].fd should be a socket, input pipe, or conosle input
173+
* and if it's a negative number then the entry is ignored, plus
174+
* revents will be set to zero
175+
* @param fds[𝑖].events flags can have POLLIN, POLLOUT, POLLPRI,
176+
* POLLRDNORM, POLLWRNORM, POLLRDBAND, POLLWRBAND as well as
177+
* POLLERR, POLLHUP, and POLLNVAL although the latter are
178+
* always implied (assuming fd≥0) so they're ignored here
179+
* @param timeout_ms if 0 means don't wait and negative waits forever
180+
* @return number of `fds` whose revents field has been set to a nonzero
181+
* number, 0 if the timeout elapsed without events, or -1 w/ errno
182+
* @return fds[𝑖].revents is always zero initializaed and then will
183+
* be populated with POLL{IN,OUT,PRI,HUP,ERR,NVAL} if something
184+
* was determined about the file descriptor
185+
* @param timeout if null will block indefinitely
186+
* @param sigmask may be null in which case no mask change happens
187+
* @raise ECANCELED if thread was cancelled in masked mode
188+
* @raise EINVAL if `nfds` exceeded `RLIMIT_NOFILE`
189+
* @raise ENOMEM on failure to allocate memory
190+
* @raise EINVAL if `*timeout` is invalid
191+
* @raise EINTR if signal was delivered
192+
* @cancelationpoint
193+
* @asyncsignalsafe
194+
* @norestart
195+
*/
196+
int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout,
197+
const sigset_t *sigmask) {
198+
int fdcount;
199+
BEGIN_CANCELATION_POINT;
200+
fdcount = ppoll_impl(fds, nfds, timeout, sigmask);
195201
END_CANCELATION_POINT;
196202
STRACE("ppoll(%s, %'zu, %s, %s) → %d% lm",
197203
DescribePollFds(fdcount, fds, nfds), nfds,

libc/calls/sig.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,15 @@ static textwindows int __sig_killer(struct PosixThread *pt, int sig, int sic) {
302302
return 0;
303303
}
304304

305+
// we can't preempt threads that masked sig or are blocked
306+
if (atomic_load_explicit(&pt->tib->tib_sigmask, memory_order_acquire) &
307+
(1ull << (sig - 1))) {
308+
atomic_fetch_or_explicit(&pt->tib->tib_sigpending, 1ull << (sig - 1),
309+
memory_order_relaxed);
310+
__sig_cancel(pt, sig, flags);
311+
return 0;
312+
}
313+
305314
// if there's no handler then killing a thread kills the process
306315
if (rva == (intptr_t)SIG_DFL) {
307316
STRACE("terminating on %G due to no handler", sig);

libc/calls/sigtimedwait-nt.c

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
2+
│ vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi │
3+
╞══════════════════════════════════════════════════════════════════════════════╡
4+
│ Copyright 2024 Justine Alexandra Roberts Tunney │
5+
│ │
6+
│ Permission to use, copy, modify, and/or distribute this software for │
7+
│ any purpose with or without fee is hereby granted, provided that the │
8+
│ above copyright notice and this permission notice appear in all copies. │
9+
│ │
10+
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
11+
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
12+
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
13+
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
14+
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
15+
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
16+
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
17+
│ PERFORMANCE OF THIS SOFTWARE. │
18+
╚─────────────────────────────────────────────────────────────────────────────*/
19+
#include "libc/calls/calls.h"
20+
#include "libc/calls/internal.h"
21+
#include "libc/calls/sig.internal.h"
22+
#include "libc/calls/struct/siginfo.h"
23+
#include "libc/calls/struct/sigset.internal.h"
24+
#include "libc/calls/struct/timespec.internal.h"
25+
#include "libc/calls/syscall_support-nt.internal.h"
26+
#include "libc/intrin/atomic.h"
27+
#include "libc/macros.h"
28+
#include "libc/nt/runtime.h"
29+
#include "libc/nt/synchronization.h"
30+
#include "libc/str/str.h"
31+
#include "libc/sysv/consts/sicode.h"
32+
#include "libc/sysv/consts/sig.h"
33+
#include "libc/sysv/errfuns.h"
34+
#include "libc/thread/posixthread.internal.h"
35+
36+
textwindows static int sys_sigtimedwait_nt_check(sigset_t syncsigs,
37+
siginfo_t *opt_info,
38+
sigset_t waitmask) {
39+
int sig;
40+
if (_check_cancel() == -1)
41+
return -1;
42+
if ((sig = __sig_get(waitmask))) {
43+
if ((1ull << (sig - 1)) & syncsigs) {
44+
if (opt_info) {
45+
memset(opt_info, 0, sizeof(*opt_info));
46+
opt_info->si_signo = sig;
47+
opt_info->si_code = SI_TKILL;
48+
opt_info->si_uid = sys_getuid_nt();
49+
}
50+
return sig;
51+
}
52+
int handler_was_called = __sig_relay(sig, SI_TKILL, waitmask);
53+
if (_check_cancel() == -1)
54+
return -1;
55+
if (handler_was_called)
56+
return eintr();
57+
}
58+
return 0;
59+
}
60+
61+
textwindows static int sys_sigtimedwait_nt_impl(sigset_t syncsigs,
62+
siginfo_t *opt_info,
63+
struct timespec deadline,
64+
sigset_t waitmask,
65+
intptr_t semaphore) {
66+
for (;;) {
67+
int sig;
68+
if ((sig = sys_sigtimedwait_nt_check(syncsigs, opt_info, waitmask)))
69+
return sig;
70+
struct timespec now = sys_clock_gettime_monotonic_nt();
71+
if (timespec_cmp(now, deadline) >= 0)
72+
return eagain();
73+
struct timespec remain = timespec_sub(deadline, now);
74+
int64_t millis = timespec_tomillis(remain);
75+
uint32_t waitms = MIN(millis, 0xffffffffu);
76+
uint32_t wi = WaitForSingleObject(semaphore, waitms);
77+
if (wi == -1u)
78+
return __winerr();
79+
if (wi)
80+
return eagain();
81+
}
82+
}
83+
84+
textwindows int sys_sigtimedwait_nt(const sigset_t *set, siginfo_t *opt_info,
85+
const struct timespec *opt_timeout) {
86+
int rc;
87+
intptr_t sem;
88+
struct PosixThread *pt;
89+
struct timespec deadline;
90+
sigset_t syncsigs, waitmask;
91+
BLOCK_SIGNALS;
92+
if (opt_timeout) {
93+
deadline = timespec_add(sys_clock_gettime_monotonic_nt(), *opt_timeout);
94+
} else {
95+
deadline = timespec_max;
96+
}
97+
if ((sem = CreateSemaphore(0, 0, 1, 0))) {
98+
syncsigs = *set & ~(1ull << (SIGTHR - 1)); // internal to pthreads
99+
waitmask = ~syncsigs & _SigMask;
100+
pt = _pthread_self();
101+
pt->pt_blkmask = waitmask;
102+
pt->pt_semaphore = sem = CreateSemaphore(0, 0, 1, 0);
103+
atomic_store_explicit(&pt->pt_blocker, PT_BLOCKER_SEM,
104+
memory_order_release);
105+
rc = sys_sigtimedwait_nt_impl(syncsigs, opt_info, deadline, waitmask, sem);
106+
atomic_store_explicit(&pt->pt_blocker, 0, memory_order_release);
107+
CloseHandle(sem);
108+
} else {
109+
rc = __winerr();
110+
}
111+
ALLOW_SIGNALS;
112+
return rc;
113+
}

libc/calls/sigtimedwait.c

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,48 +27,62 @@
2727
#include "libc/str/str.h"
2828
#include "libc/sysv/errfuns.h"
2929

30+
int sys_sigtimedwait_nt(const sigset_t *, siginfo_t *, const struct timespec *);
31+
3032
/**
3133
* Waits for signal synchronously, w/ timeout.
3234
*
35+
* This function does not change the thread signal mask. Signals that
36+
* aren't masked, which aren't in `set`, will be handled normally, in
37+
* which case this function will raise `EINTR`.
38+
*
39+
* This function silently ignores attempts to synchronously wait for
40+
* SIGTHR which is used internally by the POSIX threads implementation.
41+
*
3342
* @param set is signals for which we'll be waiting
34-
* @param info if not null shall receive info about signal
35-
* @param timeout is relative deadline and null means wait forever
43+
* @param opt_info if not null shall receive info about signal
44+
* @param opt_timeout is relative deadline and null means wait forever
3645
* @return signal number on success, or -1 w/ errno
3746
* @raise EINTR if an asynchronous signal was delivered instead
3847
* @raise ECANCELED if thread was cancelled in masked mode
3948
* @raise EINVAL if nanoseconds parameter was out of range
40-
* @raise EAGAIN if deadline expired
41-
* @raise ENOSYS on Windows, XNU, OpenBSD, Metal
49+
* @raise EAGAIN if timeout elapsed
50+
* @raise ENOSYS on XNU, OpenBSD, and Metal
4251
* @raise EFAULT if invalid memory was supplied
4352
* @cancelationpoint
53+
* @norestart
4454
*/
45-
int sigtimedwait(const sigset_t *set, siginfo_t *info,
46-
const struct timespec *timeout) {
55+
int sigtimedwait(const sigset_t *set, siginfo_t *opt_info,
56+
const struct timespec *opt_timeout) {
4757
int rc;
4858
char strsig[21];
4959
struct timespec ts;
5060
union siginfo_meta si = {0};
5161
BEGIN_CANCELATION_POINT;
5262

53-
if (IsLinux() || IsFreebsd() || IsNetbsd()) {
54-
if (timeout) {
63+
// validate timeout
64+
if (opt_timeout && opt_timeout->tv_nsec >= 1000000000ull) {
65+
rc = einval();
66+
} else if (IsLinux() || IsFreebsd() || IsNetbsd()) {
67+
if (opt_timeout) {
5568
// 1. Linux needs its size parameter
5669
// 2. NetBSD modifies timeout argument
57-
ts = *timeout;
70+
ts = *opt_timeout;
5871
rc = sys_sigtimedwait(set, &si, &ts, 8);
5972
} else {
6073
rc = sys_sigtimedwait(set, &si, 0, 8);
6174
}
62-
if (rc != -1 && info) {
63-
__siginfo2cosmo(info, &si);
64-
}
75+
if (rc != -1 && opt_info)
76+
__siginfo2cosmo(opt_info, &si);
77+
} else if (IsWindows()) {
78+
rc = sys_sigtimedwait_nt(set, opt_info, opt_timeout);
6579
} else {
6680
rc = enosys();
6781
}
6882

6983
END_CANCELATION_POINT;
7084
STRACE("sigtimedwait(%s, [%s], %s) → %s% m", DescribeSigset(0, set),
71-
DescribeSiginfo(rc, info), DescribeTimespec(0, timeout),
85+
DescribeSiginfo(rc, opt_info), DescribeTimespec(0, opt_timeout),
7286
strsignal_r(rc, strsig));
7387
return rc;
7488
}

0 commit comments

Comments
 (0)