cosmopolitan/libc/calls/sigaction.c

477 lines
19 KiB
C
Raw Normal View History

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/blocksigs.internal.h"
2020-06-15 14:18:57 +00:00
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/calls/sig.internal.h"
2022-05-23 22:06:11 +00:00
#include "libc/calls/state.internal.h"
#include "libc/calls/struct/sigaction-freebsd.internal.h"
#include "libc/calls/struct/sigaction-linux.internal.h"
2021-02-05 17:44:54 +00:00
#include "libc/calls/struct/sigaction-netbsd.h"
#include "libc/calls/struct/sigaction-openbsd.internal.h"
#include "libc/calls/struct/sigaction-xnu.internal.h"
2020-06-15 14:18:57 +00:00
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/sigaction.internal.h"
#include "libc/calls/struct/siginfo.internal.h"
#include "libc/calls/struct/sigset.h"
2022-05-23 22:06:11 +00:00
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/syscall_support-sysv.internal.h"
2020-06-15 14:18:57 +00:00
#include "libc/calls/ucontext.h"
#include "libc/dce.h"
Improve ZIP filesystem and change its prefix The ZIP filesystem has a breaking change. You now need to use /zip/ to open() / opendir() / etc. assets within the ZIP structure of your APE binary, instead of the previous convention of using zip: or zip! URIs. This is needed because Python likes to use absolute paths, and having ZIP paths encoded like URIs simply broke too many things. Many more system calls have been updated to be able to operate on ZIP files and file descriptors. In particular fcntl() and ioctl() since Python would do things like ask if a ZIP file is a terminal and get confused when the old implementation mistakenly said yes, because the fastest way to guarantee native file descriptors is to dup(2). This change also improves the async signal safety of zipos and ensures it doesn't maintain any open file descriptors beyond that which the user has opened. This change makes a lot of progress towards adding magic numbers that are specific to platforms other than Linux. The philosophy here is that, if you use an operating system like FreeBSD, then you should be able to take advantage of FreeBSD exclusive features, even if we don't polyfill them on other platforms. For example, you can now open() a file with the O_VERIFY flag. If your program runs on other platforms, then Cosmo will automatically set O_VERIFY to zero. This lets you safely use it without the need for #ifdef or ifstatements which detract from readability. One of the blindspots of the ASAN memory hardening we use to offer Rust like assurances has always been that memory passed to the kernel via system calls (e.g. writev) can't be checked automatically since the kernel wasn't built with MODE=asan. This change makes more progress ensuring that each system call will verify the soundness of memory before it's passed to the kernel. The code for doing these checks is fast, particularly for buffers, where it can verify 64 bytes a cycle. - Correct O_LOOP definition on NT - Introduce program_executable_name - Add ASAN guards to more system calls - Improve termios compatibility with BSDs - Fix bug in Windows auxiliary value encoding - Add BSD and XNU specific errnos and open flags - Add check to ensure build doesn't talk to internet
2021-08-22 08:04:18 +00:00
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
2020-06-15 14:18:57 +00:00
#include "libc/limits.h"
#include "libc/log/backtrace.internal.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
2020-06-15 14:18:57 +00:00
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/sa.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/errfuns.h"
#undef sigaction
#ifdef SYSDEBUG
STATIC_YOINK("strsignal"); // for kprintf()
#endif
Make major improvements to redbean and libraries The most exciting improvement is dynamic pages will soon be able to use the executable itself as an object store. it required a heroic technique for overcoming ETXTBSY restrictions which lets us open the executable in read/write mode, which means (1) wa can restore the APE header, and (2) we can potentially containerize redbean extension code so that modules you download for your redbean online will only impact your redbean. Here's a list of breaking changes to redbean: - Remove /tool/net/ prefix from magic ZIP paths - GetHeader() now returns NIL if header is absent Here's a list of fixes and enhancements to redbean: - Support 64-bit ZIP archives - Record User-Agent header in logs - Add twelve error handlers to accept() - Display octal st_mode on listing page - Show ZIP file comments on listing page - Restore APE MZ header on redbean startup - Track request count on redbean index page - Report server uptime on redbean index page - Don't bind server socket using SO_REUSEPORT - Fix #151 where Lua LoadAsset() could free twice - Report rusage accounting when workers exit w/ -vv - Use ZIP iattr field as text/plain vs. binary hint - Add ParseUrl() API for parsing things like a.href - Add ParseParams() API for parsing HTTP POST bodies - Add IsAcceptablePath() API for checking dots, etc. - Add IsValidHttpToken() API for validating sane ASCII - Add IsAcceptableHostPort() for validating HOST[:PORT] - Send 400 response to HTTP/1.1 requests without a Host - Send 403 response if ZIP or file isn't other readable - Add virtual hosting that tries prepending Host to path - Route requests based on Host in Request-URI if present - Host routing will attempt to remove or add the www. prefix - Sign-extend UNIX timestamps and don't adjust FileTime zone Here's some of the improvements made to Cosmopolitan Libc: - Fix ape.S indentation - Improve consts.sh magnums - Write pretty good URL parser - Improve rusage accounting apis - Bring mremap() closer to working - Added ZIP APIs which will change - Check for overflow in reallocarray() - Remove overly fancy linkage in strerror() - Fix GDB attach on crash w/ OpenBSD msyscall() - Make sigqueue() portable to most UNIX distros - Make integer serialization macros more elegant - Bring back 34x tprecode8to16() performance boost - Make malloc() more resilient to absurdly large sizes
2021-04-18 18:34:59 +00:00
#define SA_RESTORER 0x04000000
2021-02-02 16:14:45 +00:00
#ifndef SWITCHEROO
2020-06-15 14:18:57 +00:00
#define SWITCHEROO(S1, S2, A, B, C, D) \
do { \
autotype((S2).A) a = (typeof((S2).A))(S1).A; \
autotype((S2).B) b = (typeof((S2).B))(S1).B; \
autotype((S2).C) c = (typeof((S2).C))(S1).C; \
typeof((S2).D) d; \
Make numerous improvements - Python static hello world now 1.8mb - Python static fully loaded now 10mb - Python HTTPS client now uses MbedTLS - Python REPL now completes import stmts - Increase stack size for Python for now - Begin synthesizing posixpath and ntpath - Restore Python \N{UNICODE NAME} support - Restore Python NFKD symbol normalization - Add optimized code path for Intel SHA-NI - Get more Python unit tests passing faster - Get Python help() pagination working on NT - Python hashlib now supports MbedTLS PBKDF2 - Make memcpy/memmove/memcmp/bcmp/etc. faster - Add Mersenne Twister and Vigna to LIBC_RAND - Provide privileged __printf() for error code - Fix zipos opendir() so that it reports ENOTDIR - Add basic chmod() implementation for Windows NT - Add Cosmo's best functions to Python cosmo module - Pin function trace indent depth to that of caller - Show memory diagram on invalid access in MODE=dbg - Differentiate stack overflow on crash in MODE=dbg - Add stb_truetype and tools for analyzing font files - Upgrade to UNICODE 13 and reduce its binary footprint - COMPILE.COM now logs resource usage of build commands - Start implementing basic poll() support on bare metal - Set getauxval(AT_EXECFN) to GetModuleFileName() on NT - Add descriptions to strerror() in non-TINY build modes - Add COUNTBRANCH() macro to help with micro-optimizations - Make error / backtrace / asan / memory code more unbreakable - Add fast perfect C implementation of μ-Law and a-Law audio codecs - Make strtol() functions consistent with other libc implementations - Improve Linenoise implementation (see also github.com/jart/bestline) - COMPILE.COM now suppresses stdout/stderr of successful build commands
2021-09-28 05:58:51 +00:00
bzero(&d, sizeof(d)); \
2020-06-15 14:18:57 +00:00
memcpy(&d, &((S1).D), MIN(sizeof(d), sizeof((S1).D))); \
(S2).A = a; \
(S2).B = b; \
(S2).C = c; \
Make numerous improvements - Python static hello world now 1.8mb - Python static fully loaded now 10mb - Python HTTPS client now uses MbedTLS - Python REPL now completes import stmts - Increase stack size for Python for now - Begin synthesizing posixpath and ntpath - Restore Python \N{UNICODE NAME} support - Restore Python NFKD symbol normalization - Add optimized code path for Intel SHA-NI - Get more Python unit tests passing faster - Get Python help() pagination working on NT - Python hashlib now supports MbedTLS PBKDF2 - Make memcpy/memmove/memcmp/bcmp/etc. faster - Add Mersenne Twister and Vigna to LIBC_RAND - Provide privileged __printf() for error code - Fix zipos opendir() so that it reports ENOTDIR - Add basic chmod() implementation for Windows NT - Add Cosmo's best functions to Python cosmo module - Pin function trace indent depth to that of caller - Show memory diagram on invalid access in MODE=dbg - Differentiate stack overflow on crash in MODE=dbg - Add stb_truetype and tools for analyzing font files - Upgrade to UNICODE 13 and reduce its binary footprint - COMPILE.COM now logs resource usage of build commands - Start implementing basic poll() support on bare metal - Set getauxval(AT_EXECFN) to GetModuleFileName() on NT - Add descriptions to strerror() in non-TINY build modes - Add COUNTBRANCH() macro to help with micro-optimizations - Make error / backtrace / asan / memory code more unbreakable - Add fast perfect C implementation of μ-Law and a-Law audio codecs - Make strtol() functions consistent with other libc implementations - Improve Linenoise implementation (see also github.com/jart/bestline) - COMPILE.COM now suppresses stdout/stderr of successful build commands
2021-09-28 05:58:51 +00:00
bzero(&((S2).D), sizeof((S2).D)); \
2020-06-15 14:18:57 +00:00
memcpy(&((S2).D), &d, MIN(sizeof(d), sizeof((S2).D))); \
} while (0);
2021-02-02 16:14:45 +00:00
#endif
2020-06-15 14:18:57 +00:00
union metasigaction {
struct sigaction cosmo;
struct sigaction_linux linux;
struct sigaction_freebsd freebsd;
struct sigaction_openbsd openbsd;
struct sigaction_netbsd netbsd;
struct sigaction_xnu_in xnu_in;
struct sigaction_xnu_out xnu_out;
};
void __sigenter_xnu(int, struct siginfo *, void *) hidden;
void __sigenter_linux(int, struct siginfo *, void *) hidden;
void __sigenter_netbsd(int, struct siginfo *, void *) hidden;
void __sigenter_freebsd(int, struct siginfo *, void *) hidden;
void __sigenter_openbsd(int, struct siginfo *, void *) hidden;
2021-02-05 17:44:54 +00:00
static void sigaction_cosmo2native(union metasigaction *sa) {
2020-06-15 14:18:57 +00:00
if (!sa) return;
switch (__hostos) {
case _HOSTLINUX:
2020-06-15 14:18:57 +00:00
SWITCHEROO(sa->cosmo, sa->linux, sa_handler, sa_flags, sa_restorer,
sa_mask);
break;
case _HOSTXNU:
2020-06-15 14:18:57 +00:00
SWITCHEROO(sa->cosmo, sa->xnu_in, sa_handler, sa_flags, sa_restorer,
sa_mask);
break;
case _HOSTFREEBSD:
2020-06-15 14:18:57 +00:00
SWITCHEROO(sa->cosmo, sa->freebsd, sa_handler, sa_flags, sa_flags,
sa_mask);
break;
case _HOSTOPENBSD:
2020-06-15 14:18:57 +00:00
SWITCHEROO(sa->cosmo, sa->openbsd, sa_handler, sa_flags, sa_flags,
sa_mask);
break;
case _HOSTNETBSD:
2021-02-05 17:44:54 +00:00
SWITCHEROO(sa->cosmo, sa->netbsd, sa_handler, sa_flags, sa_flags,
sa_mask);
break;
2020-06-15 14:18:57 +00:00
default:
break;
2020-06-15 14:18:57 +00:00
}
}
2021-02-05 17:44:54 +00:00
static void sigaction_native2cosmo(union metasigaction *sa) {
2020-06-15 14:18:57 +00:00
if (!sa) return;
switch (__hostos) {
case _HOSTLINUX:
2020-06-15 14:18:57 +00:00
SWITCHEROO(sa->linux, sa->cosmo, sa_handler, sa_flags, sa_restorer,
sa_mask);
break;
case _HOSTXNU:
2020-06-15 14:18:57 +00:00
SWITCHEROO(sa->xnu_out, sa->cosmo, sa_handler, sa_flags, sa_flags,
sa_mask);
break;
case _HOSTFREEBSD:
2020-06-15 14:18:57 +00:00
SWITCHEROO(sa->freebsd, sa->cosmo, sa_handler, sa_flags, sa_flags,
sa_mask);
break;
case _HOSTOPENBSD:
2020-06-15 14:18:57 +00:00
SWITCHEROO(sa->openbsd, sa->cosmo, sa_handler, sa_flags, sa_flags,
sa_mask);
break;
case _HOSTNETBSD:
2021-02-05 17:44:54 +00:00
SWITCHEROO(sa->netbsd, sa->cosmo, sa_handler, sa_flags, sa_flags,
sa_mask);
break;
2020-06-15 14:18:57 +00:00
default:
break;
2020-06-15 14:18:57 +00:00
}
}
static int __sigaction(int sig, const struct sigaction *act,
struct sigaction *oldact) {
Improve ZIP filesystem and change its prefix The ZIP filesystem has a breaking change. You now need to use /zip/ to open() / opendir() / etc. assets within the ZIP structure of your APE binary, instead of the previous convention of using zip: or zip! URIs. This is needed because Python likes to use absolute paths, and having ZIP paths encoded like URIs simply broke too many things. Many more system calls have been updated to be able to operate on ZIP files and file descriptors. In particular fcntl() and ioctl() since Python would do things like ask if a ZIP file is a terminal and get confused when the old implementation mistakenly said yes, because the fastest way to guarantee native file descriptors is to dup(2). This change also improves the async signal safety of zipos and ensures it doesn't maintain any open file descriptors beyond that which the user has opened. This change makes a lot of progress towards adding magic numbers that are specific to platforms other than Linux. The philosophy here is that, if you use an operating system like FreeBSD, then you should be able to take advantage of FreeBSD exclusive features, even if we don't polyfill them on other platforms. For example, you can now open() a file with the O_VERIFY flag. If your program runs on other platforms, then Cosmo will automatically set O_VERIFY to zero. This lets you safely use it without the need for #ifdef or ifstatements which detract from readability. One of the blindspots of the ASAN memory hardening we use to offer Rust like assurances has always been that memory passed to the kernel via system calls (e.g. writev) can't be checked automatically since the kernel wasn't built with MODE=asan. This change makes more progress ensuring that each system call will verify the soundness of memory before it's passed to the kernel. The code for doing these checks is fast, particularly for buffers, where it can verify 64 bytes a cycle. - Correct O_LOOP definition on NT - Introduce program_executable_name - Add ASAN guards to more system calls - Improve termios compatibility with BSDs - Fix bug in Windows auxiliary value encoding - Add BSD and XNU specific errnos and open flags - Add check to ensure build doesn't talk to internet
2021-08-22 08:04:18 +00:00
_Static_assert((sizeof(struct sigaction) > sizeof(struct sigaction_linux) &&
sizeof(struct sigaction) > sizeof(struct sigaction_xnu_in) &&
sizeof(struct sigaction) > sizeof(struct sigaction_xnu_out) &&
sizeof(struct sigaction) > sizeof(struct sigaction_freebsd) &&
sizeof(struct sigaction) > sizeof(struct sigaction_openbsd) &&
sizeof(struct sigaction) > sizeof(struct sigaction_netbsd)),
"sigaction cosmo abi needs tuning");
2021-02-05 17:44:54 +00:00
int64_t arg4, arg5;
2020-06-15 14:18:57 +00:00
int rc, rva, oldrva;
sigaction_f sigenter;
2020-06-15 14:18:57 +00:00
struct sigaction *ap, copy;
if (IsMetal()) return enosys(); /* TODO: Signals on Metal */
if (!(0 < sig && sig < NSIG)) return einval();
if (sig == SIGKILL || sig == SIGSTOP) return einval();
Improve ZIP filesystem and change its prefix The ZIP filesystem has a breaking change. You now need to use /zip/ to open() / opendir() / etc. assets within the ZIP structure of your APE binary, instead of the previous convention of using zip: or zip! URIs. This is needed because Python likes to use absolute paths, and having ZIP paths encoded like URIs simply broke too many things. Many more system calls have been updated to be able to operate on ZIP files and file descriptors. In particular fcntl() and ioctl() since Python would do things like ask if a ZIP file is a terminal and get confused when the old implementation mistakenly said yes, because the fastest way to guarantee native file descriptors is to dup(2). This change also improves the async signal safety of zipos and ensures it doesn't maintain any open file descriptors beyond that which the user has opened. This change makes a lot of progress towards adding magic numbers that are specific to platforms other than Linux. The philosophy here is that, if you use an operating system like FreeBSD, then you should be able to take advantage of FreeBSD exclusive features, even if we don't polyfill them on other platforms. For example, you can now open() a file with the O_VERIFY flag. If your program runs on other platforms, then Cosmo will automatically set O_VERIFY to zero. This lets you safely use it without the need for #ifdef or ifstatements which detract from readability. One of the blindspots of the ASAN memory hardening we use to offer Rust like assurances has always been that memory passed to the kernel via system calls (e.g. writev) can't be checked automatically since the kernel wasn't built with MODE=asan. This change makes more progress ensuring that each system call will verify the soundness of memory before it's passed to the kernel. The code for doing these checks is fast, particularly for buffers, where it can verify 64 bytes a cycle. - Correct O_LOOP definition on NT - Introduce program_executable_name - Add ASAN guards to more system calls - Improve termios compatibility with BSDs - Fix bug in Windows auxiliary value encoding - Add BSD and XNU specific errnos and open flags - Add check to ensure build doesn't talk to internet
2021-08-22 08:04:18 +00:00
if (IsAsan() && ((act && !__asan_is_valid(act, sizeof(*act))) ||
(oldact && !__asan_is_valid(oldact, sizeof(*oldact))))) {
return efault();
}
2020-06-15 14:18:57 +00:00
if (!act) {
rva = (int32_t)(intptr_t)SIG_DFL;
} else if ((intptr_t)act->sa_handler < kSigactionMinRva) {
rva = (int)(intptr_t)act->sa_handler;
} else if ((intptr_t)act->sa_handler >= (intptr_t)&_base + kSigactionMinRva &&
(intptr_t)act->sa_handler < (intptr_t)&_base + INT_MAX) {
rva = (int)((uintptr_t)act->sa_handler - (uintptr_t)&_base);
} else {
return efault();
}
if (__vforked && rva != (intptr_t)SIG_DFL && rva != (intptr_t)SIG_IGN) {
return einval();
}
2020-06-15 14:18:57 +00:00
if (!IsWindows()) {
2021-02-05 17:44:54 +00:00
if (act) {
memcpy(&copy, act, sizeof(copy));
ap = &copy;
if (IsXnu()) {
ap->sa_restorer = (void *)&__sigenter_xnu;
sigenter = __sigenter_xnu;
// mitigate Rosetta signal handling strangeness
// https://github.com/jart/cosmopolitan/issues/455
ap->sa_flags |= SA_SIGINFO;
2021-02-05 17:44:54 +00:00
} else if (IsLinux()) {
if (!(ap->sa_flags & SA_RESTORER)) {
ap->sa_flags |= SA_RESTORER;
ap->sa_restorer = &__restore_rt;
2020-06-15 14:18:57 +00:00
}
sigenter = __sigenter_linux;
2021-02-05 17:44:54 +00:00
} else if (IsNetbsd()) {
sigenter = __sigenter_netbsd;
} else if (IsFreebsd()) {
sigenter = __sigenter_freebsd;
} else if (IsOpenbsd()) {
sigenter = __sigenter_openbsd;
} else {
return enosys();
2021-02-05 17:44:54 +00:00
}
if (rva < kSigactionMinRva) {
ap->sa_sigaction = (void *)(intptr_t)rva;
} else {
ap->sa_sigaction = sigenter;
}
2021-02-05 17:44:54 +00:00
sigaction_cosmo2native((union metasigaction *)ap);
} else {
ap = NULL;
}
if (IsXnu()) {
arg4 = (int64_t)(intptr_t)oldact; /* from go code */
arg5 = 0;
} else if (IsNetbsd()) {
/* int __sigaction_sigtramp(int signum,
const struct sigaction *nsa,
struct sigaction *osa,
const void *tramp,
int vers); */
2021-02-05 17:44:54 +00:00
if (ap) {
arg4 = (int64_t)(intptr_t)&__restore_rt_netbsd;
arg5 = 2; /* netbsd/lib/libc/arch/x86_64/sys/__sigtramp2.S */
} else {
2021-02-05 17:44:54 +00:00
arg4 = 0;
arg5 = 0; /* netbsd/lib/libc/arch/x86_64/sys/__sigtramp2.S */
2020-06-15 14:18:57 +00:00
}
} else {
2021-02-05 17:44:54 +00:00
arg4 = 8; /* or linux whines */
arg5 = 0;
}
if ((rc = sys_sigaction(sig, ap, oldact, arg4, arg5)) != -1) {
sigaction_native2cosmo((union metasigaction *)oldact);
2020-06-15 14:18:57 +00:00
}
} else {
if (oldact) {
Make numerous improvements - Python static hello world now 1.8mb - Python static fully loaded now 10mb - Python HTTPS client now uses MbedTLS - Python REPL now completes import stmts - Increase stack size for Python for now - Begin synthesizing posixpath and ntpath - Restore Python \N{UNICODE NAME} support - Restore Python NFKD symbol normalization - Add optimized code path for Intel SHA-NI - Get more Python unit tests passing faster - Get Python help() pagination working on NT - Python hashlib now supports MbedTLS PBKDF2 - Make memcpy/memmove/memcmp/bcmp/etc. faster - Add Mersenne Twister and Vigna to LIBC_RAND - Provide privileged __printf() for error code - Fix zipos opendir() so that it reports ENOTDIR - Add basic chmod() implementation for Windows NT - Add Cosmo's best functions to Python cosmo module - Pin function trace indent depth to that of caller - Show memory diagram on invalid access in MODE=dbg - Differentiate stack overflow on crash in MODE=dbg - Add stb_truetype and tools for analyzing font files - Upgrade to UNICODE 13 and reduce its binary footprint - COMPILE.COM now logs resource usage of build commands - Start implementing basic poll() support on bare metal - Set getauxval(AT_EXECFN) to GetModuleFileName() on NT - Add descriptions to strerror() in non-TINY build modes - Add COUNTBRANCH() macro to help with micro-optimizations - Make error / backtrace / asan / memory code more unbreakable - Add fast perfect C implementation of μ-Law and a-Law audio codecs - Make strtol() functions consistent with other libc implementations - Improve Linenoise implementation (see also github.com/jart/bestline) - COMPILE.COM now suppresses stdout/stderr of successful build commands
2021-09-28 05:58:51 +00:00
bzero(oldact, sizeof(*oldact));
2020-06-15 14:18:57 +00:00
}
rc = 0;
}
if (rc != -1 && !__vforked) {
2020-06-15 14:18:57 +00:00
if (oldact) {
oldrva = __sighandrvas[sig];
oldact->sa_sigaction = (sigaction_f)(
oldrva < kSigactionMinRva ? oldrva : (intptr_t)&_base + oldrva);
2020-06-15 14:18:57 +00:00
}
if (act) {
__sighandrvas[sig] = rva;
__sighandflags[sig] = act->sa_flags;
__sig_check_ignore(sig, rva);
2020-06-15 14:18:57 +00:00
}
}
return rc;
}
/**
* Installs handler for kernel interrupt to thread, e.g.:
*
* void GotCtrlC(int sig, siginfo_t *si, void *ctx);
* struct sigaction sa = {.sa_sigaction = GotCtrlC,
* .sa_flags = SA_RESETHAND|SA_RESTART|SA_SIGINFO};
* CHECK_NE(-1, sigaction(SIGINT, &sa, NULL));
*
* The following flags are supported across platforms:
*
* - `SA_SIGINFO`: Causes the `siginfo_t` and `ucontext_t` parameters to
* be passed. `void *ctx` actually refers to `struct ucontext *`.
* This not only gives you more information about the signal, but also
* allows your signal handler to change the CPU registers. That's
* useful for recovering from crashes. If you don't use this attribute,
* then signal delivery will go a little faster.
*
* - `SA_RESTART`: Enables BSD signal handling semantics. Normally i/o
* entrypoints check for pending signals to deliver. If one gets
* delivered during an i/o call, the normal behavior is to cancel the
* i/o operation and return -1 with EINTR in errno. If you use the
* `SA_RESTART` flag then that behavior changes, so that any function
* that's been annotated with @restartable will not return `EINTR` and
* will instead resume the i/o operation. This makes coding easier but
* it can be an anti-pattern if not used carefully, since poor usage
* can easily result in latency issues. It also requires one to do
* more work in signal handlers, so special care needs to be given to
* which C library functions are @asyncsignalsafe.
*
* - `SA_RESETHAND`: Causes signal handler to be single-shot. This means
* that, upon entry of delivery to a signal handler, it's reset to the
* `SIG_DFL` handler automatically. You may use the alias `SA_ONESHOT`
* for this flag, which means the same thing.
*
* - `SA_NODEFER`: Disables the reentrancy safety check on your signal
* handler. Normally that's a good thing, since for instance if your
* `SIGSEGV` signal handler happens to segfault, you're going to want
* your process to just crash rather than looping endlessly. But in
* some cases it's desirable to use `SA_NODEFER` instead, such as at
* times when you wish to `longjmp()` out of your signal handler and
* back into your program. This is only safe to do across platforms
* for non-crashing signals such as `SIGCHLD` and `SIGINT`. Crash
* handlers should use Xed instead to recover execution, because on
* Windows a `SIGSEGV` or `SIGTRAP` crash handler might happen on a
* separate stack and/or a separate thread. You may use the alias
* `SA_NOMASK` for this flag, which means the same thing.
*
* - `SA_NOCLDWAIT`: Changes `SIGCHLD` so the zombie is gone and you
* can't call `wait()` anymore; similar but may
* still deliver the SIGCHLD.
*
* - `SA_NOCLDSTOP`: Lets you set `SIGCHLD` handler that's only notified
* on exit/termination and not notified on `SIGSTOP`, `SIGTSTP`,
* `SIGTTIN`, `SIGTTOU`, or `SIGCONT`.
*
* Here's an example of the most professional way to handle signals in
* an i/o event loop. It's generally a best practice to have signal
* handlers do the fewest number of things possible. The trick is to
* have your signals work hand-in-glove with the EINTR errno. This
* obfuscates the need for having to worry about @asyncsignalsafe.
*
* static volatile bool gotctrlc;
*
* void OnCtrlC(int sig) {
* gotctrlc = true;
* }
*
* int main() {
* size_t got;
* ssize_t rc;
* char buf[1];
* struct sigaction oldint;
* struct sigaction saint = {.sa_handler = GotCtrlC};
* if (sigaction(SIGINT, &saint, &oldint) == -1) {
* perror("sigaction");
* exit(1);
* }
* for (;;) {
* rc = read(0, buf, sizeof(buf));
* if (rc == -1) {
* if (errno == EINTR) {
* if (gotctrlc) {
* break;
* }
* } else {
* perror("read");
* exit(2);
* }
* }
* if (!(got = rc)) {
* break;
* }
* for (;;) {
* rc = write(1, buf, got);
* if (rc != -1) {
* assert(rc == 1);
* break;
* } else if (errno != EINTR) {
* perror("write");
* exit(3);
* }
* }
* }
* sigaction(SIGINT, &oldint, 0);
* }
*
* Please note that you can't do the above if you use SA_RESTART. Since
* the purpose of SA_RESTART is to restart i/o operations whose docs say
* that they're @restartable and read() is one such function. Here's
* some even better news: if you don't install any signal handlers at
* all, then your i/o calls will never be interrupted!
*
* Here's an example of the most professional way to recover from
* `SIGSEGV`, `SIGFPE`, and `SIGILL`.
*
* void ContinueOnCrash(void);
*
* void SkipOverFaultingInstruction(struct ucontext *ctx) {
* struct XedDecodedInst xedd;
* xed_decoded_inst_zero_set_mode(&xedd, XED_MACHINE_MODE_LONG_64);
* xed_instruction_length_decode(&xedd, (void *)ctx->uc_mcontext.rip, 15);
* ctx->uc_mcontext.rip += xedd.length;
* }
*
* void OnCrash(int sig, struct siginfo *si, void *vctx) {
* struct ucontext *ctx = vctx;
* SkipOverFaultingInstruction(ctx);
* ContinueOnCrash(); // reinstall here in case *rip faults
* }
*
* void ContinueOnCrash(void) {
* struct sigaction sa = {.sa_handler = OnSigSegv,
* .sa_flags = SA_SIGINFO | SA_RESETHAND};
* sigaction(SIGSEGV, &sa, 0);
* sigaction(SIGFPE, &sa, 0);
* sigaction(SIGILL, &sa, 0);
* }
*
* int main() {
* ContinueOnCrash();
* // ...
* }
*
* You may also edit any other CPU registers during the handler. For
* example, you can use the above technique so that division by zero
* becomes defined to a specific value of your choosing!
*
* Please note that Xed isn't needed to recover from `SIGTRAP` which can
* be raised at any time by embedding `DebugBreak()` or `asm("int3")` in
* your program code. Your signal handler will automatically skip over
* the interrupt instruction, assuming your signal handler returns.
*
* The important signals supported across all platforms are:
*
* - `SIGINT`: When you press Ctrl-C this signal gets broadcasted to
* your process session group. This is the normal way to terminate
* console applications.
*
* - `SIGQUIT`: When you press CTRL-\ this signal gets broadcasted to
* your process session group. This is the irregular way to kill an
* application in cases where maybe your `SIGINT` handler is broken
* although, Cosmopolitan Libc ShowCrashReports() should program it
* such as to attach a debugger to the process if possible, or else
* show a crash report. Also note that in New Technology you should
* press CTRL+BREAK rather than CTRL+\ to get this signal.
*
* - `SIGHUP`: This gets sent to your non-daemon processes when you
* close your terminal session.
*
* - `SIGTERM` is what the `kill` command sends by default. It's the
* choice signal for terminating daemons.
*
* - `SIGUSR1` and `SIGUSR2` can be anything you want. Their default
* action is to kill the process. By convention `SIGUSR1` is usually
* used by daemons to reload the config file.
*
* - `SIGCHLD` is sent when a process terminates and it takes a certain
* degree of UNIX mastery to address sanely.
*
* - `SIGALRM` is invoked by `setitimer()` and `alarm()`. It can be
* useful for interrupting i/o operations like `connect()`.
*
* - `SIGTRAP`: This happens when an INT3 instruction is encountered.
*
* - `SIGILL` happens on illegal instructions, e.g. `UD2`.
*
* - `SIGABRT` happens when you call `abort()`.
*
* - `SIGFPE` happens when you divide ints by zero, among other things.
*
* - `SIGSEGV` and `SIGBUS` indicate memory access errors and they have
* inconsistent semantics across platforms like FreeBSD.
*
* - `SIGWINCH` is sent when your terminal window is resized.
*
* - `SIGXCPU` and `SIGXFSZ` may be raised if you run out of resources,
* which can happen if your process, or the parent process that
* spawned your process, happened to call `setrlimit()`. Doing this is
* a wonderful idea.
*
* @return 0 on success or -1 w/ errno
* @see xsigaction() for a much better api
* @asyncsignalsafe
* @vforksafe
*/
int sigaction(int sig, const struct sigaction *act, struct sigaction *oldact) {
int rc;
if (sig == SIGKILL || sig == SIGSTOP) {
rc = einval();
} else {
rc = __sigaction(sig, act, oldact);
}
STRACE("sigaction(%G, %s, [%s]) → %d% m", sig, DescribeSigaction(0, act),
DescribeSigaction(rc, oldact), rc);
return rc;
}