mirror of
https://github.com/jart/cosmopolitan.git
synced 2025-02-02 04:23:34 +00:00
ec480f5aa0
- 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.
271 lines
9.3 KiB
C
271 lines
9.3 KiB
C
/*-*- 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 │
|
|
│ │
|
|
│ Permission to use, copy, modify, and/or distribute this software for │
|
|
│ any purpose with or without fee is hereby granted, provided that the │
|
|
│ above copyright notice and this permission notice appear in all copies. │
|
|
│ │
|
|
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
|
|
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
|
|
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
|
|
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
|
|
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
|
|
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
|
|
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
|
│ PERFORMANCE OF THIS SOFTWARE. │
|
|
╚─────────────────────────────────────────────────────────────────────────────*/
|
|
#include "libc/calls/internal.h"
|
|
#include "libc/calls/sig.internal.h"
|
|
#include "libc/calls/struct/metatermios.internal.h"
|
|
#include "libc/calls/syscall-nt.internal.h"
|
|
#include "libc/calls/termios.h"
|
|
#include "libc/calls/termios.internal.h"
|
|
#include "libc/calls/ttydefaults.h"
|
|
#include "libc/dce.h"
|
|
#include "libc/errno.h"
|
|
#include "libc/intrin/describeflags.internal.h"
|
|
#include "libc/intrin/nomultics.internal.h"
|
|
#include "libc/intrin/strace.internal.h"
|
|
#include "libc/macros.internal.h"
|
|
#include "libc/nt/console.h"
|
|
#include "libc/nt/enum/consolemodeflags.h"
|
|
#include "libc/nt/enum/version.h"
|
|
#include "libc/nt/runtime.h"
|
|
#include "libc/nt/version.h"
|
|
#include "libc/runtime/runtime.h"
|
|
#include "libc/str/str.h"
|
|
#include "libc/sysv/consts/fileno.h"
|
|
#include "libc/sysv/consts/o.h"
|
|
#include "libc/sysv/consts/sicode.h"
|
|
#include "libc/sysv/consts/sig.h"
|
|
#include "libc/sysv/consts/termios.h"
|
|
#include "libc/sysv/errfuns.h"
|
|
|
|
#ifdef __x86_64__
|
|
|
|
textwindows int __munge_terminal_input(char *p, uint32_t *n) {
|
|
size_t i, j;
|
|
if (!(__ttymagic & kFdTtyNoCr2Nl)) {
|
|
for (i = 0; i < *n; ++i) {
|
|
if (p[i] == '\r') {
|
|
p[i] = '\n';
|
|
}
|
|
}
|
|
}
|
|
bool delivered = false;
|
|
bool got_vintr = false;
|
|
bool got_vquit = false;
|
|
for (j = i = 0; i < *n; ++i) {
|
|
/*
|
|
It's not possible to type Ctrl+Space (aka ^@) into the CMD.EXE
|
|
console. Ctrl+Z is also problematic, since the Windows Console
|
|
processes that keystroke into an EOF event, even when we don't
|
|
enable input processing. These control codes are important for
|
|
Emacs users. One solution is to install the "Windows Terminal"
|
|
application from Microsoft Store, type Ctrl+Shift+, to get its
|
|
settings.json file opened, and add this code to its "actions":
|
|
|
|
"actions": [
|
|
{
|
|
"command": {
|
|
"action": "sendInput",
|
|
"input": "␀"
|
|
},
|
|
"keys": "ctrl+space"
|
|
},
|
|
{
|
|
"command": {
|
|
"action": "sendInput",
|
|
"input": "␚"
|
|
},
|
|
"keys": "ctrl+z"
|
|
},
|
|
{
|
|
"command": {
|
|
"action": "sendInput",
|
|
"input": "\u001f"
|
|
},
|
|
"keys": "ctrl+-"
|
|
}
|
|
],
|
|
|
|
Its not possible to configure Windows Terminal to output our
|
|
control codes. The workaround is to encode control sequences
|
|
using the "Control Pictures" UNICODE plane, which we'll then
|
|
translate back from UTF-8 glyphs, into actual control codes.
|
|
|
|
Another option Windows users can consider, particularly when
|
|
using CMD.EXE is installing Microsoft PowerTools whech makes
|
|
it possible to remap keys then configure ncurses to use them
|
|
|
|
https://github.com/microsoft/terminal/issues/2865
|
|
*/
|
|
int c;
|
|
if (i + 3 <= *n && // control pictures ascii nul ␀
|
|
(p[i + 0] & 255) == 0xe2 && // becomes ^@ a.k.a. ctrl-space
|
|
(p[i + 1] & 255) == 0x90 && // map the entire unicode plane
|
|
((p[i + 2] & 255) >= 0x80 && //
|
|
(p[i + 2] & 255) <= 0x9F)) {
|
|
c = (p[i + 2] & 255) - 0x80;
|
|
i += 2;
|
|
} else {
|
|
c = p[i] & 255;
|
|
}
|
|
if (!(__ttymagic & kFdTtyNoIsigs) && //
|
|
__vintr != _POSIX_VDISABLE && //
|
|
c == __vintr) {
|
|
got_vintr = true;
|
|
} else if (!(__ttymagic & kFdTtyNoIsigs) && //
|
|
__vquit != _POSIX_VDISABLE && //
|
|
c == __vquit) {
|
|
got_vquit = true;
|
|
} else {
|
|
p[j++] = c;
|
|
}
|
|
}
|
|
if (got_vintr) {
|
|
__sig_raise(SIGINT, SI_KERNEL);
|
|
delivered |= true;
|
|
}
|
|
if (got_vquit) {
|
|
__sig_raise(SIGQUIT, SI_KERNEL);
|
|
delivered |= true;
|
|
}
|
|
if (*n && !j) {
|
|
if (delivered) {
|
|
return DO_EINTR;
|
|
} else {
|
|
return DO_RESTART;
|
|
}
|
|
}
|
|
*n = j;
|
|
return DO_NOTHING;
|
|
}
|
|
|
|
// Manual CMD.EXE echoing for when !ICANON && ECHO is the case.
|
|
textwindows void __echo_terminal_input(struct Fd *fd, char *p, size_t n) {
|
|
int64_t hOutput;
|
|
if (fd->kind == kFdConsole) {
|
|
hOutput = fd->extra;
|
|
} else {
|
|
hOutput = g_fds.p[1].handle;
|
|
}
|
|
if (__ttymagic & kFdTtyEchoRaw) {
|
|
WriteFile(hOutput, p, n, 0, 0);
|
|
} else {
|
|
size_t i;
|
|
for (i = 0; i < n; ++i) {
|
|
if (isascii(p[i]) && iscntrl(p[i]) && p[i] != '\n' && p[i] != '\t') {
|
|
char ctl[2];
|
|
ctl[0] = '^';
|
|
ctl[1] = p[i] ^ 0100;
|
|
WriteFile(hOutput, ctl, 2, 0, 0);
|
|
} else {
|
|
WriteFile(hOutput, p + i, 1, 0, 0);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
textwindows int tcsetattr_nt(int fd, int opt, const struct termios *tio) {
|
|
bool32 ok;
|
|
int64_t hInput, hOutput;
|
|
uint32_t inmode, outmode;
|
|
|
|
if (__isfdkind(fd, kFdConsole)) {
|
|
hInput = g_fds.p[fd].handle;
|
|
hOutput = g_fds.p[fd].extra;
|
|
} else if (fd == STDIN_FILENO || //
|
|
fd == STDOUT_FILENO || //
|
|
fd == STDERR_FILENO) {
|
|
hInput = g_fds.p[STDIN_FILENO].handle;
|
|
hOutput = g_fds.p[MAX(STDOUT_FILENO, fd)].handle;
|
|
} else {
|
|
return enotty();
|
|
}
|
|
|
|
if (!GetConsoleMode(hInput, &inmode) || !GetConsoleMode(hOutput, &outmode)) {
|
|
return enotty();
|
|
}
|
|
|
|
if (opt == TCSAFLUSH) {
|
|
tcflush(fd, TCIFLUSH);
|
|
}
|
|
inmode &= ~(kNtEnableLineInput | kNtEnableEchoInput |
|
|
kNtEnableProcessedInput | kNtEnableVirtualTerminalInput);
|
|
inmode |= kNtEnableWindowInput;
|
|
__ttymagic = 0;
|
|
if (tio->c_lflag & ICANON) {
|
|
inmode |= kNtEnableLineInput | kNtEnableProcessedInput;
|
|
} else {
|
|
__ttymagic |= kFdTtyMunging;
|
|
if (tio->c_cc[VMIN] != 1) {
|
|
STRACE("tcsetattr c_cc[VMIN] must be 1 on Windows");
|
|
return einval();
|
|
}
|
|
if (IsAtLeastWindows10()) {
|
|
// - keys like f1, up, etc. get turned into \e ansi codes
|
|
// - totally destroys default console gui (e.g. up arrow)
|
|
inmode |= kNtEnableVirtualTerminalInput;
|
|
}
|
|
}
|
|
if (!(tio->c_iflag & ICRNL)) {
|
|
__ttymagic |= kFdTtyNoCr2Nl;
|
|
}
|
|
if (!(tio->c_lflag & ECHOCTL)) {
|
|
__ttymagic |= kFdTtyEchoRaw;
|
|
}
|
|
if (tio->c_lflag & ECHO) {
|
|
// "kNtEnableEchoInput can be used only if the
|
|
// kNtEnableLineInput mode is also enabled." -MSDN
|
|
if (tio->c_lflag & ICANON) {
|
|
inmode |= kNtEnableEchoInput;
|
|
} else {
|
|
// If ECHO is enabled in raw mode, then read(0) needs to
|
|
// magically write(1) to simulate echoing. This normally
|
|
// visualizes control codes, e.g. \r → ^M unless ECHOCTL
|
|
// hasn't been specified.
|
|
__ttymagic |= kFdTtyEchoing;
|
|
}
|
|
}
|
|
if (!(tio->c_lflag & ISIG)) {
|
|
__ttymagic |= kFdTtyNoIsigs;
|
|
}
|
|
__vintr = tio->c_cc[VINTR];
|
|
__vquit = tio->c_cc[VQUIT];
|
|
if ((tio->c_lflag & ISIG) && //
|
|
tio->c_cc[VINTR] == CTRL('C')) {
|
|
// allows ctrl-c to be delivered asynchronously via win32
|
|
inmode |= kNtEnableProcessedInput;
|
|
}
|
|
ok = SetConsoleMode(hInput, inmode);
|
|
(void)ok;
|
|
NTTRACE("SetConsoleMode(%p, %s) → %hhhd", hInput,
|
|
DescribeNtConsoleInFlags(inmode), ok);
|
|
|
|
outmode &= ~kNtDisableNewlineAutoReturn;
|
|
outmode |= kNtEnableProcessedOutput;
|
|
if (!(tio->c_oflag & ONLCR)) {
|
|
outmode |= kNtDisableNewlineAutoReturn;
|
|
}
|
|
if (IsAtLeastWindows10()) {
|
|
outmode |= kNtEnableVirtualTerminalProcessing;
|
|
}
|
|
ok = SetConsoleMode(hOutput, outmode);
|
|
(void)ok;
|
|
NTTRACE("SetConsoleMode(%p, %s) → %hhhd", hOutput,
|
|
DescribeNtConsoleOutFlags(outmode), ok);
|
|
|
|
return 0;
|
|
}
|
|
|
|
__attribute__((__constructor__)) static void tcsetattr_nt_init(void) {
|
|
if (!getenv("TERM")) {
|
|
setenv("TERM", "xterm-256color", true);
|
|
errno = 0; // ignore malloc not linked
|
|
}
|
|
}
|
|
|
|
#endif /* __x86_64__ */
|