2020-06-15 14:18:57 +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 2020 Justine Alexandra Roberts Tunney │
|
|
|
|
│ │
|
2020-12-28 01:18:44 +00:00
|
|
|
│ 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. │
|
2020-06-15 14:18:57 +00:00
|
|
|
│ │
|
2020-12-28 01:18:44 +00:00
|
|
|
│ 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. │
|
2020-06-15 14:18:57 +00:00
|
|
|
╚─────────────────────────────────────────────────────────────────────────────*/
|
|
|
|
#include "libc/assert.h"
|
|
|
|
#include "libc/calls/calls.h"
|
|
|
|
#include "libc/calls/internal.h"
|
Make improvements
- We now serialize the file descriptor table when spawning / executing
processes on Windows. This means you can now inherit more stuff than
just standard i/o. It's needed by bash, which duplicates the console
to file descriptor #255. We also now do a better job serializing the
environment variables, so you're less likely to encounter E2BIG when
using your bash shell. We also no longer coerce environ to uppercase
- execve() on Windows now remotely controls its parent process to make
them spawn a replacement for itself. Then it'll be able to terminate
immediately once the spawn succeeds, without having to linger around
for the lifetime as a shell process for proxying the exit code. When
process worker thread running in the parent sees the child die, it's
given a handle to the new child, to replace it in the process table.
- execve() and posix_spawn() on Windows will now provide CreateProcess
an explicit handle list. This allows us to remove handle locks which
enables better fork/spawn concurrency, with seriously correct thread
safety. Other codebases like Go use the same technique. On the other
hand fork() still favors the conventional WIN32 inheritence approach
which can be a little bit messy, but is *controlled* by guaranteeing
perfectly clean slates at both the spawning and execution boundaries
- sigset_t is now 64 bits. Having it be 128 bits was a mistake because
there's no reason to use that and it's only supported by FreeBSD. By
using the system word size, signal mask manipulation on Windows goes
very fast. Furthermore @asyncsignalsafe funcs have been rewritten on
Windows to take advantage of signal masking, now that it's much more
pleasant to use.
- All the overlapped i/o code on Windows has been rewritten for pretty
good signal and cancelation safety. We're now able to ensure overlap
data structures are cleaned up so long as you don't longjmp() out of
out of a signal handler that interrupted an i/o operation. Latencies
are also improved thanks to the removal of lots of "busy wait" code.
Waits should be optimal for everything except poll(), which shall be
the last and final demon we slay in the win32 i/o horror show.
- getrusage() on Windows is now able to report RUSAGE_CHILDREN as well
as RUSAGE_SELF, thanks to aggregation in the process manager thread.
2023-10-08 12:36:18 +00:00
|
|
|
#include "libc/calls/struct/sigset.h"
|
2022-05-23 22:06:11 +00:00
|
|
|
#include "libc/calls/syscall-sysv.internal.h"
|
2020-06-15 14:18:57 +00:00
|
|
|
#include "libc/dce.h"
|
2021-10-15 02:36:49 +00:00
|
|
|
#include "libc/errno.h"
|
2021-02-01 11:33:13 +00:00
|
|
|
#include "libc/intrin/asan.internal.h"
|
2022-05-13 00:52:13 +00:00
|
|
|
#include "libc/intrin/asancodes.h"
|
2022-08-20 19:32:51 +00:00
|
|
|
#include "libc/intrin/bits.h"
|
2022-10-10 05:38:28 +00:00
|
|
|
#include "libc/intrin/bsr.h"
|
2022-04-13 05:11:00 +00:00
|
|
|
#include "libc/intrin/describeflags.internal.h"
|
2022-11-02 05:36:03 +00:00
|
|
|
#include "libc/intrin/directmap.internal.h"
|
2023-10-04 14:07:43 +00:00
|
|
|
#include "libc/intrin/kprintf.h"
|
2022-08-20 19:32:51 +00:00
|
|
|
#include "libc/intrin/likely.h"
|
|
|
|
#include "libc/intrin/safemacros.internal.h"
|
2022-09-13 06:10:38 +00:00
|
|
|
#include "libc/intrin/strace.internal.h"
|
2022-08-20 19:32:51 +00:00
|
|
|
#include "libc/intrin/weaken.h"
|
2022-04-20 16:56:53 +00:00
|
|
|
#include "libc/limits.h"
|
2021-09-28 05:58:51 +00:00
|
|
|
#include "libc/log/backtrace.internal.h"
|
2021-10-15 02:36:49 +00:00
|
|
|
#include "libc/log/libfatal.internal.h"
|
2021-10-14 00:27:13 +00:00
|
|
|
#include "libc/log/log.h"
|
2021-03-01 07:42:35 +00:00
|
|
|
#include "libc/macros.internal.h"
|
2023-10-04 14:07:43 +00:00
|
|
|
#include "libc/nt/enum/memflags.h"
|
|
|
|
#include "libc/nt/enum/pageflags.h"
|
|
|
|
#include "libc/nt/memory.h"
|
2022-04-15 06:39:48 +00:00
|
|
|
#include "libc/nt/process.h"
|
|
|
|
#include "libc/nt/runtime.h"
|
|
|
|
#include "libc/nt/struct/processmemorycounters.h"
|
2022-04-13 05:11:00 +00:00
|
|
|
#include "libc/runtime/internal.h"
|
2021-09-04 20:20:47 +00:00
|
|
|
#include "libc/runtime/memtrack.internal.h"
|
2020-08-25 11:23:25 +00:00
|
|
|
#include "libc/runtime/runtime.h"
|
2023-08-12 06:14:02 +00:00
|
|
|
#include "libc/runtime/zipos.internal.h"
|
2023-06-10 16:15:19 +00:00
|
|
|
#include "libc/stdckdint.h"
|
2022-08-20 19:32:51 +00:00
|
|
|
#include "libc/stdio/rand.h"
|
2020-06-15 14:18:57 +00:00
|
|
|
#include "libc/str/str.h"
|
2023-07-26 20:54:49 +00:00
|
|
|
#include "libc/sysv/consts/auxv.h"
|
2020-06-15 14:18:57 +00:00
|
|
|
#include "libc/sysv/consts/map.h"
|
2022-04-13 05:11:00 +00:00
|
|
|
#include "libc/sysv/consts/o.h"
|
2020-08-25 11:23:25 +00:00
|
|
|
#include "libc/sysv/consts/prot.h"
|
Make improvements
- We now serialize the file descriptor table when spawning / executing
processes on Windows. This means you can now inherit more stuff than
just standard i/o. It's needed by bash, which duplicates the console
to file descriptor #255. We also now do a better job serializing the
environment variables, so you're less likely to encounter E2BIG when
using your bash shell. We also no longer coerce environ to uppercase
- execve() on Windows now remotely controls its parent process to make
them spawn a replacement for itself. Then it'll be able to terminate
immediately once the spawn succeeds, without having to linger around
for the lifetime as a shell process for proxying the exit code. When
process worker thread running in the parent sees the child die, it's
given a handle to the new child, to replace it in the process table.
- execve() and posix_spawn() on Windows will now provide CreateProcess
an explicit handle list. This allows us to remove handle locks which
enables better fork/spawn concurrency, with seriously correct thread
safety. Other codebases like Go use the same technique. On the other
hand fork() still favors the conventional WIN32 inheritence approach
which can be a little bit messy, but is *controlled* by guaranteeing
perfectly clean slates at both the spawning and execution boundaries
- sigset_t is now 64 bits. Having it be 128 bits was a mistake because
there's no reason to use that and it's only supported by FreeBSD. By
using the system word size, signal mask manipulation on Windows goes
very fast. Furthermore @asyncsignalsafe funcs have been rewritten on
Windows to take advantage of signal masking, now that it's much more
pleasant to use.
- All the overlapped i/o code on Windows has been rewritten for pretty
good signal and cancelation safety. We're now able to ensure overlap
data structures are cleaned up so long as you don't longjmp() out of
out of a signal handler that interrupted an i/o operation. Latencies
are also improved thanks to the removal of lots of "busy wait" code.
Waits should be optimal for everything except poll(), which shall be
the last and final demon we slay in the win32 i/o horror show.
- getrusage() on Windows is now able to report RUSAGE_CHILDREN as well
as RUSAGE_SELF, thanks to aggregation in the process manager thread.
2023-10-08 12:36:18 +00:00
|
|
|
#include "libc/sysv/consts/sig.h"
|
2023-07-26 20:54:49 +00:00
|
|
|
#include "libc/sysv/consts/ss.h"
|
2020-06-15 14:18:57 +00:00
|
|
|
#include "libc/sysv/errfuns.h"
|
2022-09-13 06:10:38 +00:00
|
|
|
#include "libc/thread/thread.h"
|
2020-06-15 14:18:57 +00:00
|
|
|
|
2022-05-12 13:43:59 +00:00
|
|
|
#define MAP_ANONYMOUS_linux 0x00000020
|
|
|
|
#define MAP_ANONYMOUS_openbsd 0x00001000
|
|
|
|
#define MAP_GROWSDOWN_linux 0x00000100
|
|
|
|
#define MAP_STACK_freebsd 0x00000400
|
|
|
|
#define MAP_STACK_openbsd 0x00004000
|
|
|
|
|
2021-10-14 00:27:13 +00:00
|
|
|
#define IP(X) (intptr_t)(X)
|
|
|
|
#define VIP(X) (void *)IP(X)
|
|
|
|
#define ALIGNED(p) (!(IP(p) & (FRAMESIZE - 1)))
|
|
|
|
#define SHADE(x) (((intptr_t)(x) >> 3) + 0x7fff8000)
|
|
|
|
#define FRAME(x) ((int)((intptr_t)(x) >> 16))
|
|
|
|
|
2023-08-14 03:31:27 +00:00
|
|
|
static inline pureconst unsigned long __rounddown2pow(unsigned long x) {
|
2022-10-10 05:38:28 +00:00
|
|
|
return x ? 1ul << _bsrl(x) : 0;
|
|
|
|
}
|
|
|
|
|
2023-08-14 03:31:27 +00:00
|
|
|
static wontreturn void __mmap_die(const char *s) {
|
2022-09-13 06:10:38 +00:00
|
|
|
if (_weaken(__die)) _weaken(__die)();
|
2022-04-15 06:39:48 +00:00
|
|
|
STRACE("%s %m", s);
|
2023-08-19 13:41:06 +00:00
|
|
|
_Exit(199);
|
2021-10-14 00:27:13 +00:00
|
|
|
}
|
|
|
|
|
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
|
|
|
static inline bool __overlaps_existing_mapping(char *p, size_t n) {
|
2022-05-19 23:57:49 +00:00
|
|
|
int a, b, i;
|
2023-07-26 20:54:49 +00:00
|
|
|
unassert(n > 0);
|
2022-05-19 23:57:49 +00:00
|
|
|
a = FRAME(p);
|
|
|
|
b = FRAME(p + (n - 1));
|
2023-08-14 03:31:27 +00:00
|
|
|
i = __find_memory(&_mmi, a);
|
2022-05-19 23:57:49 +00:00
|
|
|
if (i < _mmi.i) {
|
|
|
|
if (a <= _mmi.p[i].x && _mmi.p[i].x <= b) return true;
|
|
|
|
if (a <= _mmi.p[i].y && _mmi.p[i].y <= b) return true;
|
|
|
|
if (_mmi.p[i].x <= a && b <= _mmi.p[i].y) return true;
|
|
|
|
}
|
|
|
|
return false;
|
2021-10-14 00:27:13 +00:00
|
|
|
}
|
|
|
|
|
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
|
|
|
static bool __choose_memory(int x, int n, int align, int *res) {
|
2022-05-27 20:25:46 +00:00
|
|
|
// TODO: improve performance
|
2022-05-19 23:57:49 +00:00
|
|
|
int i, start, end;
|
2023-07-26 20:54:49 +00:00
|
|
|
unassert(align > 0);
|
2021-10-14 00:27:13 +00:00
|
|
|
if (_mmi.i) {
|
2022-05-19 23:57:49 +00:00
|
|
|
|
|
|
|
// find the start of the automap memory region
|
2023-08-14 03:31:27 +00:00
|
|
|
i = __find_memory(&_mmi, x);
|
2021-10-14 00:27:13 +00:00
|
|
|
if (i < _mmi.i) {
|
2022-05-19 23:57:49 +00:00
|
|
|
|
|
|
|
// check to see if there's space available before the first entry
|
2023-06-10 16:15:19 +00:00
|
|
|
if (!ckd_add(&start, x, align - 1)) {
|
2022-05-19 23:57:49 +00:00
|
|
|
start &= -align;
|
2023-06-10 16:15:19 +00:00
|
|
|
if (!ckd_add(&end, start, n - 1)) {
|
2022-05-19 23:57:49 +00:00
|
|
|
if (end < _mmi.p[i].x) {
|
|
|
|
*res = start;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
2021-10-14 00:27:13 +00:00
|
|
|
}
|
2022-05-19 23:57:49 +00:00
|
|
|
|
|
|
|
// check to see if there's space available between two entries
|
2021-10-14 00:27:13 +00:00
|
|
|
while (++i < _mmi.i) {
|
2023-06-10 16:15:19 +00:00
|
|
|
if (!ckd_add(&start, _mmi.p[i - 1].y, 1) &&
|
|
|
|
!ckd_add(&start, start, align - 1)) {
|
2022-05-19 23:57:49 +00:00
|
|
|
start &= -align;
|
2023-06-10 16:15:19 +00:00
|
|
|
if (!ckd_add(&end, start, n - 1)) {
|
2022-05-19 23:57:49 +00:00
|
|
|
if (end < _mmi.p[i].x) {
|
|
|
|
*res = start;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
2021-10-14 00:27:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-05-19 23:57:49 +00:00
|
|
|
|
|
|
|
// otherwise append after the last entry if space is available
|
2023-06-10 16:15:19 +00:00
|
|
|
if (!ckd_add(&start, _mmi.p[i - 1].y, 1) &&
|
|
|
|
!ckd_add(&start, start, align - 1)) {
|
2022-05-19 23:57:49 +00:00
|
|
|
start &= -align;
|
2023-06-10 16:15:19 +00:00
|
|
|
if (!ckd_add(&end, start, n - 1)) {
|
2022-05-19 23:57:49 +00:00
|
|
|
*res = start;
|
|
|
|
return true;
|
|
|
|
}
|
2021-10-14 00:27:13 +00:00
|
|
|
}
|
2022-05-19 23:57:49 +00:00
|
|
|
|
2021-10-14 00:27:13 +00:00
|
|
|
} else {
|
2022-05-19 23:57:49 +00:00
|
|
|
// if memtrack is empty, then just assign the requested address
|
|
|
|
// assuming it doesn't overflow
|
2023-06-10 16:15:19 +00:00
|
|
|
if (!ckd_add(&start, x, align - 1)) {
|
2022-05-19 23:57:49 +00:00
|
|
|
start &= -align;
|
2023-06-10 16:15:19 +00:00
|
|
|
if (!ckd_add(&end, start, n - 1)) {
|
2022-05-19 23:57:49 +00:00
|
|
|
*res = start;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
2021-10-14 00:27:13 +00:00
|
|
|
}
|
2022-05-19 23:57:49 +00:00
|
|
|
|
|
|
|
return false;
|
2021-10-14 00:27:13 +00:00
|
|
|
}
|
|
|
|
|
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
|
|
|
static bool __auto_map(int count, int align, int *res) {
|
2023-08-14 03:31:27 +00:00
|
|
|
return __choose_memory(FRAME(kAutomapStart), count, align, res) &&
|
2022-05-19 23:57:49 +00:00
|
|
|
*res + count <= FRAME(kAutomapStart + (kAutomapSize - 1));
|
2021-10-14 00:27:13 +00:00
|
|
|
}
|
2020-06-15 14:18:57 +00:00
|
|
|
|
2023-09-21 14:30:39 +00:00
|
|
|
static void *__finish_memory(void *addr, size_t size, int prot, int flags,
|
|
|
|
int fd, int64_t off, int f, int x, int n,
|
|
|
|
struct DirectMap dm) {
|
2021-10-15 02:36:49 +00:00
|
|
|
if (!IsWindows() && (flags & MAP_FIXED)) {
|
2023-08-14 03:31:27 +00:00
|
|
|
if (__untrack_memories(addr, size)) {
|
|
|
|
__mmap_die("FIXED UNTRACK FAILED");
|
2021-10-15 02:36:49 +00:00
|
|
|
}
|
|
|
|
}
|
2023-08-14 03:31:27 +00:00
|
|
|
if (__track_memory(&_mmi, x, x + (n - 1), dm.maphandle, prot, flags, false,
|
|
|
|
false, off, size)) {
|
2021-10-15 02:36:49 +00:00
|
|
|
if (sys_munmap(addr, n) == -1) {
|
2023-08-14 03:31:27 +00:00
|
|
|
__mmap_die("TRACK MUNMAP FAILED");
|
2021-10-15 02:36:49 +00:00
|
|
|
}
|
|
|
|
return MAP_FAILED;
|
|
|
|
}
|
2022-09-13 06:10:38 +00:00
|
|
|
if (_weaken(__asan_map_shadow) && !OverlapsShadowSpace(addr, size)) {
|
|
|
|
_weaken(__asan_map_shadow)((intptr_t)addr, size);
|
2021-10-15 02:36:49 +00:00
|
|
|
}
|
|
|
|
return addr;
|
|
|
|
}
|
|
|
|
|
2023-09-21 14:30:39 +00:00
|
|
|
static void *__map_memory(void *addr, size_t size, int prot, int flags, int fd,
|
|
|
|
int64_t off, int f, int x, int n) {
|
2022-05-12 13:43:59 +00:00
|
|
|
struct DirectMap dm;
|
|
|
|
dm = sys_mmap(addr, size, prot, f, fd, off);
|
2022-05-29 15:14:55 +00:00
|
|
|
if (VERY_UNLIKELY(dm.addr == MAP_FAILED)) {
|
2022-05-12 13:43:59 +00:00
|
|
|
if (IsWindows() && (flags & MAP_FIXED)) {
|
2023-08-14 03:31:27 +00:00
|
|
|
__mmap_die("can't recover from MAP_FIXED errors on Windows");
|
2022-05-12 13:43:59 +00:00
|
|
|
}
|
|
|
|
return MAP_FAILED;
|
|
|
|
}
|
2022-05-29 15:14:55 +00:00
|
|
|
if (VERY_UNLIKELY(dm.addr != addr)) {
|
2023-08-14 03:31:27 +00:00
|
|
|
__mmap_die("KERNEL DIDN'T RESPECT MAP_FIXED");
|
2022-05-12 13:43:59 +00:00
|
|
|
}
|
2023-08-14 03:31:27 +00:00
|
|
|
return __finish_memory(addr, size, prot, flags, fd, off, f, x, n, dm);
|
2022-05-12 13:43:59 +00:00
|
|
|
}
|
|
|
|
|
2021-10-15 02:36:49 +00:00
|
|
|
/**
|
|
|
|
* Maps memory from system, one frame at a time.
|
|
|
|
*
|
|
|
|
* This is useful on Windows since it allows us to partially unmap or
|
|
|
|
* punch holes into existing mappings.
|
|
|
|
*/
|
2023-09-21 14:30:39 +00:00
|
|
|
static textwindows dontinline void *__map_memories(char *addr, size_t size,
|
|
|
|
int prot, int flags, int fd,
|
|
|
|
int64_t off, int f, int x,
|
|
|
|
int n) {
|
2022-04-15 06:39:48 +00:00
|
|
|
size_t i, m;
|
2022-03-20 15:01:14 +00:00
|
|
|
int64_t oi, sz;
|
2021-10-15 02:36:49 +00:00
|
|
|
struct DirectMap dm;
|
2022-04-13 05:11:00 +00:00
|
|
|
bool iscow, readonlyfile;
|
2022-04-15 06:39:48 +00:00
|
|
|
m = (size_t)(n - 1) << 16;
|
2023-07-26 20:54:49 +00:00
|
|
|
unassert(m < size);
|
|
|
|
unassert(m + FRAMESIZE >= size);
|
2022-03-20 15:01:14 +00:00
|
|
|
oi = fd == -1 ? 0 : off + m;
|
|
|
|
sz = size - m;
|
|
|
|
dm = sys_mmap(addr + m, sz, prot, f, fd, oi);
|
2022-04-13 05:11:00 +00:00
|
|
|
if (dm.addr == MAP_FAILED) return MAP_FAILED;
|
2022-05-12 13:43:59 +00:00
|
|
|
iscow = (flags & MAP_TYPE) != MAP_SHARED && fd != -1;
|
|
|
|
readonlyfile = (flags & MAP_TYPE) == MAP_SHARED && fd != -1 &&
|
2022-04-13 05:11:00 +00:00
|
|
|
(g_fds.p[fd].flags & O_ACCMODE) == O_RDONLY;
|
2023-08-14 03:31:27 +00:00
|
|
|
if (__track_memory(&_mmi, x + (n - 1), x + (n - 1), dm.maphandle, prot, flags,
|
|
|
|
readonlyfile, iscow, oi, sz) == -1) {
|
|
|
|
__mmap_die("__map_memories unrecoverable #1");
|
2021-10-15 02:36:49 +00:00
|
|
|
}
|
|
|
|
for (i = 0; i < m; i += FRAMESIZE) {
|
2022-03-20 15:01:14 +00:00
|
|
|
oi = fd == -1 ? 0 : off + i;
|
|
|
|
sz = FRAMESIZE;
|
|
|
|
dm = sys_mmap(addr + i, sz, prot, f, fd, oi);
|
2021-10-15 02:36:49 +00:00
|
|
|
if (dm.addr == MAP_FAILED ||
|
2023-08-14 03:31:27 +00:00
|
|
|
__track_memory(&_mmi, x + i / FRAMESIZE, x + i / FRAMESIZE,
|
|
|
|
dm.maphandle, prot, flags, readonlyfile, iscow, oi,
|
|
|
|
sz) == -1) {
|
|
|
|
__mmap_die("__map_memories unrecoverable #2");
|
2021-10-15 02:36:49 +00:00
|
|
|
}
|
|
|
|
}
|
2022-09-13 06:10:38 +00:00
|
|
|
if (_weaken(__asan_map_shadow) && !OverlapsShadowSpace(addr, size)) {
|
|
|
|
_weaken(__asan_map_shadow)((intptr_t)addr, size);
|
2021-10-15 02:36:49 +00:00
|
|
|
}
|
|
|
|
return addr;
|
|
|
|
}
|
|
|
|
|
2023-09-21 14:30:39 +00:00
|
|
|
inline void *__mmap_unlocked(void *addr, size_t size, int prot, int flags,
|
|
|
|
int fd, int64_t off) {
|
2022-04-13 05:11:00 +00:00
|
|
|
char *p = addr;
|
2020-06-15 14:18:57 +00:00
|
|
|
struct DirectMap dm;
|
2023-07-30 01:44:15 +00:00
|
|
|
size_t requested_size;
|
2022-05-19 23:57:49 +00:00
|
|
|
bool needguard, clashes;
|
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
|
|
|
int a, f, n, x, pagesize;
|
2022-05-19 23:57:49 +00:00
|
|
|
size_t virtualused, virtualneed;
|
2022-04-24 16:59:22 +00:00
|
|
|
|
2022-05-29 15:14:55 +00:00
|
|
|
if (VERY_UNLIKELY(!size)) {
|
2023-06-03 15:12:13 +00:00
|
|
|
STRACE("can't mmap zero bytes");
|
2022-04-24 16:59:22 +00:00
|
|
|
return VIP(einval());
|
|
|
|
}
|
|
|
|
|
2022-05-29 15:14:55 +00:00
|
|
|
if (VERY_UNLIKELY(!ALIGNED(p))) {
|
2023-06-03 15:12:13 +00:00
|
|
|
STRACE("cosmo mmap is 64kb aligned");
|
2022-04-24 16:59:22 +00:00
|
|
|
return VIP(einval());
|
|
|
|
}
|
|
|
|
|
2023-06-03 15:12:13 +00:00
|
|
|
if (VERY_UNLIKELY(!IsLegalSize(size))) {
|
|
|
|
STRACE("mmap size isn't legal");
|
2022-04-24 16:59:22 +00:00
|
|
|
return VIP(einval());
|
|
|
|
}
|
|
|
|
|
2023-06-03 15:12:13 +00:00
|
|
|
if (VERY_UNLIKELY(!IsLegalPointer(p))) {
|
|
|
|
STRACE("mmap addr isn't 48-bit");
|
2022-04-24 16:59:22 +00:00
|
|
|
return VIP(einval());
|
|
|
|
}
|
|
|
|
|
2023-06-03 15:12:13 +00:00
|
|
|
if ((flags & (MAP_SHARED | MAP_PRIVATE)) == (MAP_SHARED | MAP_PRIVATE)) {
|
|
|
|
flags = MAP_SHARED; // cf. MAP_SHARED_VALIDATE
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
|
2023-07-30 01:44:15 +00:00
|
|
|
requested_size = size;
|
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
|
|
|
pagesize = getauxval(AT_PAGESZ);
|
2023-06-03 15:12:13 +00:00
|
|
|
if (flags & MAP_ANONYMOUS) {
|
|
|
|
fd = -1;
|
|
|
|
off = 0;
|
2022-05-19 23:57:49 +00:00
|
|
|
size = ROUNDUP(size, FRAMESIZE);
|
2023-06-03 15:12:13 +00:00
|
|
|
if ((flags & MAP_TYPE) == MAP_FILE) {
|
|
|
|
STRACE("need MAP_PRIVATE or MAP_SHARED");
|
|
|
|
return VIP(einval());
|
2020-08-25 11:23:25 +00:00
|
|
|
}
|
2022-05-19 23:57:49 +00:00
|
|
|
} else if (__isfdkind(fd, kFdZip)) {
|
2023-06-03 15:12:13 +00:00
|
|
|
STRACE("mmap fd is zipos handle");
|
2022-05-19 23:57:49 +00:00
|
|
|
return VIP(einval());
|
2023-06-03 15:12:13 +00:00
|
|
|
} else if (VERY_UNLIKELY(off < 0)) {
|
|
|
|
STRACE("mmap negative offset");
|
2022-05-19 23:57:49 +00:00
|
|
|
return VIP(einval());
|
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
|
|
|
} else if (off & ((IsWindows() ? FRAMESIZE : pagesize) - 1)) {
|
2023-07-30 01:44:15 +00:00
|
|
|
STRACE("mmap offset isn't properly aligned");
|
2023-06-03 15:12:13 +00:00
|
|
|
return VIP(einval());
|
|
|
|
} else if (VERY_UNLIKELY(INT64_MAX - size < off)) {
|
|
|
|
STRACE("mmap too large");
|
2022-04-24 16:59:22 +00:00
|
|
|
return VIP(einval());
|
|
|
|
}
|
|
|
|
|
|
|
|
if (__virtualmax < LONG_MAX &&
|
2023-08-14 03:31:27 +00:00
|
|
|
(ckd_add(&virtualneed, (virtualused = __get_memtrack_size(&_mmi)),
|
|
|
|
size) ||
|
2022-04-24 16:59:22 +00:00
|
|
|
virtualneed > __virtualmax)) {
|
2023-06-03 15:12:13 +00:00
|
|
|
STRACE("mmap %'zu size + %'zu inuse exceeds virtual memory limit %'zu",
|
|
|
|
size, virtualused, __virtualmax);
|
2022-04-24 16:59:22 +00:00
|
|
|
return VIP(enomem());
|
|
|
|
}
|
|
|
|
|
2023-08-14 03:31:27 +00:00
|
|
|
clashes = OverlapsImageSpace(p, size) || __overlaps_existing_mapping(p, size);
|
2022-05-19 23:57:49 +00:00
|
|
|
|
2022-05-22 11:51:02 +00:00
|
|
|
if ((flags & MAP_FIXED_NOREPLACE) == MAP_FIXED_NOREPLACE && clashes) {
|
2023-06-03 15:12:13 +00:00
|
|
|
STRACE("mmap noreplace overlaps existing");
|
2022-05-19 23:57:49 +00:00
|
|
|
return VIP(eexist());
|
|
|
|
}
|
|
|
|
|
2023-06-10 16:15:19 +00:00
|
|
|
if (ckd_add(&n, (int)(size >> 16), (int)!!(size & (FRAMESIZE - 1)))) {
|
2023-06-03 15:12:13 +00:00
|
|
|
STRACE("mmap range overflows");
|
2022-05-19 23:57:49 +00:00
|
|
|
return VIP(einval());
|
|
|
|
}
|
|
|
|
|
2023-08-14 03:31:27 +00:00
|
|
|
a = MAX(1, __rounddown2pow(size) >> 16);
|
2022-04-24 16:59:22 +00:00
|
|
|
f = (flags & ~MAP_FIXED_NOREPLACE) | MAP_FIXED;
|
|
|
|
if (flags & MAP_FIXED) {
|
|
|
|
x = FRAME(p);
|
|
|
|
if (IsWindows()) {
|
2023-08-14 03:31:27 +00:00
|
|
|
if (__untrack_memories(p, size)) {
|
|
|
|
__mmap_die("FIXED UNTRACK FAILED");
|
2021-10-14 00:27:13 +00:00
|
|
|
}
|
2022-04-13 05:11:00 +00:00
|
|
|
}
|
2023-07-30 01:44:15 +00:00
|
|
|
} else if (p && !clashes && !OverlapsShadowSpace(p, size)) {
|
2022-04-24 16:59:22 +00:00
|
|
|
x = FRAME(p);
|
2023-08-14 03:31:27 +00:00
|
|
|
} else if (!__auto_map(n, a, &x)) {
|
2022-05-19 23:57:49 +00:00
|
|
|
STRACE("automap has no room for %d frames with %d alignment", n, a);
|
2022-04-24 16:59:22 +00:00
|
|
|
return VIP(enomem());
|
|
|
|
}
|
|
|
|
|
2022-05-12 13:43:59 +00:00
|
|
|
needguard = false;
|
2023-06-03 15:12:13 +00:00
|
|
|
p = (char *)ADDR_32_TO_48(x);
|
2022-05-12 13:43:59 +00:00
|
|
|
if ((f & MAP_TYPE) == MAP_STACK) {
|
|
|
|
if (~f & MAP_ANONYMOUS) {
|
|
|
|
STRACE("MAP_STACK must be anonymous");
|
|
|
|
return VIP(einval());
|
|
|
|
}
|
|
|
|
f &= ~MAP_TYPE;
|
|
|
|
f |= MAP_PRIVATE;
|
|
|
|
if (IsOpenbsd()) { // openbsd:dubstack
|
|
|
|
// on openbsd this is less about scalability of threads, and more
|
|
|
|
// about defining the legal intervals for the RSP register. sadly
|
|
|
|
// openbsd doesn't let us create a new fixed stack mapping. but..
|
|
|
|
// openbsd does allow us to overwrite existing fixed mappings, to
|
|
|
|
// authorize its usage as a stack.
|
|
|
|
if (sys_mmap(p, size, prot, f, fd, off).addr == MAP_FAILED) {
|
|
|
|
return MAP_FAILED;
|
|
|
|
}
|
|
|
|
f |= MAP_STACK_openbsd;
|
2022-05-13 20:31:21 +00:00
|
|
|
needguard = true;
|
2022-05-12 13:43:59 +00:00
|
|
|
} else if (IsLinux()) {
|
2022-10-03 20:43:52 +00:00
|
|
|
// make sure there's no existing stuff existing between our stack
|
|
|
|
// starting page and the bottom guard page, since that would stop
|
|
|
|
// our stack page from growing down.
|
2023-07-26 20:54:49 +00:00
|
|
|
npassert(!sys_munmap(p, size));
|
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
|
|
|
int guardsize = pagesize, e = errno;
|
|
|
|
if ((dm = sys_mmap(p + size - guardsize, guardsize, prot,
|
2022-05-12 13:43:59 +00:00
|
|
|
f | MAP_GROWSDOWN_linux, fd, off))
|
2022-11-02 08:38:06 +00:00
|
|
|
.addr != MAP_FAILED) {
|
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
|
|
|
npassert(sys_mmap(p, pagesize, PROT_NONE,
|
2023-07-26 20:54:49 +00:00
|
|
|
MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)
|
|
|
|
.addr == p);
|
2022-11-02 08:38:06 +00:00
|
|
|
dm.addr = p;
|
2023-08-14 03:31:27 +00:00
|
|
|
p = __finish_memory(p, size, prot, flags, fd, off, f, x, n, dm);
|
2023-07-30 01:44:15 +00:00
|
|
|
if (IsAsan() && p != MAP_FAILED) {
|
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
|
|
|
__asan_poison(p, pagesize, kAsanStackOverflow);
|
2023-07-30 01:44:15 +00:00
|
|
|
}
|
|
|
|
return p;
|
2022-11-02 08:38:06 +00:00
|
|
|
} else if (errno == ENOTSUP) {
|
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
|
|
|
// WSL and Blink don't support MAP_GROWSDOWN
|
2022-11-02 08:38:06 +00:00
|
|
|
needguard = true;
|
|
|
|
errno = e;
|
2022-05-12 13:43:59 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if (IsFreebsd()) {
|
|
|
|
f |= MAP_STACK_freebsd;
|
|
|
|
}
|
|
|
|
needguard = true;
|
2020-09-03 12:44:37 +00:00
|
|
|
}
|
2020-06-15 14:18:57 +00:00
|
|
|
}
|
2022-04-24 16:59:22 +00:00
|
|
|
|
|
|
|
if (!IsWindows()) {
|
2023-08-14 03:31:27 +00:00
|
|
|
p = __map_memory(p, size, prot, flags, fd, off, f, x, n);
|
2022-04-24 16:59:22 +00:00
|
|
|
} else {
|
2023-08-14 03:31:27 +00:00
|
|
|
p = __map_memories(p, size, prot, flags, fd, off, f, x, n);
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
2022-05-12 13:43:59 +00:00
|
|
|
|
|
|
|
if (p != MAP_FAILED) {
|
2023-07-30 01:44:15 +00:00
|
|
|
if (IsAsan()) {
|
|
|
|
__asan_poison(p + requested_size, size - requested_size,
|
|
|
|
kAsanMmapSizeOverrun);
|
|
|
|
}
|
2022-05-12 13:43:59 +00:00
|
|
|
if (needguard) {
|
2023-10-04 14:07:43 +00:00
|
|
|
if (!IsWindows()) {
|
|
|
|
unassert(!mprotect(p, pagesize, PROT_NONE));
|
|
|
|
if (IsAsan()) {
|
|
|
|
__asan_poison(p, pagesize, kAsanStackOverflow);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
uint32_t oldattr;
|
|
|
|
unassert(VirtualProtect(p, pagesize, kNtPageReadwrite | kNtPageGuard,
|
|
|
|
&oldattr));
|
2022-05-13 00:52:13 +00:00
|
|
|
}
|
2022-05-12 13:43:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return p;
|
2022-04-24 16:59:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-07-30 01:44:15 +00:00
|
|
|
* Creates virtual memory, e.g.
|
2022-04-24 16:59:22 +00:00
|
|
|
*
|
|
|
|
* char *m;
|
|
|
|
* m = mmap(NULL, FRAMESIZE, PROT_READ | PROT_WRITE,
|
|
|
|
* MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
|
|
|
* munmap(m, FRAMESIZE);
|
|
|
|
*
|
|
|
|
* @param addr should be 0 to let your memory manager choose address;
|
|
|
|
* unless MAP_FIXED or MAP_FIXED_NOREPLACE are specified in flags
|
|
|
|
* in which case this function will do precicely as you ask, even
|
|
|
|
* if p=0 (in which you need -fno-delete-null-pointer-checks); it
|
|
|
|
* needs to be 64kb aligned because it's a wise choice that sadly
|
|
|
|
* needs to be made mandatory because of Windows although you can
|
|
|
|
* use __sys_mmap() to circumvent it on System Five in which case
|
|
|
|
* runtime support services, e.g. asan memory safety, could break
|
2023-07-30 01:44:15 +00:00
|
|
|
* @param size must be >0 otherwise EINVAL is raised
|
2022-04-24 16:59:22 +00:00
|
|
|
* @param prot can have PROT_READ/PROT_WRITE/PROT_EXEC/PROT_NONE/etc.
|
2022-05-13 00:52:13 +00:00
|
|
|
* @param flags should have one of the following masked by `MAP_TYPE`
|
2023-06-03 15:12:13 +00:00
|
|
|
* - `MAP_FILE` in which case `MAP_ANONYMOUS` shouldn't be used
|
2022-05-13 00:52:13 +00:00
|
|
|
* - `MAP_PRIVATE` for copy-on-write behavior of writeable pages
|
|
|
|
* - `MAP_SHARED` to create shared memory between processes
|
|
|
|
* - `MAP_STACK` to create a grows-down alloc, where a guard page
|
2023-07-26 20:54:49 +00:00
|
|
|
* is automatically protected at the bottom, sized as AT_PAGESZ
|
2022-05-13 00:52:13 +00:00
|
|
|
* Your `flags` may optionally bitwise or any of the following:
|
2023-06-03 15:12:13 +00:00
|
|
|
* - `MAP_ANONYMOUS` in which case `fd` and `off` are ignored
|
2022-05-22 11:51:02 +00:00
|
|
|
* - `MAP_FIXED` in which case `addr` becomes more than a hint
|
|
|
|
* - `MAP_FIXED_NOREPLACE` to protect existing mappings; this is
|
|
|
|
* always polyfilled by mmap() which tracks its own memory and
|
|
|
|
* removed before passing to the kernel, in order to support
|
|
|
|
* old versions; if you believe mappings exist which only the
|
|
|
|
* kernel knows, then this flag may be passed to sys_mmap() on
|
|
|
|
* Linux 4.17+ and FreeBSD (where it has multiple bits)
|
2022-05-13 00:52:13 +00:00
|
|
|
* - `MAP_CONCEAL` is FreeBSD/NetBSD/OpenBSD-only
|
|
|
|
* - `MAP_NORESERVE` is Linux/XNU/NetBSD-only
|
2022-05-22 11:51:02 +00:00
|
|
|
* - `MAP_POPULATE` is Linux/FreeBSD-only
|
2022-05-13 00:52:13 +00:00
|
|
|
* - `MAP_NONBLOCK` is Linux-only
|
2022-05-22 11:51:02 +00:00
|
|
|
* - `MAP_NOSYNC` is FreeBSD-only
|
|
|
|
* - `MAP_INHERIT` is NetBSD-only
|
|
|
|
* - `MAP_LOCKED` is Linux-only
|
2022-04-24 16:59:22 +00:00
|
|
|
* @param fd is an open()'d file descriptor, whose contents shall be
|
2023-06-03 15:12:13 +00:00
|
|
|
* made available w/ automatic reading at the chosen address
|
2022-04-24 16:59:22 +00:00
|
|
|
* @param off specifies absolute byte index of fd's file for mapping,
|
2023-07-30 01:44:15 +00:00
|
|
|
* should be zero if MAP_ANONYMOUS is specified, which SHOULD be
|
|
|
|
* aligned to FRAMESIZE
|
2022-04-24 16:59:22 +00:00
|
|
|
* @return virtual base address of new mapping, or MAP_FAILED w/ errno
|
|
|
|
*/
|
2022-06-26 01:17:31 +00:00
|
|
|
void *mmap(void *addr, size_t size, int prot, int flags, int fd, int64_t off) {
|
2022-04-24 16:59:22 +00:00
|
|
|
void *res;
|
2023-09-02 03:49:13 +00:00
|
|
|
#ifdef SYSDEBUG
|
2023-02-23 02:57:36 +00:00
|
|
|
size_t toto = 0;
|
2023-09-02 03:49:13 +00:00
|
|
|
#if _KERNTRACE || _NTTRACE
|
2022-06-26 01:17:31 +00:00
|
|
|
if (IsWindows()) {
|
|
|
|
STRACE("mmap(%p, %'zu, %s, %s, %d, %'ld) → ...", addr, size,
|
|
|
|
DescribeProtFlags(prot), DescribeMapFlags(flags), fd, off);
|
|
|
|
}
|
2023-09-02 03:49:13 +00:00
|
|
|
#endif
|
2022-06-26 01:17:31 +00:00
|
|
|
#endif
|
2022-06-11 08:59:26 +00:00
|
|
|
__mmi_lock();
|
2023-02-23 02:57:36 +00:00
|
|
|
if (!__isfdkind(fd, kFdZip)) {
|
2023-08-14 03:31:27 +00:00
|
|
|
res = __mmap_unlocked(addr, size, prot, flags, fd, off);
|
2023-02-23 02:57:36 +00:00
|
|
|
} else {
|
2023-08-14 03:31:27 +00:00
|
|
|
res = _weaken(__zipos_mmap)(
|
2023-02-23 02:57:36 +00:00
|
|
|
addr, size, prot, flags,
|
|
|
|
(struct ZiposHandle *)(intptr_t)g_fds.p[fd].handle, off);
|
|
|
|
}
|
2022-05-27 06:17:19 +00:00
|
|
|
#if SYSDEBUG
|
2023-08-14 03:31:27 +00:00
|
|
|
toto = __strace > 0 ? __get_memtrack_size(&_mmi) : 0;
|
2022-05-27 06:17:19 +00:00
|
|
|
#endif
|
2022-06-11 08:59:26 +00:00
|
|
|
__mmi_unlock();
|
2022-05-27 06:17:19 +00:00
|
|
|
STRACE("mmap(%p, %'zu, %s, %s, %d, %'ld) → %p% m (%'zu bytes total)", addr,
|
|
|
|
size, DescribeProtFlags(prot), DescribeMapFlags(flags), fd, off, res,
|
|
|
|
toto);
|
2022-04-13 05:11:00 +00:00
|
|
|
return res;
|
2020-06-15 14:18:57 +00:00
|
|
|
}
|
2023-09-21 14:30:39 +00:00
|
|
|
|
|
|
|
__strong_reference(mmap, mmap64);
|