2022-10-05 13:37:15 +00:00
|
|
|
/*-*- 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. │
|
|
|
|
╚─────────────────────────────────────────────────────────────────────────────*/
|
2022-11-08 18:09:47 +00:00
|
|
|
#include "libc/assert.h"
|
2022-10-05 13:37:15 +00:00
|
|
|
#include "libc/calls/asan.internal.h"
|
2022-11-08 18:09:47 +00:00
|
|
|
#include "libc/calls/blockcancel.internal.h"
|
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.
2023-09-19 03:44:45 +00:00
|
|
|
#include "libc/calls/blocksigs.internal.h"
|
2022-11-08 18:09:47 +00:00
|
|
|
#include "libc/calls/calls.h"
|
2022-11-06 02:49:41 +00:00
|
|
|
#include "libc/calls/cp.internal.h"
|
2022-10-08 04:29:40 +00:00
|
|
|
#include "libc/calls/state.internal.h"
|
2022-10-05 13:37:15 +00:00
|
|
|
#include "libc/calls/struct/timespec.h"
|
|
|
|
#include "libc/calls/struct/timespec.internal.h"
|
|
|
|
#include "libc/calls/struct/timeval.h"
|
|
|
|
#include "libc/calls/struct/timeval.internal.h"
|
|
|
|
#include "libc/dce.h"
|
2022-10-08 04:29:40 +00:00
|
|
|
#include "libc/errno.h"
|
2022-10-05 13:37:15 +00:00
|
|
|
#include "libc/intrin/describeflags.internal.h"
|
|
|
|
#include "libc/intrin/strace.internal.h"
|
2022-11-08 18:09:47 +00:00
|
|
|
#include "libc/intrin/weaken.h"
|
|
|
|
#include "libc/macros.internal.h"
|
|
|
|
#include "libc/nt/ntdll.h"
|
|
|
|
#include "libc/str/str.h"
|
2022-10-05 13:37:15 +00:00
|
|
|
#include "libc/sysv/consts/clock.h"
|
|
|
|
#include "libc/sysv/consts/timer.h"
|
|
|
|
#include "libc/sysv/errfuns.h"
|
2022-11-08 18:09:47 +00:00
|
|
|
#include "libc/thread/thread.h"
|
2022-10-08 09:40:44 +00:00
|
|
|
#include "libc/thread/tls.h"
|
2022-10-05 13:37:15 +00:00
|
|
|
|
2022-11-08 18:09:47 +00:00
|
|
|
static int64_t g_nanosleep_latency;
|
|
|
|
|
|
|
|
static errno_t sys_clock_nanosleep(int clock, int flags,
|
|
|
|
const struct timespec *req,
|
|
|
|
struct timespec *rem) {
|
|
|
|
int e, rc;
|
|
|
|
BEGIN_CANCELLATION_POINT;
|
|
|
|
e = errno;
|
|
|
|
if (IsLinux() || IsFreebsd() || IsNetbsd()) {
|
|
|
|
rc = __sys_clock_nanosleep(clock, flags, req, rem);
|
|
|
|
} else if (IsXnu()) {
|
|
|
|
rc = sys_clock_nanosleep_xnu(clock, flags, req, rem);
|
|
|
|
} else if (IsOpenbsd()) {
|
|
|
|
rc = sys_clock_nanosleep_openbsd(clock, flags, req, rem);
|
2023-07-10 02:47:46 +00:00
|
|
|
} else if (IsWindows()) {
|
2022-11-08 18:09:47 +00:00
|
|
|
rc = sys_clock_nanosleep_nt(clock, flags, req, rem);
|
2023-07-10 02:47:46 +00:00
|
|
|
} else {
|
|
|
|
rc = enosys();
|
2022-11-08 18:09:47 +00:00
|
|
|
}
|
|
|
|
if (rc == -1) {
|
|
|
|
rc = errno;
|
|
|
|
errno = e;
|
|
|
|
}
|
|
|
|
END_CANCELLATION_POINT;
|
|
|
|
return rc;
|
|
|
|
}
|
|
|
|
|
|
|
|
// determine sched_yield() vs. clock_nanosleep() threshold
|
|
|
|
// 1ns sys_clock_nanosleep() on Windows takes milliseconds :'(
|
|
|
|
// 1ns sys_clock_nanosleep() on Linux/FreeBSD takes tens of microseconds
|
|
|
|
// 1ns sys_clock_nanosleep() on OpenBSD/NetBSD takes tens of milliseconds D:
|
|
|
|
static struct timespec GetNanosleepLatency(void) {
|
|
|
|
errno_t rc;
|
|
|
|
int64_t nanos;
|
|
|
|
struct timespec x, y, w = {0, 1};
|
|
|
|
if (!(nanos = g_nanosleep_latency)) {
|
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.
2023-09-19 03:44:45 +00:00
|
|
|
BLOCK_SIGNALS;
|
2023-10-03 02:25:19 +00:00
|
|
|
for (;;) {
|
|
|
|
unassert(!clock_gettime(CLOCK_REALTIME_PRECISE, &x));
|
2022-11-08 18:09:47 +00:00
|
|
|
rc = sys_clock_nanosleep(CLOCK_REALTIME, 0, &w, 0);
|
2023-10-03 02:25:19 +00:00
|
|
|
unassert(!rc || rc == EINTR);
|
2022-11-08 18:09:47 +00:00
|
|
|
if (!rc) {
|
2023-10-03 02:25:19 +00:00
|
|
|
unassert(!clock_gettime(CLOCK_REALTIME_PRECISE, &y));
|
2022-11-08 18:09:47 +00:00
|
|
|
nanos = timespec_tonanos(timespec_sub(y, x));
|
|
|
|
g_nanosleep_latency = nanos;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
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.
2023-09-19 03:44:45 +00:00
|
|
|
ALLOW_SIGNALS;
|
2022-11-08 18:09:47 +00:00
|
|
|
}
|
|
|
|
return timespec_fromnanos(nanos);
|
|
|
|
}
|
|
|
|
|
|
|
|
static errno_t CheckCancel(void) {
|
|
|
|
if (_weaken(pthread_testcancel_np)) {
|
|
|
|
return _weaken(pthread_testcancel_np)();
|
|
|
|
} else {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static errno_t SpinNanosleep(int clock, int flags, const struct timespec *req,
|
|
|
|
struct timespec *rem) {
|
|
|
|
errno_t rc;
|
|
|
|
struct timespec now, start, elapsed;
|
|
|
|
if ((rc = CheckCancel())) {
|
|
|
|
if (rc == EINTR && !flags && rem) {
|
|
|
|
*rem = *req;
|
|
|
|
}
|
|
|
|
return rc;
|
|
|
|
}
|
2023-10-03 02:25:19 +00:00
|
|
|
unassert(!clock_gettime(CLOCK_REALTIME, &start));
|
2022-11-08 18:09:47 +00:00
|
|
|
for (;;) {
|
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.
2023-09-19 03:44:45 +00:00
|
|
|
pthread_yield();
|
2023-10-03 02:25:19 +00:00
|
|
|
unassert(!clock_gettime(CLOCK_REALTIME, &now));
|
2022-11-08 18:09:47 +00:00
|
|
|
if (flags & TIMER_ABSTIME) {
|
|
|
|
if (timespec_cmp(now, *req) >= 0) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
if ((rc = CheckCancel())) {
|
|
|
|
return rc;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if (timespec_cmp(now, start) < 0) continue;
|
|
|
|
elapsed = timespec_sub(now, start);
|
|
|
|
if ((rc = CheckCancel())) {
|
|
|
|
if (rc == EINTR && rem) {
|
|
|
|
if (timespec_cmp(elapsed, *req) >= 0) {
|
|
|
|
bzero(rem, sizeof(*rem));
|
|
|
|
} else {
|
|
|
|
*rem = elapsed;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return rc;
|
|
|
|
}
|
|
|
|
if (timespec_cmp(elapsed, *req) >= 0) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static bool ShouldUseSpinNanosleep(int clock, int flags,
|
|
|
|
const struct timespec *req) {
|
|
|
|
errno_t e;
|
|
|
|
struct timespec now;
|
|
|
|
if (IsWindows()) {
|
|
|
|
// Our spin technique here is intended to take advantage of the fact
|
|
|
|
// that sched_yield() takes about a hundred nanoseconds. But Windows
|
|
|
|
// SleepEx(0, 0) a.k.a. NtYieldExecution() takes a whole millisecond
|
|
|
|
// and it matters not whether our intent is to yielding or sleeping,
|
|
|
|
// since we use the SleepEx() function to implement both. Therefore,
|
|
|
|
// there's no reason to use SpinNanosleep() on Windows.
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
if (clock != CLOCK_REALTIME && //
|
|
|
|
clock != CLOCK_REALTIME_PRECISE && //
|
|
|
|
clock != CLOCK_MONOTONIC && //
|
|
|
|
clock != CLOCK_MONOTONIC_RAW && //
|
|
|
|
clock != CLOCK_MONOTONIC_PRECISE) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
if (!flags) {
|
|
|
|
return timespec_cmp(*req, GetNanosleepLatency()) < 0;
|
|
|
|
}
|
|
|
|
// We need a clock_gettime() system call to perform this check if the
|
|
|
|
// sleep request is an absolute timestamp. So we avoid doing that on
|
|
|
|
// systems where sleep latency isn't too outrageous.
|
|
|
|
if (timespec_cmp(GetNanosleepLatency(), timespec_fromnanos(50 * 1000)) < 0) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
e = errno;
|
2023-10-03 02:25:19 +00:00
|
|
|
if (clock_gettime(clock, &now)) {
|
2022-11-08 18:09:47 +00:00
|
|
|
// punt to the nanosleep system call
|
|
|
|
errno = e;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return timespec_cmp(*req, now) < 0 ||
|
|
|
|
timespec_cmp(timespec_sub(*req, now), GetNanosleepLatency()) < 0;
|
|
|
|
}
|
|
|
|
|
2022-10-05 13:37:15 +00:00
|
|
|
/**
|
|
|
|
* Sleeps for particular amount of time.
|
|
|
|
*
|
|
|
|
* Here's how you could sleep for one second:
|
|
|
|
*
|
|
|
|
* clock_nanosleep(0, 0, &(struct timespec){1}, 0);
|
|
|
|
*
|
|
|
|
* Your sleep will be interrupted automatically if you do something like
|
|
|
|
* press ctrl-c during the wait. That's an `EINTR` error and it lets you
|
|
|
|
* immediately react to status changes. This is always the case, even if
|
|
|
|
* you're using `SA_RESTART` since this is a `@norestart` system call.
|
|
|
|
*
|
|
|
|
* void OnCtrlC(int sig) {} // EINTR only happens after delivery
|
|
|
|
* signal(SIGINT, OnCtrlC); // do delivery rather than kill proc
|
|
|
|
* printf("save me from sleeping forever by pressing ctrl-c\n");
|
|
|
|
* clock_nanosleep(0, 0, &(struct timespec){INT_MAX}, 0);
|
|
|
|
* printf("you're my hero\n");
|
|
|
|
*
|
|
|
|
* If you want to perform an uninterruptible sleep without having to use
|
|
|
|
* sigprocmask() to block all signals then this function provides a good
|
|
|
|
* solution to that problem. For example:
|
|
|
|
*
|
|
|
|
* struct timespec rel, now, abs;
|
|
|
|
* clock_gettime(CLOCK_REALTIME, &now);
|
2022-11-06 02:49:41 +00:00
|
|
|
* rel = timespec_frommillis(100);
|
|
|
|
* abs = timespec_add(now, rel);
|
2022-10-05 13:37:15 +00:00
|
|
|
* while (clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &abs, 0));
|
|
|
|
*
|
|
|
|
* will accurately spin on `EINTR` errors. That way you're not impeding
|
2023-02-23 14:03:06 +00:00
|
|
|
* signal delivery and you're not loosing precision on the wait timeout.
|
2022-10-05 13:37:15 +00:00
|
|
|
* This function has first-class support on Linux, FreeBSD, and NetBSD;
|
|
|
|
* on OpenBSD it's good; on XNU it's bad; and on Windows it's ugly.
|
|
|
|
*
|
|
|
|
* @param clock should be `CLOCK_REALTIME` and you may consult the docs
|
|
|
|
* of your preferred platforms to see what other clocks might work
|
|
|
|
* @param flags can be 0 for relative and `TIMER_ABSTIME` for absolute
|
|
|
|
* @param req can be a relative or absolute time, depending on `flags`
|
2022-10-06 02:25:07 +00:00
|
|
|
* @param rem shall be updated with the remainder of unslept time when
|
|
|
|
* (1) it's non-null; (2) `flags` is 0; and (3) -1 w/ `EINTR` is
|
|
|
|
* returned; if this function returns 0 then `rem` is undefined;
|
|
|
|
* if flags is `TIMER_ABSTIME` then `rem` is ignored
|
2022-10-08 04:29:40 +00:00
|
|
|
* @return 0 on success, or errno on error
|
2022-10-05 13:37:15 +00:00
|
|
|
* @raise EINTR when a signal got delivered while we were waiting
|
2022-11-06 02:49:41 +00:00
|
|
|
* @raise ECANCELED if thread was cancelled in masked mode
|
2022-10-05 13:37:15 +00:00
|
|
|
* @raise ENOTSUP if `clock` is known but we can't use it here
|
2022-10-12 17:44:54 +00:00
|
|
|
* @raise EFAULT if `req` or null or bad memory was passed
|
2022-10-05 13:37:15 +00:00
|
|
|
* @raise EINVAL if `clock` is unknown to current platform
|
|
|
|
* @raise EINVAL if `flags` has an unrecognized value
|
|
|
|
* @raise EINVAL if `req->tv_nsec ∉ [0,1000000000)`
|
|
|
|
* @raise ENOSYS on bare metal
|
2022-11-04 08:04:43 +00:00
|
|
|
* @cancellationpoint
|
2022-10-08 04:29:40 +00:00
|
|
|
* @returnserrno
|
2022-10-05 13:37:15 +00:00
|
|
|
* @norestart
|
|
|
|
*/
|
2022-10-08 04:29:40 +00:00
|
|
|
errno_t clock_nanosleep(int clock, int flags, const struct timespec *req,
|
|
|
|
struct timespec *rem) {
|
2022-11-08 18:09:47 +00:00
|
|
|
int rc;
|
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.
2023-09-19 03:44:45 +00:00
|
|
|
// threads on win32 stacks call this so we can't asan check *ts
|
2022-11-11 05:52:47 +00:00
|
|
|
LOCKTRACE("clock_nanosleep(%s, %s, %s) → ...", DescribeClockName(clock),
|
|
|
|
DescribeSleepFlags(flags), DescribeTimespec(0, req));
|
2022-11-08 18:09:47 +00:00
|
|
|
if (IsMetal()) {
|
|
|
|
rc = ENOSYS;
|
2022-10-05 13:37:15 +00:00
|
|
|
} else if (clock == 127 || //
|
|
|
|
(flags & ~TIMER_ABSTIME) || //
|
|
|
|
req->tv_sec < 0 || //
|
|
|
|
!(0 <= req->tv_nsec && req->tv_nsec <= 999999999)) {
|
2022-11-08 18:09:47 +00:00
|
|
|
rc = EINVAL;
|
|
|
|
} else if (ShouldUseSpinNanosleep(clock, flags, req)) {
|
|
|
|
rc = SpinNanosleep(clock, flags, req, rem);
|
2022-10-05 13:37:15 +00:00
|
|
|
} else {
|
2022-11-08 18:09:47 +00:00
|
|
|
rc = sys_clock_nanosleep(clock, flags, req, rem);
|
2022-10-08 04:29:40 +00:00
|
|
|
}
|
2023-10-03 02:25:19 +00:00
|
|
|
TIMETRACE("clock_nanosleep(%s, %s, %s, [%s]) → %s", DescribeClockName(clock),
|
|
|
|
DescribeSleepFlags(flags), DescribeTimespec(0, req),
|
|
|
|
DescribeTimespec(rc, rem), DescribeErrno(rc));
|
2022-10-05 13:37:15 +00:00
|
|
|
return rc;
|
|
|
|
}
|