2020-06-15 14:18:57 +00:00
|
|
|
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
|
2023-12-08 03:11:56 +00:00
|
|
|
│ vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi │
|
2020-06-15 14:18:57 +00:00
|
|
|
╞══════════════════════════════════════════════════════════════════════════════╡
|
|
|
|
│ 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
|
|
|
╚─────────────────────────────────────────────────────────────────────────────*/
|
2022-10-17 18:02:04 +00:00
|
|
|
#include "libc/assert.h"
|
2021-01-30 21:09:11 +00:00
|
|
|
#include "libc/calls/calls.h"
|
2023-10-15 03:57:15 +00:00
|
|
|
#include "libc/calls/createfileflags.internal.h"
|
2020-06-15 14:18:57 +00:00
|
|
|
#include "libc/calls/internal.h"
|
2022-08-13 20:11:56 +00:00
|
|
|
#include "libc/calls/struct/fd.internal.h"
|
2021-05-14 12:36:58 +00:00
|
|
|
#include "libc/calls/struct/flock.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.internal.h"
|
2022-05-23 22:06:11 +00:00
|
|
|
#include "libc/calls/syscall-nt.internal.h"
|
|
|
|
#include "libc/calls/syscall_support-nt.internal.h"
|
2022-08-13 20:11:56 +00:00
|
|
|
#include "libc/calls/wincrash.internal.h"
|
|
|
|
#include "libc/errno.h"
|
2023-08-21 09:28:24 +00:00
|
|
|
#include "libc/intrin/kprintf.h"
|
2023-09-12 04:34:53 +00:00
|
|
|
#include "libc/intrin/leaky.internal.h"
|
2022-09-15 04:29:50 +00:00
|
|
|
#include "libc/intrin/weaken.h"
|
2022-10-17 18:02:04 +00:00
|
|
|
#include "libc/limits.h"
|
2022-09-15 04:29:50 +00:00
|
|
|
#include "libc/log/backtrace.internal.h"
|
2022-10-17 18:02:04 +00:00
|
|
|
#include "libc/macros.internal.h"
|
2023-09-12 04:34:53 +00:00
|
|
|
#include "libc/mem/mem.h"
|
2023-08-21 09:28:24 +00:00
|
|
|
#include "libc/nt/createfile.h"
|
|
|
|
#include "libc/nt/enum/fileflagandattributes.h"
|
2021-05-14 12:36:58 +00:00
|
|
|
#include "libc/nt/enum/filelockflags.h"
|
2021-06-12 07:01:55 +00:00
|
|
|
#include "libc/nt/errors.h"
|
2020-06-15 14:18:57 +00:00
|
|
|
#include "libc/nt/files.h"
|
2021-06-12 07:01:55 +00:00
|
|
|
#include "libc/nt/runtime.h"
|
2021-05-14 12:36:58 +00:00
|
|
|
#include "libc/nt/struct/byhandlefileinformation.h"
|
|
|
|
#include "libc/nt/struct/overlapped.h"
|
Support non-blocking i/o across platforms
This change introduces new tests for `O_NONBLOCK` and `SOCK_NONBLOCK` to
confirm that non-blocking i/o is now working on all supported platforms,
including Windows. For example, you can now say on Windows, MacOS, etc.:
socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP);
To create a non-blocking IPv4 TCP socket. Or you can enable non-blocking
i/o on an existing socket / pipe / etc. file descriptor by calling fcntl
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
This functionality is polyfilled on older Linux kernels too, e.g. RHEL5.
Now that fcntl() support is much better the FIOCLEX / FIONCLEX polyfills
for ioctl() have been removed since they're ugly non-POSIX diameond APIs
This change fixes a weakness in kprintf() that was causing Windows trace
tools to frequently crash.
2023-07-23 09:56:47 +00:00
|
|
|
#include "libc/nt/winsock.h"
|
|
|
|
#include "libc/sock/internal.h"
|
2023-06-10 16:15:19 +00:00
|
|
|
#include "libc/stdckdint.h"
|
2022-10-17 18:02:04 +00:00
|
|
|
#include "libc/str/str.h"
|
2020-06-15 14:18:57 +00:00
|
|
|
#include "libc/sysv/consts/f.h"
|
|
|
|
#include "libc/sysv/consts/fd.h"
|
Support non-blocking i/o across platforms
This change introduces new tests for `O_NONBLOCK` and `SOCK_NONBLOCK` to
confirm that non-blocking i/o is now working on all supported platforms,
including Windows. For example, you can now say on Windows, MacOS, etc.:
socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP);
To create a non-blocking IPv4 TCP socket. Or you can enable non-blocking
i/o on an existing socket / pipe / etc. file descriptor by calling fcntl
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
This functionality is polyfilled on older Linux kernels too, e.g. RHEL5.
Now that fcntl() support is much better the FIOCLEX / FIONCLEX polyfills
for ioctl() have been removed since they're ugly non-POSIX diameond APIs
This change fixes a weakness in kprintf() that was causing Windows trace
tools to frequently crash.
2023-07-23 09:56:47 +00:00
|
|
|
#include "libc/sysv/consts/fio.h"
|
2020-11-28 20:01:51 +00:00
|
|
|
#include "libc/sysv/consts/o.h"
|
2020-06-15 14:18:57 +00:00
|
|
|
#include "libc/sysv/errfuns.h"
|
2022-10-17 18:02:04 +00:00
|
|
|
#include "libc/thread/thread.h"
|
2020-06-15 14:18:57 +00:00
|
|
|
|
2022-10-17 18:02:04 +00:00
|
|
|
struct FileLock {
|
|
|
|
struct FileLock *next;
|
|
|
|
int64_t off;
|
|
|
|
int64_t len;
|
|
|
|
int fd;
|
|
|
|
bool exc;
|
|
|
|
};
|
2021-08-12 07:42:14 +00:00
|
|
|
|
2022-10-17 18:02:04 +00:00
|
|
|
struct FileLocks {
|
|
|
|
pthread_mutex_t mu;
|
|
|
|
struct FileLock *list;
|
|
|
|
struct FileLock *free;
|
|
|
|
};
|
|
|
|
|
|
|
|
static struct FileLocks g_locks;
|
2022-09-15 04:29:50 +00:00
|
|
|
|
2022-10-17 18:02:04 +00:00
|
|
|
static textwindows struct FileLock *NewFileLock(void) {
|
|
|
|
struct FileLock *fl;
|
|
|
|
if (g_locks.free) {
|
|
|
|
fl = g_locks.free;
|
|
|
|
g_locks.free = fl->next;
|
|
|
|
} else {
|
2023-09-12 04:34:53 +00:00
|
|
|
unassert((fl = _weaken(malloc)(sizeof(*fl))));
|
2022-09-15 04:29:50 +00:00
|
|
|
}
|
2022-10-17 18:02:04 +00:00
|
|
|
bzero(fl, sizeof(*fl));
|
|
|
|
fl->next = g_locks.list;
|
|
|
|
g_locks.list = fl;
|
|
|
|
return fl;
|
|
|
|
}
|
|
|
|
|
2023-09-12 04:34:53 +00:00
|
|
|
IGNORE_LEAKS(NewFileLock)
|
|
|
|
|
2022-10-17 18:02:04 +00:00
|
|
|
static textwindows void FreeFileLock(struct FileLock *fl) {
|
|
|
|
fl->next = g_locks.free;
|
|
|
|
g_locks.free = fl;
|
|
|
|
}
|
|
|
|
|
|
|
|
static textwindows bool OverlapsFileLock(struct FileLock *fl, int64_t off,
|
|
|
|
int64_t len) {
|
|
|
|
uint64_t BegA, EndA, BegB, EndB;
|
|
|
|
BegA = off;
|
|
|
|
EndA = off + (len - 1);
|
|
|
|
BegB = fl->off;
|
|
|
|
EndB = fl->off + (fl->len - 1);
|
2023-10-13 17:48:04 +00:00
|
|
|
return MAX(BegA, BegB) <= MIN(EndA, EndB);
|
2022-10-17 18:02:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
static textwindows bool EncompassesFileLock(struct FileLock *fl, int64_t off,
|
|
|
|
int64_t len) {
|
|
|
|
return off <= fl->off && fl->off + fl->len <= off + len;
|
|
|
|
}
|
|
|
|
|
|
|
|
static textwindows bool EqualsFileLock(struct FileLock *fl, int64_t off,
|
|
|
|
int64_t len) {
|
|
|
|
return fl->off == off && off + len == fl->off + fl->len;
|
|
|
|
}
|
2022-09-15 04:29:50 +00:00
|
|
|
|
2023-07-24 15:31:54 +00:00
|
|
|
textwindows void sys_fcntl_nt_lock_cleanup(int fd) {
|
2022-10-17 18:02:04 +00:00
|
|
|
struct FileLock *fl, *ft, **flp;
|
|
|
|
pthread_mutex_lock(&g_locks.mu);
|
|
|
|
for (flp = &g_locks.list, fl = *flp; fl;) {
|
|
|
|
if (fl->fd == fd) {
|
|
|
|
*flp = fl->next;
|
|
|
|
ft = fl->next;
|
|
|
|
FreeFileLock(fl);
|
|
|
|
fl = ft;
|
|
|
|
} else {
|
|
|
|
flp = &fl->next;
|
|
|
|
fl = *flp;
|
|
|
|
}
|
2022-09-15 04:29:50 +00:00
|
|
|
}
|
2022-10-17 18:02:04 +00:00
|
|
|
pthread_mutex_unlock(&g_locks.mu);
|
|
|
|
}
|
|
|
|
|
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
|
|
|
static textwindows int64_t GetfileSize(int64_t handle) {
|
|
|
|
struct NtByHandleFileInformation wst;
|
Apply clang-format update to repo (#1154)
Commit bc6c183 introduced a bunch of discrepancies between what files
look like in the repo and what clang-format says they should look like.
However, there were already a few discrepancies prior to that. Most of
these discrepancies seemed to be unintentional, but a few of them were
load-bearing (e.g., a #include that violated header ordering needing
something to have been #defined by a 'later' #include.)
I opted to take what I hope is a relatively smooth-brained approach: I
reverted the .clang-format change, ran clang-format on the whole repo,
reapplied the .clang-format change, reran clang-format again, and then
reverted the commit that contained the first run. Thus the full effect
of this PR should only be to apply the changed formatting rules to the
repo, and from skimming the results, this seems to be the case.
My work can be checked by applying the short, manual commits, and then
rerunning the command listed in the autogenerated commits (those whose
messages I have prefixed auto:) and seeing if your results agree.
It might be that the other diffs should be fixed at some point but I'm
leaving that aside for now.
fd '\.c(c|pp)?$' --print0| xargs -0 clang-format -i
2024-04-25 17:38:00 +00:00
|
|
|
if (!GetFileInformationByHandle(handle, &wst))
|
|
|
|
return __winerr();
|
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
|
|
|
return (wst.nFileSizeHigh + 0ull) << 32 | wst.nFileSizeLow;
|
|
|
|
}
|
|
|
|
|
2022-10-17 18:02:04 +00:00
|
|
|
static textwindows int sys_fcntl_nt_lock(struct Fd *f, int fd, int cmd,
|
|
|
|
uintptr_t arg) {
|
2023-09-02 03:49:13 +00:00
|
|
|
uint32_t flags;
|
2022-10-17 18:02:04 +00:00
|
|
|
struct flock *l;
|
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
|
|
|
int64_t off, len, end;
|
2022-10-17 18:02:04 +00:00
|
|
|
struct FileLock *fl, *ft, **flp;
|
2022-09-15 04:29:50 +00:00
|
|
|
|
2023-09-12 04:34:53 +00:00
|
|
|
if (!_weaken(malloc)) {
|
|
|
|
return enomem();
|
|
|
|
}
|
|
|
|
|
2021-05-14 12:36:58 +00:00
|
|
|
l = (struct flock *)arg;
|
|
|
|
len = l->l_len;
|
|
|
|
off = l->l_start;
|
2022-09-15 04:29:50 +00:00
|
|
|
|
2021-06-12 07:01:55 +00:00
|
|
|
switch (l->l_whence) {
|
|
|
|
case SEEK_SET:
|
|
|
|
break;
|
|
|
|
case SEEK_CUR:
|
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
|
|
|
off = f->pointer + off;
|
2021-06-12 07:01:55 +00:00
|
|
|
break;
|
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
|
|
|
case SEEK_END: {
|
|
|
|
int64_t size;
|
Apply clang-format update to repo (#1154)
Commit bc6c183 introduced a bunch of discrepancies between what files
look like in the repo and what clang-format says they should look like.
However, there were already a few discrepancies prior to that. Most of
these discrepancies seemed to be unintentional, but a few of them were
load-bearing (e.g., a #include that violated header ordering needing
something to have been #defined by a 'later' #include.)
I opted to take what I hope is a relatively smooth-brained approach: I
reverted the .clang-format change, ran clang-format on the whole repo,
reapplied the .clang-format change, reran clang-format again, and then
reverted the commit that contained the first run. Thus the full effect
of this PR should only be to apply the changed formatting rules to the
repo, and from skimming the results, this seems to be the case.
My work can be checked by applying the short, manual commits, and then
rerunning the command listed in the autogenerated commits (those whose
messages I have prefixed auto:) and seeing if your results agree.
It might be that the other diffs should be fixed at some point but I'm
leaving that aside for now.
fd '\.c(c|pp)?$' --print0| xargs -0 clang-format -i
2024-04-25 17:38:00 +00:00
|
|
|
if ((size = GetfileSize(f->handle)) == -1)
|
|
|
|
return -1;
|
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
|
|
|
off = size - off;
|
2021-06-12 07:01:55 +00:00
|
|
|
break;
|
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
|
|
|
}
|
2021-06-12 07:01:55 +00:00
|
|
|
default:
|
2021-05-14 12:36:58 +00:00
|
|
|
return einval();
|
|
|
|
}
|
2022-09-15 04:29:50 +00:00
|
|
|
|
|
|
|
if (!len) {
|
2022-10-17 18:02:04 +00:00
|
|
|
len = INT64_MAX - off;
|
2022-09-15 04:29:50 +00:00
|
|
|
}
|
|
|
|
|
2023-06-10 16:15:19 +00:00
|
|
|
if (off < 0 || len < 0 || ckd_add(&end, off, len)) {
|
2022-09-15 04:29:50 +00:00
|
|
|
return einval();
|
|
|
|
}
|
|
|
|
|
|
|
|
bool32 ok;
|
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
|
|
|
struct NtOverlapped ov = {.hEvent = f->handle, .Pointer = off};
|
2022-09-15 04:29:50 +00:00
|
|
|
|
2021-05-14 12:36:58 +00:00
|
|
|
if (l->l_type == F_RDLCK || l->l_type == F_WRLCK) {
|
2022-10-17 18:02:04 +00:00
|
|
|
|
|
|
|
if (cmd == F_SETLK || cmd == F_SETLKW) {
|
|
|
|
// make it possible to transition read locks to write locks
|
|
|
|
for (flp = &g_locks.list, fl = *flp; fl;) {
|
|
|
|
if (fl->fd == fd) {
|
|
|
|
if (EqualsFileLock(fl, off, len)) {
|
2023-09-02 03:49:13 +00:00
|
|
|
if (fl->exc == (l->l_type == F_WRLCK)) {
|
2022-10-17 18:02:04 +00:00
|
|
|
// we already have this lock
|
|
|
|
return 0;
|
|
|
|
} else {
|
|
|
|
// unlock our read lock and acquire write lock below
|
|
|
|
if (UnlockFileEx(f->handle, 0, len, len >> 32, &ov)) {
|
|
|
|
*flp = fl->next;
|
|
|
|
ft = fl->next;
|
|
|
|
FreeFileLock(fl);
|
|
|
|
fl = ft;
|
|
|
|
continue;
|
|
|
|
} else {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
} else if (OverlapsFileLock(fl, off, len)) {
|
|
|
|
return enotsup();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
flp = &fl->next;
|
|
|
|
fl = *flp;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// return better information on conflicting locks if possible
|
|
|
|
if (cmd == F_GETLK) {
|
|
|
|
for (fl = g_locks.list; fl; fl = fl->next) {
|
|
|
|
if (fl->fd == fd && //
|
|
|
|
OverlapsFileLock(fl, off, len) &&
|
|
|
|
(l->l_type == F_WRLCK || !fl->exc)) {
|
|
|
|
l->l_whence = SEEK_SET;
|
|
|
|
l->l_start = fl->off;
|
|
|
|
l->l_len = fl->len;
|
2023-09-02 03:49:13 +00:00
|
|
|
l->l_type = fl->exc ? F_WRLCK : F_RDLCK;
|
2022-10-17 18:02:04 +00:00
|
|
|
l->l_pid = getpid();
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-14 12:36:58 +00:00
|
|
|
flags = 0;
|
2022-09-15 04:29:50 +00:00
|
|
|
if (cmd != F_SETLKW) {
|
2022-10-17 18:02:04 +00:00
|
|
|
// TODO(jart): we should use expo backoff in wrapper function
|
|
|
|
// should not matter since sqlite doesn't need it
|
2022-09-15 04:29:50 +00:00
|
|
|
flags |= kNtLockfileFailImmediately;
|
|
|
|
}
|
|
|
|
if (l->l_type == F_WRLCK) {
|
|
|
|
flags |= kNtLockfileExclusiveLock;
|
|
|
|
}
|
|
|
|
ok = LockFileEx(f->handle, flags, 0, len, len >> 32, &ov);
|
|
|
|
if (cmd == F_GETLK) {
|
|
|
|
if (ok) {
|
|
|
|
l->l_type = F_UNLCK;
|
|
|
|
if (!UnlockFileEx(f->handle, 0, len, len >> 32, &ov)) {
|
2022-10-17 18:02:04 +00:00
|
|
|
return -1;
|
2022-09-15 04:29:50 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
l->l_pid = -1;
|
|
|
|
ok = true;
|
|
|
|
}
|
2022-10-17 18:02:04 +00:00
|
|
|
} else if (ok) {
|
|
|
|
fl = NewFileLock();
|
|
|
|
fl->off = off;
|
|
|
|
fl->len = len;
|
|
|
|
fl->exc = l->l_type == F_WRLCK;
|
|
|
|
fl->fd = fd;
|
2022-09-15 04:29:50 +00:00
|
|
|
}
|
2022-10-13 20:44:41 +00:00
|
|
|
return ok ? 0 : -1;
|
2022-09-15 04:29:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (l->l_type == F_UNLCK) {
|
Apply clang-format update to repo (#1154)
Commit bc6c183 introduced a bunch of discrepancies between what files
look like in the repo and what clang-format says they should look like.
However, there were already a few discrepancies prior to that. Most of
these discrepancies seemed to be unintentional, but a few of them were
load-bearing (e.g., a #include that violated header ordering needing
something to have been #defined by a 'later' #include.)
I opted to take what I hope is a relatively smooth-brained approach: I
reverted the .clang-format change, ran clang-format on the whole repo,
reapplied the .clang-format change, reran clang-format again, and then
reverted the commit that contained the first run. Thus the full effect
of this PR should only be to apply the changed formatting rules to the
repo, and from skimming the results, this seems to be the case.
My work can be checked by applying the short, manual commits, and then
rerunning the command listed in the autogenerated commits (those whose
messages I have prefixed auto:) and seeing if your results agree.
It might be that the other diffs should be fixed at some point but I'm
leaving that aside for now.
fd '\.c(c|pp)?$' --print0| xargs -0 clang-format -i
2024-04-25 17:38:00 +00:00
|
|
|
if (cmd == F_GETLK)
|
|
|
|
return einval();
|
2022-10-17 18:02:04 +00:00
|
|
|
|
|
|
|
// allow a big range to unlock many small ranges
|
|
|
|
for (flp = &g_locks.list, fl = *flp; fl;) {
|
|
|
|
if (fl->fd == fd && EncompassesFileLock(fl, off, len)) {
|
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
|
|
|
struct NtOverlapped ov = {.hEvent = f->handle, .Pointer = fl->off};
|
2022-10-17 18:02:04 +00:00
|
|
|
if (UnlockFileEx(f->handle, 0, fl->len, fl->len >> 32, &ov)) {
|
|
|
|
*flp = fl->next;
|
|
|
|
ft = fl->next;
|
|
|
|
FreeFileLock(fl);
|
|
|
|
fl = ft;
|
|
|
|
} else {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
flp = &fl->next;
|
|
|
|
fl = *flp;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// win32 won't let us carve up existing locks
|
|
|
|
int overlap_count = 0;
|
|
|
|
for (fl = g_locks.list; fl; fl = fl->next) {
|
|
|
|
if (fl->fd == fd && //
|
|
|
|
OverlapsFileLock(fl, off, len)) {
|
|
|
|
++overlap_count;
|
|
|
|
}
|
2021-05-14 12:36:58 +00:00
|
|
|
}
|
2022-10-17 18:02:04 +00:00
|
|
|
|
|
|
|
// try to handle the carving cases needed by sqlite
|
|
|
|
if (overlap_count == 1) {
|
|
|
|
for (fl = g_locks.list; fl; fl = fl->next) {
|
|
|
|
if (fl->fd == fd && //
|
|
|
|
off <= fl->off && //
|
|
|
|
off + len >= fl->off && //
|
|
|
|
off + len < fl->off + fl->len) {
|
|
|
|
// cleave left side of lock
|
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
|
|
|
struct NtOverlapped ov = {.hEvent = f->handle, .Pointer = fl->off};
|
2022-10-17 18:02:04 +00:00
|
|
|
if (!UnlockFileEx(f->handle, 0, fl->len, fl->len >> 32, &ov)) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
fl->len = (fl->off + fl->len) - (off + len);
|
|
|
|
fl->off = off + len;
|
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
|
|
|
ov.Pointer = fl->off;
|
2022-10-17 18:02:04 +00:00
|
|
|
if (!LockFileEx(f->handle, kNtLockfileExclusiveLock, 0, fl->len,
|
|
|
|
fl->len >> 32, &ov)) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (overlap_count) {
|
|
|
|
return enotsup();
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
2021-05-14 12:36:58 +00:00
|
|
|
}
|
2022-09-15 04:29:50 +00:00
|
|
|
|
|
|
|
return einval();
|
2021-05-14 12:36:58 +00:00
|
|
|
}
|
|
|
|
|
2022-10-17 18:02:04 +00:00
|
|
|
static textwindows int sys_fcntl_nt_dupfd(int fd, int cmd, int start) {
|
Apply clang-format update to repo (#1154)
Commit bc6c183 introduced a bunch of discrepancies between what files
look like in the repo and what clang-format says they should look like.
However, there were already a few discrepancies prior to that. Most of
these discrepancies seemed to be unintentional, but a few of them were
load-bearing (e.g., a #include that violated header ordering needing
something to have been #defined by a 'later' #include.)
I opted to take what I hope is a relatively smooth-brained approach: I
reverted the .clang-format change, ran clang-format on the whole repo,
reapplied the .clang-format change, reran clang-format again, and then
reverted the commit that contained the first run. Thus the full effect
of this PR should only be to apply the changed formatting rules to the
repo, and from skimming the results, this seems to be the case.
My work can be checked by applying the short, manual commits, and then
rerunning the command listed in the autogenerated commits (those whose
messages I have prefixed auto:) and seeing if your results agree.
It might be that the other diffs should be fixed at some point but I'm
leaving that aside for now.
fd '\.c(c|pp)?$' --print0| xargs -0 clang-format -i
2024-04-25 17:38:00 +00:00
|
|
|
if (start < 0)
|
|
|
|
return einval();
|
2023-10-15 03:57:15 +00:00
|
|
|
return sys_dup_nt(fd, -1, (cmd == F_DUPFD_CLOEXEC ? _O_CLOEXEC : 0), start);
|
2022-10-17 18:02:04 +00:00
|
|
|
}
|
|
|
|
|
2021-05-14 12:36:58 +00:00
|
|
|
textwindows int sys_fcntl_nt(int fd, int cmd, uintptr_t arg) {
|
2022-10-17 18:02:04 +00:00
|
|
|
int rc;
|
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
|
|
|
BLOCK_SIGNALS;
|
2023-10-14 08:06:00 +00:00
|
|
|
if (__isfdkind(fd, kFdFile) || //
|
|
|
|
__isfdkind(fd, kFdSocket) || //
|
|
|
|
__isfdkind(fd, kFdConsole) || //
|
2024-05-03 14:59:51 +00:00
|
|
|
__isfdkind(fd, kFdDevNull) || //
|
|
|
|
__isfdkind(fd, kFdDevRandom)) {
|
2021-05-14 12:36:58 +00:00
|
|
|
if (cmd == F_GETFL) {
|
2023-10-15 03:57:15 +00:00
|
|
|
rc = g_fds.p[fd].flags & (O_ACCMODE | _O_APPEND | _O_DIRECT |
|
|
|
|
_O_NONBLOCK | _O_RANDOM | _O_SEQUENTIAL);
|
2021-05-14 12:36:58 +00:00
|
|
|
} else if (cmd == F_SETFL) {
|
2023-10-14 08:06:00 +00:00
|
|
|
rc = sys_fcntl_nt_setfl(fd, arg);
|
2021-05-14 12:36:58 +00:00
|
|
|
} else if (cmd == F_GETFD) {
|
2023-10-15 03:57:15 +00:00
|
|
|
if (g_fds.p[fd].flags & _O_CLOEXEC) {
|
2022-10-17 18:02:04 +00:00
|
|
|
rc = FD_CLOEXEC;
|
2021-05-14 12:36:58 +00:00
|
|
|
} else {
|
2022-10-17 18:02:04 +00:00
|
|
|
rc = 0;
|
2021-05-14 12:36:58 +00:00
|
|
|
}
|
|
|
|
} else if (cmd == F_SETFD) {
|
|
|
|
if (arg & FD_CLOEXEC) {
|
2023-10-15 03:57:15 +00:00
|
|
|
g_fds.p[fd].flags |= _O_CLOEXEC;
|
2021-05-14 12:36:58 +00:00
|
|
|
} else {
|
2023-10-15 03:57:15 +00:00
|
|
|
g_fds.p[fd].flags &= ~_O_CLOEXEC;
|
2021-05-14 12:36:58 +00:00
|
|
|
}
|
2022-11-02 06:14:14 +00:00
|
|
|
rc = 0;
|
2022-08-17 06:23:34 +00:00
|
|
|
} else if (cmd == F_SETLK || cmd == F_SETLKW || cmd == F_GETLK) {
|
2022-10-17 18:02:04 +00:00
|
|
|
pthread_mutex_lock(&g_locks.mu);
|
|
|
|
rc = sys_fcntl_nt_lock(g_fds.p + fd, fd, cmd, arg);
|
|
|
|
pthread_mutex_unlock(&g_locks.mu);
|
2021-08-12 07:42:14 +00:00
|
|
|
} else if (cmd == F_DUPFD || cmd == F_DUPFD_CLOEXEC) {
|
2022-10-17 18:02:04 +00:00
|
|
|
rc = sys_fcntl_nt_dupfd(fd, cmd, arg);
|
2021-05-14 12:36:58 +00:00
|
|
|
} else {
|
2022-10-17 18:02:04 +00:00
|
|
|
rc = einval();
|
2021-01-25 21:08:05 +00:00
|
|
|
}
|
|
|
|
} else {
|
2022-10-17 18:02:04 +00:00
|
|
|
rc = ebadf();
|
2020-06-15 14:18:57 +00:00
|
|
|
}
|
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
|
|
|
ALLOW_SIGNALS;
|
2022-10-17 18:02:04 +00:00
|
|
|
return rc;
|
2020-06-15 14:18:57 +00:00
|
|
|
}
|