[Git][ghc/ghc][wip/dcoutts/signals-cleanup] 18 commits: Change sigprocmask to pthread_sigmask in a couple places in the rts
Duncan Coutts pushed to branch wip/dcoutts/signals-cleanup at Glasgow Haskell Compiler / GHC Commits: f926f179 by Duncan Coutts at 2026-10-22T09:42:05+01:00 Change sigprocmask to pthread_sigmask in a couple places in the rts This is part of a series of changes to fix or remove uses of sigprocmask. See issue #27968. According to Posix:
The use of the sigprocmask() function is unspecified in a multi-threaded process.
and indeed it does different things on different platforms. In particular on macOS the behaviour is to change the signal mask for every thread in the process (there is no per-process mask, it changes the per-thread mask for every thread). This obviously does not mix well with other concurrent changes to signal masks in other threads. The use of sigprocmask in exitBySignal just needs to unmask a signal in the current OS thread so that it can send a signal to itself. This purpose only requires changing the signal mask of the calling thread, which is exactly what pthread_sigmask is specified to do. In resetTerminalSettings, sigprocmask (now pthread_sigmask) is used in an attempt to mask a signal. It is unclear if this is effective. It depends on whether there are any remaining threads running by the time the function is called during shutdown. Add a Note [pthread_sigmask and the ineffectiveness of masking signals] and refer to it. - - - - - 4647eb92 by Duncan Coutts at 2026-10-22T09:42:05+01:00 Change (un)blockUserSignals to use pthread_sigmask, not sigprocmask These functions are exported from the RTS (on posix platforms). They are used in the process library to temporarily mask signals during a fork(). This is only needed to ensure the new process has the signals masked initially. So in particular for this use case we want it to only affect the signal mask of the calling thread. Thus pthread_sigmask is appropriate. - - - - - 2c282519 by Duncan Coutts at 2026-10-22T09:42:05+01:00 Make (un)blockUserSignals local functions in win32 console handling These functions were defined for all platforms in the RTS public headers but only exported from the RTS on non-win32 platforms. They are only used externally (by the process library) on posix platforms. So for win32, break the link with the exported names and use local only C static functions. They do serve a local purpose, but are now unrelated to the posix ones. - - - - - ae933af6 by Duncan Coutts at 2026-10-22T09:42:05+01:00 In System.Posix.Internals, change import of sigprocmask to pthread_sigmask and refer to the Note. It's still pretty dubious! - - - - - c8736342 by Duncan Coutts at 2026-10-22T09:42:05+01:00 Drop use of sigprocmask in stg_sig_install It is somewhat unclear what the signal masking was trying to protect in stg_sig_install. The comment said // Block the signal until we figure out what to do There are no shared data structured between stg_sig_install and the generic_handler that it installs. In any case, masking signals does not in general work, so whatever it was doing was a false sense of security. - - - - - ff39bcb0 by Duncan Coutts at 2026-10-22T09:42:05+01:00 Make startPendingSignalHandlers a per-platform, not common, API The direction of travel is that user-signal handling should be managed by the I/O manager(s). This is because signals (& win32 console events) are (a funny kind of) I/O, and also because they have to be involved in noticing signals and starting signal handlers. And how we communicate between the low level signal handler and starting the Haskell signal handler threads is also speific to the I/O manager implementation. There is no need for a common API here. These are just utilities shared between some I/O manager implementations. - - - - - 8d91f749 by Duncan Coutts at 2026-10-22T09:42:05+01:00 Unify freeSignalHandlers and finiUserSignals in RTS shutdown They were called at different stages of shutdown. Historically this might have made sense when the handler mechanism used stable pointers. Now there appears to be no good reason. On win32, freeSignalHandlers did nothing. On posix, finiUserSignals did nothing. There appears to be no dependency on the stage of shutdown. It is all local resources. - - - - - 6ef09cae by Duncan Coutts at 2026-10-22T09:42:05+01:00 Push checks on install_signal_handlers flag into signal functions Also, change the logic slightly. The docs for --install-signal-handlers say that it installs handlers for ctl-c etc. It does _not_ say that it disables the API for Haskell code to install signal handerls. Previously however the RTS startup code would guard initUserSignals behind the flag install_signal_handlers. All that code does is initalise variables properly. This meant that when user code installs a handler, it would be working with ill-defined userSignals value and an un-initialised mutex! Similarly, in the win32 console handling, it would skip initialising the hConsoleEvent, which certainly cannot lead to good outcomes. So now we only guard initDefaultHandlers and resetDefaultHandlers behind the install_signal_handlers flag. - - - - - 30eb1db7 by Duncan Coutts at 2026-10-22T09:42:05+01:00 Fix user guide reference to --install-signal-handlers While reviewing --install-signal-handlers docs, noticed a typo in the --generate-crash-dumps docs that referred to --install-signal-handlers when it means --install-seh-handlers. Yes I double-checked the code. - - - - - 44a3e261 by Duncan Coutts at 2026-10-22T14:43:43+01:00 Split user signal functions out of posix/Signals into new file The direction of travel is that user-signal handling should be managed by the I/O manager(s). The user signal functions (i.e. to allow Haskell code to set signal handlers) should stop being first class functions called by the rest of the RTS and become utilities used by the I/O managers. Start here by splitting them out. - - - - - b99b82fb by Duncan Coutts at 2026-10-22T14:49:18+01:00 Make stg_sig_install part of the IOManager API This is the external entry point for user code to install signal handlers. So it becomes part of the I/O manager API. Eventually it will dispatch to the I/O manager implementations (which will do different things), but for now it dispatches to the same old implementation, under a new name. - - - - - 103a6e93 by Duncan Coutts at 2026-10-22T14:49:20+01:00 Document that nocldstop is a totally mad implicit parameter and it's part of our public API! - - - - - 6a4e9de3 by Duncan Coutts at 2026-10-22T14:49:20+01:00 Move user signal init and fini into the I/O manager Initially just moved into start/stopIOManager, but a later step will be to make that be part of the initialisation of each I/O manager. Why? Because they cannot have a common init if they have different data structures that need initialisation. In fact they already do have different code and data (threaded/non-threaded, windows/other), but this is fudged using CPP. - - - - - ebe75c89 by Duncan Coutts at 2026-10-22T14:49:20+01:00 Push {init,fini}{UserSignals,ConsoleEvents} down into I/O managers So they become part of individual I/O managers, which will allow us to start specialising them more sanely. Rename the Win32 ones to {init,fini}ConsoleEvents. - - - - - 7cc77334 by Duncan Coutts at 2026-10-22T15:07:19+01:00 Push installUserSignalHandler down into individual I/O managers This will allow us to specialise them. Initally they all use the same (existing) generic_handler. - - - - - d8e070f7 by Duncan Coutts at 2026-10-22T15:07:19+01:00 Specialise MIO's installing of signals It already used a separate implementation, but using cpp via the signal "generic_handler". Now it is much more direct and local. MIO writes signals into a pipe and reads and dispatches them at the other end (in Haskell). - - - - - ce8ccebf by Duncan Coutts at 2026-10-22T15:15:41+01:00 Introduce a I/O manager data structure shared between all caps Accessed via cap->iomgr_shared, but it points to the same struct for all capabilities. We initialise and free this with cap 0. Use this initially for the MIO I/O manager's timer manager control fd. This fd is used for signals. Soon we will use the same mechanism for the same purpose of signal handling, but for the other posix I/O managers. This is a fairly general mechanism, so other I/O managers may be able to make use of it, once they are adapted to work in the threaded RTS with multiple capabilities. - - - - - 544e5e6b by Duncan Coutts at 2026-10-22T15:15:41+01:00 Extract and add more utility functions for the signal self-pipe trick Extract a utility function writeSignalInfoToPipe from the MIO I/O manager so we can use it in other I/O managers too. Also add related utility functions readSignalInfoFromPipe, newNonBlockingPipe and startSignalHandler. We will use these in the poll and selectbis I/O managers. - - - - - 26 changed files: - libraries/ghc-internal/src/GHC/Internal/System/Posix/Internals.hs - rts/IOManager.c - rts/IOManagerInternals.h - rts/RtsFlags.c - rts/RtsSignals.h - rts/RtsStartup.c - rts/configure.ac - rts/include/Rts.h - rts/include/rts/BlockSignals.h - rts/include/rts/IOInterface.h - + rts/posix/IOManSignals.c - + rts/posix/IOManSignals.h - rts/posix/MIO.c - rts/posix/MIO.h - rts/posix/Poll.c - rts/posix/Poll.h - rts/posix/Select.c - rts/posix/Select.h - rts/posix/SelectBis.c - rts/posix/SelectBis.h - rts/posix/Signals.c - rts/posix/TTY.c - rts/posix/Ticker.c - rts/rts.cabal - rts/win32/ConsoleHandler.c - rts/win32/ConsoleHandler.h Changes: ===================================== libraries/ghc-internal/src/GHC/Internal/System/Posix/Internals.hs ===================================== @@ -878,7 +878,12 @@ foreign import capi unsafe "signal.h sigemptyset" foreign import capi unsafe "signal.h sigaddset" c_sigaddset :: Ptr CSigset -> CInt -> IO CInt -foreign import capi unsafe "signal.h sigprocmask" +-- Actually uses @pthread_sigmask@, which is the more modern version +-- specified by Posix. pthread_sigmask() is specified to be per-thread. +-- +-- Use of this is still very dubious however! +-- See Note [pthread_sigmask and the ineffectiveness of masking signals] +foreign import capi unsafe "signal.h pthread_sigmask" c_sigprocmask :: CInt -> Ptr CSigset -> Ptr CSigset -> IO CInt #endif ===================================== rts/IOManager.c ===================================== @@ -27,6 +27,11 @@ #include "IOManagerInternals.h" +#if !defined(mingw32_HOST_OS) +// TODO: make this per-I/O manager, not called from here directly. +#include "posix/IOManSignals.h" +#endif + #if defined(IOMGR_ENABLED_SELECT) #include "Threads.h" #include "posix/Select.h" @@ -50,6 +55,7 @@ #if defined(IOMGR_ENABLED_MIO_WIN32) #include "win32/ThrIOManager.h" #include "win32/AsyncMIO.h" +#include "win32/ConsoleHandler.h" #endif #if defined(IOMGR_ENABLED_WIN32_LEGACY) @@ -57,6 +63,7 @@ #include "win32/AsyncMIO.h" #include "win32/AwaitEvent.h" #include "win32/MIOManager.h" +#include "win32/ConsoleHandler.h" #endif #if defined(IOMGR_ENABLED_WINIO) @@ -65,6 +72,7 @@ #if !defined(THREADED_RTS) #include "win32/AwaitEvent.h" #endif +#include "win32/ConsoleHandler.h" #endif #include <string.h> @@ -348,6 +356,15 @@ CapIOManager *allocCapabilityIOManager(Capability *cap) CapIOManager *iomgr = stgMallocBytes(sizeof(CapIOManager), "allocCapabilityIOManager"); iomgr->cap = cap; /* link back */ + + /* Allocate and/or link the shared I/O manager data structure */ + if (cap->no == 0) { + iomgr->shared = stgMallocBytes(sizeof(CapIOManagerShared), + "allocCapabilityIOManager"); + } else { + iomgr->shared = MainCapability.iomgr->shared; + } + return iomgr; } @@ -364,6 +381,8 @@ void initCapabilityIOManager(CapIOManager *iomgr) debugTrace(DEBUG_iomanager, "initialising I/O manager %s for cap %d", showIOManager(), iomgr->cap->no); + ASSERT(iomgr->cap && iomgr->shared); /* These are initialised already */ + switch (iomgr_type) { #if defined(IOMGR_ENABLED_SELECT) case IO_MANAGER_SELECT: @@ -392,7 +411,7 @@ void initCapabilityIOManager(CapIOManager *iomgr) #if defined(IOMGR_ENABLED_MIO_POSIX) case IO_MANAGER_MIO_POSIX: - iomgr->control_fd = -1; + initCapabilityIOManagerMIO(iomgr); break; #endif default: @@ -424,6 +443,13 @@ void freeCapabilityIOManager(CapIOManager *iomgr) default: break; } + + /* We expect the per-impl free function (for cap 0) to free anything within + * the shared structure. + */ + if (iomgr->cap->no == 0) { + stgFree(iomgr->shared); + } } @@ -449,6 +475,7 @@ void startIOManager(void) * TODO: rename ioManagerStart to be less generic, impl specific */ ioManagerStart(); + initConsoleEvents(); //TODO: fully integrate break; #endif #if defined(IOMGR_ENABLED_WINIO) @@ -465,11 +492,13 @@ void startIOManager(void) #else startupAsyncWinIO(); #endif + initConsoleEvents(); //TODO: fully integrate break; #endif #if defined(IOMGR_ENABLED_WIN32_LEGACY) case IO_MANAGER_WIN32_LEGACY: startupAsyncIO(); + initConsoleEvents(); //TODO: fully integrate break; #endif default: @@ -566,14 +595,21 @@ void exitIOManager(bool wait_threads) { switch (iomgr_type) { +#if defined(IOMGR_ENABLED_MIO_WIN32) + case IO_MANAGER_MIO_WIN32: + finiConsoleEvents(); //TODO: fully integrate + break; +#endif #if defined(IOMGR_ENABLED_WINIO) case IO_MANAGER_WINIO: shutdownAsyncWinIO(wait_threads); + finiConsoleEvents(); //TODO: fully integrate break; #endif #if defined(IOMGR_ENABLED_WIN32_LEGACY) case IO_MANAGER_WIN32_LEGACY: shutdownAsyncIO(wait_threads); + finiConsoleEvents(); //TODO: fully integrate break; #endif default: @@ -634,6 +670,67 @@ setIOManagerControlFd(uint32_t cap_no, int fd) { #endif +/* This is a plausible candidate for a newer public API, but it isn't yet. + * It is currently the worker for stg_sig_install below. + */ +static int installUserSignalHandler(int sig, int spi, sigset_t *mask, + bool nocldstop) +{ +#if !defined(RTS_USER_SIGNALS) + return STG_SIG_DFL; +#endif + + debugTrace(DEBUG_iomanager, "Installing a signal handler for sig %d", sig); + + switch (iomgr_type) { +#if defined(IOMGR_ENABLED_SELECT) + case IO_MANAGER_SELECT: + return installUserSignalHandlerSelect(sig, spi, mask, nocldstop); +#endif +#if defined(IOMGR_ENABLED_SELECTBIS) + case IO_MANAGER_SELECTBIS: + return installUserSignalHandlerSelectBis(sig, spi, mask, nocldstop); +#endif +#if defined(IOMGR_ENABLED_POLL) + case IO_MANAGER_POLL: + return installUserSignalHandlerPoll(sig, spi, mask, nocldstop); +#endif +#if defined(IOMGR_ENABLED_MIO) + case IO_MANAGER_MIO: + return installUserSignalHandlerMIO(sig, spi, mask, nocldstop); +#endif + default: + barf("installUserSignalHandler not implemented"); + } +} + + + +#if !defined(mingw32_HOST_OS) +/* This flag is a public API, used by the unix package. It is an _implicit_ + * argument to stg_sig_install to control whether or not to include + * SA_NOCLDSTOP when installing a SIGCHLD handler. + * + * Yes this is completely mad, and it should really be a normal explicit + * parameter. Note also the total lack of protection against data races. + */ +HsInt nocldstop = 0; + + +/* Declared in rts/IOInterface.h. This is a public API, used by the unix + * package for installHandler. + * + * This is used as an FFI ccall import, but it would be better as a primop, for + * consistency and so we can always have a Capability to hand. + */ +int stg_sig_install(int sig, int spi, void *mask) +{ + /* Grab the current value of the nocldstop argument. Yes this is madness. */ + return installUserSignalHandler(sig, spi, mask, nocldstop); +} +#endif + + void pollCompletedTimeoutsOrIO(CapIOManager *iomgr) { debugTrace(DEBUG_iomanager, "polling for completed IO or timeouts"); ===================================== rts/IOManagerInternals.h ===================================== @@ -30,6 +30,11 @@ #include "BeginPrivate.h" +/* Forward reference */ +struct _CapIOManagerShared; +typedef struct _CapIOManagerShared CapIOManagerShared; + + /* The per-capability data structures belonging to the I/O manager. * * It can be accessed as cap->iomgr. Or given just the iomgr, you can access @@ -42,9 +47,12 @@ */ struct _CapIOManager { - /* Back reference to the containing capability */ + /* Back reference to the containing capability */ Capability *cap; + /* Data shared between the I/O manager instances across all capabilities */ + CapIOManagerShared *shared; + #if defined(IOMGR_ENABLED_SELECT) /* Thread queue for threads blocked on I/O completion. */ StgTSO *blocked_queue_hd; @@ -96,6 +104,24 @@ struct _CapIOManager { }; + +/* Much like above, but for I/O manager data that is shared between the + * I/O manager instances for all the capabilities. + * + * This gets allocated and linked by the shared IOManager.c code, and should be + * initialised by the individual I/O manager's init function but only for cap 0. + */ +struct _CapIOManagerShared { + +#if defined(IOMGR_ENABLED_MIO_POSIX) + /* The timer manager control pipe (write end). This is the pipe into which + * we will send our signals. + */ + int timer_manager_control_wr_fd; +#endif +}; + + /* Fill in the outcome and result/error on the TSO's stack frame. * The TSO must be blocked using one of the stg_block_io_* blocking actions. * ===================================== rts/RtsFlags.c ===================================== @@ -535,9 +535,8 @@ usage_text[] = { " --install-seh-handlers=<yes|no>", " Install exception handlers (default: yes)", " --generate-crash-dumps", -" Generate Windows crash dumps, requires exception handlers", -" to be installed. Implies --install-signal-handlers=yes.", -" (default: no)", +" Generate Windows crash dumps (default: no).", +" Implies --install-seh-handlers=yes", " --generate-stack-traces=<yes|no>", " Generate a stack trace when your application encounters a", " fatal error. When symbols are available an attempt will be", ===================================== rts/RtsSignals.h ===================================== @@ -15,13 +15,6 @@ #include "BeginPrivate.h" -/* - * Function: initUserSignals() - * - * Initialize the console handling substrate. - */ -void initUserSignals(void); - /* * Function: initDefaultHandlers() * @@ -31,24 +24,6 @@ void initUserSignals(void); void initDefaultHandlers(void); void resetDefaultHandlers(void); -void freeSignalHandlers(void); - -/* Tear down and shut down user signal processing. - * This is called *after* freeSignalHandlers, but unconditionally! - * TODO: unify this and freeSignalHandlers together, and make them make sense! - */ -void finiUserSignals(void); - -/* - * Function: startPendingSignalHandlers() - * - * If there are any queued up posix signals or win32 console events, run the - * handlers associated with them. This is used by some in-RTS I/O managers. - */ -#if !defined(THREADED_RTS) -void startPendingSignalHandlers(Capability *cap); -#endif - #include "EndPrivate.h" #endif /* RTS_USER_SIGNALS */ ===================================== rts/RtsStartup.c ===================================== @@ -423,12 +423,8 @@ hs_init_ghc(int *argc, char **argv[], RtsConfig rts_config) unpauseTimer(); #if defined(RTS_USER_SIGNALS) - if (RtsFlags.MiscFlags.install_signal_handlers) { - /* Initialise the user signal handler set */ - initUserSignals(); - /* Set up handler to run on SIGINT, etc. */ - initDefaultHandlers(); - } + /* Set up handler to run on SIGINT, etc. */ + initDefaultHandlers(); #endif startIOManager(); @@ -510,12 +506,6 @@ hs_exit_(bool wait_foreign) } runAllCFinalizers(nonmoving_weak_ptr_list); -#if defined(RTS_USER_SIGNALS) - if (RtsFlags.MiscFlags.install_signal_handlers) { - freeSignalHandlers(); - } -#endif - /* We rely on the guarantee that exitTimer stops the timer synchronously, * which ensures the timer handler does not get run again after this point. * We are about to start freeing resources used by the timer handler (like @@ -540,10 +530,8 @@ hs_exit_(bool wait_foreign) #endif #if defined(RTS_USER_SIGNALS) - if (RtsFlags.MiscFlags.install_signal_handlers) { - // uninstall signal handlers - resetDefaultHandlers(); - } + // uninstall signal handlers + resetDefaultHandlers(); #endif /* stop timing the shutdown, we're about to print stats */ @@ -623,10 +611,6 @@ hs_exit_(bool wait_foreign) hs_restoreConsoleCP(); #endif -#if defined(RTS_USER_SIGNALS) - finiUserSignals (); -#endif - /* tear down statistics subsystem */ stat_exit(); @@ -725,10 +709,12 @@ exitBySignal(int sig) dfl.sa_handler = SIG_DFL; (void)sigaction(sig, &dfl, NULL); - // Then we unblock the signal so we can deliver it to ourselves + // Then we unmask the signal so we can deliver it to ourselves. + // This is a (rare) valid use of signal mask manipulation. + // See Note [pthread_sigmask and the ineffectiveness of masking signals]. sigemptyset(&sigset); sigaddset(&sigset, sig); - sigprocmask(SIG_UNBLOCK, &sigset, NULL); + pthread_sigmask(SIG_UNBLOCK, &sigset, NULL); switch (sig) { case SIGSTOP: case SIGTSTP: case SIGTTIN: case SIGTTOU: case SIGCONT: ===================================== rts/configure.ac ===================================== @@ -221,10 +221,6 @@ AC_LINK_IFELSE([AC_LANG_CALL([], [printf\$LDBLStub])], FP_CHECK_PTHREAD_FUNCS -dnl ** check for eventfd which is needed by the I/O manager -AC_CHECK_HEADERS([sys/eventfd.h]) -AC_CHECK_FUNCS([eventfd]) - AC_CHECK_FUNCS([getpid getuid raise]) dnl large address space support (see rts/include/rts/storage/MBlock.h) @@ -359,6 +355,10 @@ dnl ------------------------------------------------------------------- dnl Here we check for platform constraints. The result is the CPP flag dnl IOMGR_BUILD_<name> and a EnableIOManager<Name> var for use here later. +dnl Check for functions (optionally) used by several I/O managers +AC_CHECK_HEADERS([sys/eventfd.h]) +AC_CHECK_FUNCS([eventfd pipe2]) + GHC_IOMANAGER_ENABLE([select], [EnableIOManagerSelect], [IOMGR_BUILD_SELECT], [if test "$HostOS" = "mingw32"; then EnableIOManagerSelect=NO ===================================== rts/include/Rts.h ===================================== @@ -283,10 +283,6 @@ void exitHeapOverflow(void) STG_NORETURN;; void stg_exit(int n) STG_NORETURN; -#if !defined(mingw32_HOST_OS) -int stg_sig_install (int, int, void *); -#endif - /* ----------------------------------------------------------------------------- Ways -------------------------------------------------------------------------- */ ===================================== rts/include/rts/BlockSignals.h ===================================== @@ -13,16 +13,25 @@ #pragma once -/* Used by runProcess() in the process package +#if !defined(mingw32_HOST_OS) + +/* Used by runProcess() in the process package, but this is almost certainly + * a bad idea. + * + * See also: + * + https://github.com/haskell/process/issues/384 + * + https://github.com/haskell/process/issues/385 + * + GHC issue #27968 + * + See Note [pthread_sigmask and the ineffectiveness of masking signals] */ /* * Function: blockUserSignals() * - * Temporarily block the delivery of further console events. Needed to - * avoid race conditions when GCing the queue of outstanding handlers or - * when emptying the queue by running the handlers. + * Temporarily block the delivery of further user-registered posix signals. * + * This is exported from the RTS but should no longer be used. It is likely to + * be removed in future. */ void blockUserSignals(void); @@ -32,3 +41,5 @@ void blockUserSignals(void); * The inverse of blockUserSignals(); re-enable the deliver of console events. */ void unblockUserSignals(void); + +#endif ===================================== rts/include/rts/IOInterface.h ===================================== @@ -33,6 +33,7 @@ void ioManagerFinished (void); void setIOManagerControlFd (uint32_t cap_no, int fd); void setTimerManagerControlFd(int fd); +int stg_sig_install(int sig, int spi, void *mask); #endif ===================================== rts/posix/IOManSignals.c ===================================== @@ -0,0 +1,389 @@ +/* ----------------------------------------------------------------------------- + * + * (c) The GHC Team, 1998-2005 + * + * Signal processing / handling. + * + * ---------------------------------------------------------------------------*/ + +#include "rts/PosixSource.h" +#include "Rts.h" + +#if defined(RTS_USER_SIGNALS) + +#include "RtsSignals.h" +#include "IOManSignals.h" +#include "RtsUtils.h" +#include "Schedule.h" +#include "Prelude.h" +#include "ThreadLabels.h" +#include "Libdw.h" +#include "MIO.h" + +#include <unistd.h> +#include <signal.h> +#include <fcntl.h> +#include <string.h> + +/* ----------------------------------------------------------------------------- + * The table of signal handlers + * -------------------------------------------------------------------------- */ + +/* SUP: The type of handlers is a little bit, well, doubtful... */ +StgInt *signal_handlers = NULL; /* Dynamically grown array of signal handlers */ +static StgInt nHandlers = 0; /* Size of handlers array */ + +static sigset_t userSignals; +static sigset_t savedSignals; + +#if defined(THREADED_RTS) +static Mutex sig_mutex; // protects signal_handlers, nHandlers +#endif + +/* ----------------------------------------------------------------------------- + * Initialisation / deinitialisation + * -------------------------------------------------------------------------- */ + +void +initUserSignals(void) +{ + sigemptyset(&userSignals); +#if defined(THREADED_RTS) + initMutex(&sig_mutex); +#endif +} + +void finiUserSignals(void) +{ + if (signal_handlers != NULL) { + stgFree(signal_handlers); + signal_handlers = NULL; + nHandlers = 0; + } +#if defined(THREADED_RTS) + closeMutex(&sig_mutex); +#endif +}; + +/* ----------------------------------------------------------------------------- + * Allocate/resize the table of signal handlers. + * -------------------------------------------------------------------------- */ + +static void +more_handlers(int sig) +{ + StgInt i; + + if (sig < nHandlers) + return; + + if (signal_handlers == NULL) + signal_handlers = (StgInt *)stgMallocBytes((sig + 1) * sizeof(StgInt), + "more_handlers"); + else + signal_handlers = (StgInt *)stgReallocBytes(signal_handlers, + (sig + 1) * sizeof(StgInt), + "more_handlers"); + + for(i = nHandlers; i <= sig; i++) + // Fill in the new slots with default actions + signal_handlers[i] = STG_SIG_DFL; + + nHandlers = sig + 1; +} + +#if !defined(THREADED_RTS) + +#define N_PENDING_HANDLERS 16 + +siginfo_t pending_handler_buf[N_PENDING_HANDLERS]; +siginfo_t *next_pending_handler = pending_handler_buf; + +static inline bool signals_pending(void) { + return (next_pending_handler != pending_handler_buf); +} + +#endif /* THREADED_RTS */ + +/* ----------------------------------------------------------------------------- + * Low-level signal handler + * + * Places the requested handler on a stack of pending handlers to be + * started up at the next context switch. + * -------------------------------------------------------------------------- */ + +#if !defined(THREADED_RTS) +void +generic_handler(int sig USED_IF_THREADS, + siginfo_t *info, + void *p STG_UNUSED) +{ + + /* Can't call allocate from here. Probably can't call malloc + either. However, we have to schedule a new thread somehow. + + It's probably ok to request a context switch and allow the + scheduler to start the handler thread, but how do we + communicate this to the scheduler? + + We need some kind of locking, but with low overhead (i.e. no + blocking signals every time around the scheduler). + + Signal Handlers are atomic (i.e. they can't be interrupted), and + we can make use of this. We just need to make sure the + critical section of the scheduler can't be interrupted - the + only way to do this is to block signals. However, we can lower + the overhead by only blocking signals when there are any + handlers to run, i.e. the set of pending handlers is + non-empty. + */ + + /* We use a stack to store the pending signals. We can't + dynamically grow this since we can't allocate any memory from + within a signal handler. + + Hence unfortunately we have to bomb out if the buffer + overflows. It might be acceptable to carry on in certain + circumstances, depending on the signal. + */ + + memcpy(next_pending_handler, info, sizeof(siginfo_t)); + + next_pending_handler++; + + // stack full? + if (next_pending_handler == &pending_handler_buf[N_PENDING_HANDLERS]) { + errorBelch("too many pending signals"); + stg_exit(EXIT_FAILURE); + } + + interruptCapability(&MainCapability); + +} +#endif /* THREADED_RTS */ + +/* ----------------------------------------------------------------------------- + * Blocking/Unblocking of the user signals + * -------------------------------------------------------------------------- */ + +void +blockUserSignals(void) +{ + pthread_sigmask(SIG_BLOCK, &userSignals, &savedSignals); +} + +void +unblockUserSignals(void) +{ + pthread_sigmask(SIG_SETMASK, &savedSignals, NULL); +} + +/* ----------------------------------------------------------------------------- + * Install a Haskell signal handler. + * + * We should really do this in Haskell in GHC.Conc, and share the + * signal_handlers array with the one there. + * + * -------------------------------------------------------------------------- */ + +int +installSignalHandler(int sig, int spi, sigset_t *mask, bool nocldstop, + SignalHandler signal_handler) +{ + ACQUIRE_LOCK(&sig_mutex); + + // Use sigaddset as a way to validate the signal number. + // We do not use the resulting signal set. + { + sigset_t signals; + sigemptyset(&signals); + if (sig < 0 || sigaddset(&signals, sig)) { + RELEASE_LOCK(&sig_mutex); + return STG_SIG_ERR; + } + } + + more_handlers(sig); + + StgInt previous_spi = signal_handlers[sig]; + + struct sigaction action; + memset(&action, 0, sizeof(struct sigaction)); + action.sa_flags = 0; + + switch(spi) { + case STG_SIG_IGN: + action.sa_handler = SIG_IGN; + break; + + case STG_SIG_DFL: + action.sa_handler = SIG_DFL; + break; + + case STG_SIG_RST: + action.sa_flags |= SA_RESETHAND; + /* fall through */ + case STG_SIG_HAN: + action.sa_sigaction = signal_handler; + action.sa_flags |= SA_SIGINFO; + break; + + default: + barf("stg_sig_install: bad spi"); + } + + if (mask != NULL) { + action.sa_mask = *mask; + } else { + sigemptyset(&action.sa_mask); + } + + action.sa_flags |= sig == SIGCHLD && nocldstop ? SA_NOCLDSTOP : 0; + + if (sigaction(sig, &action, NULL)) { + errorBelch("sigaction"); + RELEASE_LOCK(&sig_mutex); + return STG_SIG_ERR; + } + + signal_handlers[sig] = spi; + + switch(spi) { + case STG_SIG_RST: + case STG_SIG_HAN: + sigaddset(&userSignals, sig); + break; + + default: + sigdelset(&userSignals, sig); + break; + } + + RELEASE_LOCK(&sig_mutex); + return previous_spi; +} + +/* ----------------------------------------------------------------------------- + * Creating new threads for signal handlers. + * -------------------------------------------------------------------------- */ + +#if !defined(THREADED_RTS) +void +startPendingSignalHandlers(Capability *cap) +{ + siginfo_t *info; + int sig; + + if (!signals_pending()) return; + + blockUserSignals(); + + while (next_pending_handler != pending_handler_buf) { + + next_pending_handler--; + + sig = next_pending_handler->si_signo; + if (signal_handlers[sig] == STG_SIG_DFL) { + continue; // handler has been changed. + } + + info = next_pending_handler; + startSignalHandler(cap, sig, info); + } + + unblockUserSignals(); +} +#endif + +void startSignalHandler(Capability *cap, int sig, siginfo_t *info) +{ + /* Allocate a copy. This is freed by runHandler. */ + // TODO: this could be improved to use a GC'd pinned byte array, but this + // would need coordination with the unix library. + siginfo_t *info_copy = stgMallocBytes(sizeof(siginfo_t), "startSignalHandler"); + *info_copy = *info; + + /* The info structure can be zero on solaris. So at least set the signo. */ + info_copy->si_signo = sig; + + debugTrace(DEBUG_iomanager, + "Handling pending signal, no %d", info_copy->si_signo); + + StgTSO *t = + createIOThread(cap, + RtsFlags.GcFlags.initialStkSize, + rts_apply(cap, + rts_apply(cap, + runHandlersPtr_closure, + rts_mkPtr(cap, info_copy)), + rts_mkInt(cap, info_copy->si_signo))); + scheduleThread(cap, t); + setThreadLabel(cap, t, "signal handler thread"); +} + +void newNonBlockingPipe(int *pipe_fd_r, int *pipe_fd_w) +{ + int pipefd[2]; +#if defined(HAVE_PIPE2) + int res = pipe2(pipefd, O_CLOEXEC | O_NONBLOCK); +#else + int res = pipe(pipefd); +#endif + if (RTS_UNLIKELY(res < 0)) { + sysErrorBelch("newNonBlockingPipe"); + stg_exit(EXIT_FAILURE); + } +#if !defined(HAVE_PIPE2) + for (int i = 0; i < 2; i++) { + int res1 = fcntl(pipefd[i], F_SETFD, FD_CLOEXEC); + int res2 = fcntl(pipefd[i], F_SETFL, O_NONBLOCK); + if (RTS_UNLIKELY(res1 < 0 || res2 < 0)) { + sysErrorBelch("newFdWakeup fcntl()"); + stg_exit(EXIT_FAILURE); + } + } +#endif + *pipe_fd_r = pipefd[0]; /* read end */ + *pipe_fd_w = pipefd[1]; /* write end */ +} + +/* Write the signal number and siginfo into the given fd (which is + * typically a pipe in non-blocking mode). + */ +void writeSignalInfoToPipe(int sig, siginfo_t *info, int fd) +{ + StgWord8 buf[sizeof(siginfo_t) + 1]; + + buf[0] = sig; + if (info) { + memcpy(buf+1, info, sizeof(siginfo_t)); + } else { + // info may be NULL on Solaris (see #3790) + memset(buf+1, 0, sizeof(siginfo_t)); + } + + int r = write(fd, buf, sizeof(siginfo_t)+1); + if (r == -1 && errno == EAGAIN) { + errorBelch("lost signal due to full pipe: %d\n", sig); + } +} + +bool readSignalInfoFromPipe(int *sig, siginfo_t *info, int fd) +{ + StgWord8 buf[sizeof(siginfo_t) + 1]; + + int r = read(fd, buf, sizeof(siginfo_t)+1); + + if (r == sizeof(siginfo_t)+1) { + *sig = (int) buf[0]; + memcpy(info, buf+1, sizeof(siginfo_t)); + return true; + } else { + // TODO: if r is >0 and < expected then we're kind of screwed + // it means we're all out of sync with the protocol. + // it _should_ never happen of course! + return false; + } +} + +#endif /* RTS_USER_SIGNALS */ ===================================== rts/posix/IOManSignals.h ===================================== @@ -0,0 +1,58 @@ +/* ----------------------------------------------------------------------------- + * + * (c) The GHC Team, 1998-2005, 2026 + * + * Shared utilities for I/O managers: signal handling functionality. + * + * ---------------------------------------------------------------------------*/ + +#pragma once + +#if defined(RTS_USER_SIGNALS) + +#include <signal.h> + +#include "BeginPrivate.h" + +/* + * Function: initUserSignals() + * + * Initialize the console handling substrate. + */ +void initUserSignals(void); + +/* Finalise signal and console events handling. + */ +void finiUserSignals(void); + +#if !defined(THREADED_RTS) +/* + * Function: startPendingSignalHandlers() + * + * If there are any queued up posix signals, run the handlers + * associated with them. + */ +void startPendingSignalHandlers(Capability *cap); +#endif + +void startSignalHandler(Capability *cap, int sig, siginfo_t *info); + +typedef void (*SignalHandler)(int sig, siginfo_t *info, void *p); + +int installSignalHandler(int sig, int spi, sigset_t *mask, bool nocldstop, + SignalHandler handler); + +/* Utilities to help with the self-pipe trick for signal handling. */ +void newNonBlockingPipe(int *pipe_fd_r, int *pipe_fd_w); +void writeSignalInfoToPipe (int sig, siginfo_t *info, int fd); +bool readSignalInfoFromPipe(int *sig, siginfo_t *info, int fd); + +/* Temporary */ +void generic_handler(int sig USED_IF_THREADS, + siginfo_t *info, + void *p STG_UNUSED); + +#endif + +#include "EndPrivate.h" + ===================================== rts/posix/MIO.c ===================================== @@ -13,15 +13,19 @@ #include "rts/PosixSource.h" #include "Rts.h" +#include "IOManager.h" + +#if defined(IOMGR_ENABLED_MIO_POSIX) + +#include "MIO.h" +#include "IOManagerInternals.h" +#include "IOManSignals.h" + #include "Schedule.h" #include "RtsUtils.h" #include "Prelude.h" #include "ThreadLabels.h" -#include "MIO.h" -#include "IOManager.h" -#include "IOManagerInternals.h" - #if defined(HAVE_ERRNO_H) # include <errno.h> #endif @@ -29,62 +33,65 @@ #include <stdlib.h> #include <unistd.h> -// Here's the pipe into which we will send our signals -static int timer_manager_control_wr_fd = -1; -// TODO: Eliminate these globals. Put then into the CapIOManager, but the -// problem is these are shared across all caps, not per cap. - #define IO_MANAGER_DIE 0xfe +void initCapabilityIOManagerMIO(CapIOManager *iomgr) +{ + iomgr->control_fd = -1; + if (iomgr->cap == 0) { + iomgr->shared->timer_manager_control_wr_fd = -1; + } +} + void setTimerManagerControlFd(int fd) { - RELAXED_STORE(&timer_manager_control_wr_fd, fd); + int *timer_manager_control_wr_fd = + &MainCapability.iomgr->shared->timer_manager_control_wr_fd; + RELAXED_STORE(timer_manager_control_wr_fd, fd); } -#if defined(THREADED_RTS) -void timerManagerNotifySignal(int sig, siginfo_t *info) +static void signal_handler(int sig, siginfo_t *info, void *p STG_UNUSED) { - StgWord8 buf[sizeof(siginfo_t) + 1]; - int r; - - buf[0] = sig; - if (info == NULL) { - // info may be NULL on Solaris (see #3790) - memset(buf+1, 0, sizeof(siginfo_t)); - } else { - memcpy(buf+1, info, sizeof(siginfo_t)); - } - - int timer_control_fd = RELAXED_LOAD(&timer_manager_control_wr_fd); + /* In the signal handler we do not have Capability context, so access the + * control fd via MainCapability. + */ + int *timer_manager_control_wr_fd = + &MainCapability.iomgr->shared->timer_manager_control_wr_fd; + int timer_control_fd = RELAXED_LOAD(timer_manager_control_wr_fd); if (0 <= timer_control_fd) { - r = write(timer_control_fd, buf, sizeof(siginfo_t)+1); - if (r == -1 && errno == EAGAIN) { - errorBelch("lost signal due to full pipe: %d\n", sig); - } + writeSignalInfoToPipe(sig, info, timer_control_fd); } // If the IO manager hasn't told us what the FD of the write end // of its pipe is, there's not much we can do here, so just ignore // the signal.. } -#endif +int installUserSignalHandlerMIO(int sig, int spi, void *mask, + bool nocldstop) +{ + return installSignalHandler(sig, spi, mask, nocldstop, signal_handler); +} -#if defined(THREADED_RTS) void ioManagerDie (void) { + finiUserSignals(); + + int *timer_manager_control_wr_fd = + &MainCapability.iomgr->shared->timer_manager_control_wr_fd; + StgWord8 byte = (StgWord8)IO_MANAGER_DIE; uint32_t i; int r; { // Shut down timer manager - const int fd = RELAXED_LOAD(&timer_manager_control_wr_fd); + const int fd = RELAXED_LOAD(timer_manager_control_wr_fd); if (0 <= fd) { r = write(fd, &byte, 1); if (r == -1) { sysErrorBelch("ioManagerDie: write"); } - RELAXED_STORE(&timer_manager_control_wr_fd, -1); + RELAXED_STORE(timer_manager_control_wr_fd, -1); } } @@ -110,13 +117,23 @@ ioManagerStartCap (Capability **cap) void ioManagerStart (void) { + initUserSignals(); + + int *timer_manager_control_wr_fd = + &MainCapability.iomgr->shared->timer_manager_control_wr_fd; + // Make sure the IO manager thread is running Capability *cap; - if (SEQ_CST_LOAD(&timer_manager_control_wr_fd) < 0) { + if (SEQ_CST_LOAD(timer_manager_control_wr_fd) < 0) { cap = rts_lock(); ioManagerStartCap(&cap); rts_unlock(cap); } } -#endif +#else // !IOMGR_ENABLED_MIO_POSIX + +/* This is exported from the RTS unconditionally, but only used for MIO. */ +void setTimerManagerControlFd(int fd) { /* do nothing */ } + +#endif // IOMGR_ENABLED_MIO_POSIX ===================================== rts/posix/MIO.h ===================================== @@ -19,11 +19,14 @@ /* Communicating with the IO manager thread (see GHC.Conc). */ #if defined(THREADED_RTS) +void initCapabilityIOManagerMIO(CapIOManager *iomgr); + void ioManagerDie (void); void ioManagerStart (void); void ioManagerStartCap (/* inout */ Capability **cap); -void timerManagerNotifySignal(int sig, siginfo_t *info); +int installUserSignalHandlerMIO(int sig, int spi, void *mask, + bool nocldstop); #endif #include "EndPrivate.h" ===================================== rts/posix/Poll.c ===================================== @@ -23,7 +23,6 @@ #include "Trace.h" #include "Poll.h" -#include "RtsSignals.h" #include <limits.h> #include <errno.h> @@ -39,6 +38,7 @@ #endif #include "IOManagerInternals.h" +#include "IOManSignals.h" #include "Timeout.h" #include "FdWakeup.h" @@ -158,11 +158,23 @@ void initCapabilityIOManagerPoll(CapIOManager *iomgr) .revents = 0 }; iomgr->aiop_poll_table = iomgr->full_poll_table+1; /* hence empty */ + +#if defined(RTS_USER_SIGNALS) + /* Signal handlers are shared across all caps. Only init once. */ + if (iomgr->cap->no == 0) { + initUserSignals(); + } +#endif } void freeCapabilityIOManagerPoll(CapIOManager *iomgr) { +#if defined(RTS_USER_SIGNALS) + if (iomgr->cap->no == 0) { + finiUserSignals(); + } +#endif stgFree(iomgr->full_poll_table); #if defined(HAVE_PREEMPTION) closeFdWakeup(iomgr->interrupt_fd_r, iomgr->interrupt_fd_w); @@ -573,6 +585,13 @@ void interruptIOManagerPoll(CapIOManager *iomgr USED_IF_PREEMPTION) } +int installUserSignalHandlerPoll(int sig, int spi, void *mask, + bool nocldstop) +{ + return installSignalHandler(sig, spi, mask, nocldstop, generic_handler); +} + + /* Helper function to double the size of the aiop_table and aiop_poll_table. */ static bool enlargeTables(CapIOManager *iomgr) ===================================== rts/posix/Poll.h ===================================== @@ -34,6 +34,9 @@ void pollCompletedTimeoutsOrIOPoll(CapIOManager *iomgr); bool awaitCompletedTimeoutsOrIOPoll(CapIOManager *iomgr); void interruptIOManagerPoll(CapIOManager *iomgr); +/* Signals */ +int installUserSignalHandlerPoll(int sig, int spi, void *mask, bool nocldstop); + #endif /* IOMGR_ENABLED_POLL */ #include "EndPrivate.h" ===================================== rts/posix/Select.c ===================================== @@ -12,13 +12,13 @@ #include "rts/PosixSource.h" #include "Rts.h" -#include "RtsSignals.h" #include "Schedule.h" #include "Prelude.h" #include "RtsUtils.h" #include "Capability.h" #include "Select.h" #include "IOManagerInternals.h" +#include "IOManSignals.h" #include "Stats.h" #include "GetTime.h" #include "FdWakeup.h" @@ -72,10 +72,16 @@ void initCapabilityIOManagerSelect(CapIOManager *iomgr) barf("initCapabilityIOManagerSelect: fds out of select range"); } #endif +#if defined(RTS_USER_SIGNALS) + initUserSignals(); +#endif } void freeCapabilityIOManagerSelect(CapIOManager *iomgr USED_IF_PREEMPTION) { +#if defined(RTS_USER_SIGNALS) + finiUserSignals(); +#endif #if defined(HAVE_PREEMPTION) closeFdWakeup(iomgr->interrupt_fd_r, iomgr->interrupt_fd_w); #endif @@ -518,4 +524,10 @@ awaitCompletedTimeoutsOrIOSelect(CapIOManager *iomgr, bool wait) return !interrupt; } +int installUserSignalHandlerSelect(int sig, int spi, void *mask, + bool nocldstop) +{ + return installSignalHandler(sig, spi, mask, nocldstop, generic_handler); +} + #endif /* IOMGR_ENABLED_SELECT */ ===================================== rts/posix/Select.h ===================================== @@ -21,6 +21,8 @@ void wakeupIOManagerSelect(CapIOManager *iomgr); bool awaitCompletedTimeoutsOrIOSelect(CapIOManager *iomgr, bool wait); void interruptIOManagerSelect(CapIOManager *iomgr); +int installUserSignalHandlerSelect(int sig, int spi, void *mask, + bool nocldstop); #include "EndPrivate.h" ===================================== rts/posix/SelectBis.c ===================================== @@ -25,12 +25,12 @@ #include "Trace.h" #include "SelectBis.h" -#include "RtsSignals.h" #include <errno.h> #include <sys/select.h> #include "IOManagerInternals.h" +#include "IOManSignals.h" #include "Timeout.h" #include "FdWakeup.h" @@ -153,11 +153,23 @@ void initCapabilityIOManagerSelectBis(CapIOManager *iomgr) iomgr->rfds = stgMallocBytes(sizeof (fd_set), "IOManagerSelectBis"); iomgr->wfds = stgMallocBytes(sizeof (fd_set), "IOManagerSelectBis"); + +#if defined(RTS_USER_SIGNALS) + /* Signal handlers are shared across all caps. Only init once. */ + if (iomgr->cap->no == 0) { + initUserSignals(); + } +#endif } void freeCapabilityIOManagerSelectBis(CapIOManager *iomgr) { +#if defined(RTS_USER_SIGNALS) + if (iomgr->cap->no == 0) { + finiUserSignals(); + } +#endif stgFree(iomgr->rfds); stgFree(iomgr->wfds); #if defined(HAVE_PREEMPTION) @@ -583,6 +595,13 @@ void interruptIOManagerSelectBis(CapIOManager *iomgr USED_IF_PREEMPTION) } +int installUserSignalHandlerSelectBis(int sig, int spi, void *mask, + bool nocldstop) +{ + return installSignalHandler(sig, spi, mask, nocldstop, generic_handler); +} + + /* Helper function to double the size of the aiop_table. */ static bool enlargeTables(CapIOManager *iomgr) ===================================== rts/posix/SelectBis.h ===================================== @@ -55,6 +55,10 @@ void pollCompletedTimeoutsOrIOSelectBis(CapIOManager *iomgr); bool awaitCompletedTimeoutsOrIOSelectBis(CapIOManager *iomgr); void interruptIOManagerSelectBis(CapIOManager *iomgr); +/* Signals */ +int installUserSignalHandlerSelectBis(int sig, int spi, void *mask, + bool nocldstop); + #endif /* IOMGR_ENABLED_SELECTBIS */ #include "EndPrivate.h" ===================================== rts/posix/Signals.c ===================================== @@ -9,6 +9,8 @@ #include "rts/PosixSource.h" #include "Rts.h" +#if defined(RTS_USER_SIGNALS) + #include "RtsSignals.h" #include "RtsUtils.h" #include "Schedule.h" @@ -25,344 +27,46 @@ # endif #endif -#if defined(HAVE_UNISTD_H) -# include <unistd.h> -#endif - -#if defined(HAVE_SIGNAL_H) -# include <signal.h> -#endif - -#if defined(HAVE_TERMIOS_H) +#include <unistd.h> +#include <signal.h> #include <termios.h> -#endif - #include <string.h> -/* This curious flag is provided for the benefit of the Haskell binding - * to POSIX.1 to control whether or not to include SA_NOCLDSTOP when - * installing a SIGCHLD handler. - */ -HsInt nocldstop = 0; - -/* ----------------------------------------------------------------------------- - * The table of signal handlers - * -------------------------------------------------------------------------- */ - -#if defined(RTS_USER_SIGNALS) - -/* SUP: The type of handlers is a little bit, well, doubtful... */ -StgInt *signal_handlers = NULL; /* Dynamically grown array of signal handlers */ -static StgInt nHandlers = 0; /* Size of handlers array */ - -static sigset_t userSignals; -static sigset_t savedSignals; - -#if defined(THREADED_RTS) -static Mutex sig_mutex; // protects signal_handlers, nHandlers -#endif - -/* ----------------------------------------------------------------------------- - * Initialisation / deinitialisation - * -------------------------------------------------------------------------- */ - -void -initUserSignals(void) -{ - sigemptyset(&userSignals); -#if defined(THREADED_RTS) - initMutex(&sig_mutex); -#endif -} - -void -freeSignalHandlers(void) { - if (signal_handlers != NULL) { - stgFree(signal_handlers); - signal_handlers = NULL; - nHandlers = 0; - } -#if defined(THREADED_RTS) - closeMutex(&sig_mutex); -#endif -} - -void finiUserSignals(void) -{ - /* nothing */ -}; - -/* ----------------------------------------------------------------------------- - * Allocate/resize the table of signal handlers. - * -------------------------------------------------------------------------- */ - -static void -more_handlers(int sig) -{ - StgInt i; - - if (sig < nHandlers) - return; - - if (signal_handlers == NULL) - signal_handlers = (StgInt *)stgMallocBytes((sig + 1) * sizeof(StgInt), - "more_handlers"); - else - signal_handlers = (StgInt *)stgReallocBytes(signal_handlers, - (sig + 1) * sizeof(StgInt), - "more_handlers"); - - for(i = nHandlers; i <= sig; i++) - // Fill in the new slots with default actions - signal_handlers[i] = STG_SIG_DFL; - - nHandlers = sig + 1; -} - -#if !defined(THREADED_RTS) - -#define N_PENDING_HANDLERS 16 - -siginfo_t pending_handler_buf[N_PENDING_HANDLERS]; -siginfo_t *next_pending_handler = pending_handler_buf; - -static inline bool signals_pending(void) { - return (next_pending_handler != pending_handler_buf); -} - -#endif /* THREADED_RTS */ - -/* ----------------------------------------------------------------------------- - * Low-level signal handler +/* Note [pthread_sigmask and the ineffectiveness of masking signals] + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * - * Places the requested handler on a stack of pending handlers to be - * started up at the next context switch. - * -------------------------------------------------------------------------- */ - -static void -generic_handler(int sig USED_IF_THREADS, - siginfo_t *info, - void *p STG_UNUSED) -{ -#if defined(THREADED_RTS) - //TODO: This calls MIO directly. We should go via IOManager API. - // The IOManager API should be extended to cover signals. - timerManagerNotifySignal(sig, info); -#else /* not THREADED_RTS */ - - /* Can't call allocate from here. Probably can't call malloc - either. However, we have to schedule a new thread somehow. - - It's probably ok to request a context switch and allow the - scheduler to start the handler thread, but how do we - communicate this to the scheduler? - - We need some kind of locking, but with low overhead (i.e. no - blocking signals every time around the scheduler). - - Signal Handlers are atomic (i.e. they can't be interrupted), and - we can make use of this. We just need to make sure the - critical section of the scheduler can't be interrupted - the - only way to do this is to block signals. However, we can lower - the overhead by only blocking signals when there are any - handlers to run, i.e. the set of pending handlers is - non-empty. - */ - - /* We use a stack to store the pending signals. We can't - dynamically grow this since we can't allocate any memory from - within a signal handler. - - Hence unfortunately we have to bomb out if the buffer - overflows. It might be acceptable to carry on in certain - circumstances, depending on the signal. - */ - - memcpy(next_pending_handler, info, sizeof(siginfo_t)); - - next_pending_handler++; - - // stack full? - if (next_pending_handler == &pending_handler_buf[N_PENDING_HANDLERS]) { - errorBelch("too many pending signals"); - stg_exit(EXIT_FAILURE); - } - - interruptCapability(&MainCapability); - -#endif /* THREADED_RTS */ -} - -/* ----------------------------------------------------------------------------- - * Blocking/Unblocking of the user signals - * -------------------------------------------------------------------------- */ - -void -blockUserSignals(void) -{ - sigprocmask(SIG_BLOCK, &userSignals, &savedSignals); -} - -void -unblockUserSignals(void) -{ - sigprocmask(SIG_SETMASK, &savedSignals, NULL); -} - -/* ----------------------------------------------------------------------------- - * Install a Haskell signal handler. + * Relevant posix signals facts: * - * We should really do this in Haskell in GHC.Conc, and share the - * signal_handlers array with the one there. + * + Every (OS) thread has a signal mask, which can be manipulated by that + * thread itself (though sigprocmask on macOS breaks this). + * + Signal masks are inherited when new threads or processes are created (or + * can be set as an attribute in posix spawn on some platforms). + * + Most signals are processes directed, while some are thread-directed. + * + Process-directed signals will be delivered to _any_ thread that does not + * have the signal masked. * - * -------------------------------------------------------------------------- */ - -int -stg_sig_install(int sig, int spi, void *mask) -{ - sigset_t signals, osignals; - StgInt previous_spi; - - struct sigaction action; - memset(&action, 0, sizeof(struct sigaction)); - - ACQUIRE_LOCK(&sig_mutex); - - // Block the signal until we figure out what to do - // Count on this to fail if the signal number is invalid - if (sig < 0 || - sigemptyset(&signals) || - sigaddset(&signals, sig) || - sigprocmask(SIG_BLOCK, &signals, &osignals)) { - RELEASE_LOCK(&sig_mutex); - return STG_SIG_ERR; - } - - more_handlers(sig); - - previous_spi = signal_handlers[sig]; - - action.sa_flags = 0; - - switch(spi) { - case STG_SIG_IGN: - action.sa_handler = SIG_IGN; - break; - - case STG_SIG_DFL: - action.sa_handler = SIG_DFL; - break; - - case STG_SIG_RST: - action.sa_flags |= SA_RESETHAND; - /* fall through */ - case STG_SIG_HAN: - action.sa_sigaction = generic_handler; - action.sa_flags |= SA_SIGINFO; - break; - - default: - barf("stg_sig_install: bad spi"); - } - - if (mask != NULL) - action.sa_mask = *(sigset_t *)mask; - else - sigemptyset(&action.sa_mask); - - action.sa_flags |= sig == SIGCHLD && nocldstop ? SA_NOCLDSTOP : 0; - - if (sigaction(sig, &action, NULL)) - { - errorBelch("sigaction"); - RELEASE_LOCK(&sig_mutex); - return STG_SIG_ERR; - } - - signal_handlers[sig] = spi; - - switch(spi) { - case STG_SIG_RST: - case STG_SIG_HAN: - sigaddset(&userSignals, sig); - break; - - default: - sigdelset(&userSignals, sig); - break; - } - - if (sigprocmask(SIG_SETMASK, &osignals, NULL)) - { - errorBelch("sigprocmask"); - RELEASE_LOCK(&sig_mutex); - return STG_SIG_ERR; - } - - RELEASE_LOCK(&sig_mutex); - return previous_spi; -} - -/* ----------------------------------------------------------------------------- - * Creating new threads for signal handlers. - * -------------------------------------------------------------------------- */ - -#if !defined(THREADED_RTS) -void -startPendingSignalHandlers(Capability *cap) -{ - siginfo_t *info; - int sig; - - if (!signals_pending()) return; - - blockUserSignals(); - - while (next_pending_handler != pending_handler_buf) { - - next_pending_handler--; - - sig = next_pending_handler->si_signo; - if (signal_handlers[sig] == STG_SIG_DFL) { - continue; // handler has been changed. - } - - info = stgMallocBytes(sizeof(siginfo_t), "startPendingSignalHandlers"); - // freed by runHandler - memcpy(info, next_pending_handler, sizeof(siginfo_t)); - - debugTrace(DEBUG_iomanager, - "Handling pending signal, no %d", info->si_signo); - - StgTSO *t = - createIOThread(cap, - RtsFlags.GcFlags.initialStkSize, - rts_apply(cap, - rts_apply(cap, - runHandlersPtr_closure, - rts_mkPtr(cap, info)), - rts_mkInt(cap, info->si_signo))); - scheduleThread(cap, t); - setThreadLabel(cap, t, "signal handler thread"); - } - - unblockUserSignals(); -} -#endif - -#else /* !RTS_USER_SIGNALS */ -StgInt -stg_sig_install(StgInt sig STG_UNUSED, - StgInt spi STG_UNUSED, - void* mask STG_UNUSED) -{ - //barf("User signals not supported"); - return STG_SIG_DFL; -} - -#endif + * The important consequence of the "any thread will do" property is that: + * + * + it is generally _effective_ to unmask a signal in a thread, because at + * least the calling thread has the signal unmasked; however + * + it is generally _ineffective_ to mask a signal in a thread, because + * the signal will likely still be unmasked in some other thread and thus + * be delivered there. + * + * Thus we should avoid use the masking signals as a mechanism that we rely on, + * since it will not in general be effective. In best-effort cases where there + * is a reasonable likelyhood that the calling thread is the only thread with + * signals unmasked then it is ok. + * + * Closely related: always avoid sigprocmask, and prefer pthread_sigmask. + * The older function is sigprocmask but it's meaning in multi-threaded + * programs is explicitly unspecified by Posix. On Linux it modifies the + * calling thread's signal mask, but on macOS it modifies the signal mask of + * every thread in the process, leading to chaos. The new function is + * pthread_sigmask which is well defined and operates only on the signal mask + * of the calling thread. + */ -#if defined(RTS_USER_SIGNALS) /* ----------------------------------------------------------------------------- * SIGINT handler. * @@ -504,8 +208,8 @@ set_sigtstp_action (bool handle) void initDefaultHandlers(void) { - // N.B. We can't use initializers here as CentOS's ancient toolchain throws - // spurious warnings. See #23577. + if (!RtsFlags.MiscFlags.install_signal_handlers) return; + struct sigaction action, oact; memset(&oact, 0, sizeof(struct sigaction)); memset(&action, 0, sizeof(struct sigaction)); @@ -569,6 +273,8 @@ initDefaultHandlers(void) void resetDefaultHandlers(void) { + if (!RtsFlags.MiscFlags.install_signal_handlers) return; + struct sigaction action; action.sa_handler = SIG_DFL; ===================================== rts/posix/TTY.c ===================================== @@ -46,14 +46,21 @@ resetTerminalSettings (void) #if HAVE_TERMIOS_H // Reset the terminal settings on the standard file descriptors, // if we changed them. See System.Posix.Internals.tcSetAttr for - // more details, including the reason we temporarily disable + // more details, including the reason we temporarily mask // SIGTTOU here. + // + // This masking best effort only: it will only be effective if the + // calling thread is the only thread left in the process with + // signals unmasked. This should typically be true when this is + // called during shutdown, but there are many ways to make it false. + // + // See Note [pthread_sigmask and the ineffectiveness of masking signals]. { int fd; sigset_t sigset, old_sigset; sigemptyset(&sigset); sigaddset(&sigset, SIGTTOU); - sigprocmask(SIG_BLOCK, &sigset, &old_sigset); + pthread_sigmask(SIG_BLOCK, &sigset, &old_sigset); for (fd = 0; fd <= 2; fd++) { struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd); @@ -61,7 +68,7 @@ resetTerminalSettings (void) tcsetattr(fd,TCSANOW,ts); } } - sigprocmask(SIG_SETMASK, &old_sigset, NULL); + pthread_sigmask(SIG_SETMASK, &old_sigset, NULL); } #endif } ===================================== rts/posix/Ticker.c ===================================== @@ -242,7 +242,7 @@ initTicker (Time interval, TickProc handle_tick) * Create the thread with all blockable signals blocked, leaving signal * handling to the main and/or other threads. This is especially useful in * the non-threaded runtime, where applications might expect sigprocmask(2) - * to effectively block signals. + * or pthread_sigmask(3) to effectively block signals. */ #if defined(HAVE_SIGNAL_H) sigfillset(&mask); ===================================== rts/rts.cabal ===================================== @@ -579,6 +579,7 @@ library c-sources: posix/GetEnv.c posix/GetTime.c posix/Ticker.c + posix/IOManSignals.c posix/OSMem.c posix/OSThreads.c posix/FdWakeup.c ===================================== rts/win32/ConsoleHandler.c ===================================== @@ -54,11 +54,6 @@ initUserSignals(void) return; } -void -freeSignalHandlers(void) { - /* Do nothing */ -} - /* Called in hs_exit to clean up resources. */ void finiUserSignals(void) @@ -115,6 +110,8 @@ static BOOL WINAPI shutdown_handler(DWORD dwCtrlType) */ void initDefaultHandlers(void) { + if (!RtsFlags.MiscFlags.install_signal_handlers) return; + if ( !SetConsoleCtrlHandler(shutdown_handler, true) ) { errorBelch("warning: failed to install default console handler"); } @@ -122,33 +119,25 @@ void initDefaultHandlers(void) void resetDefaultHandlers(void) { + if (!RtsFlags.MiscFlags.install_signal_handlers) return; + if ( !SetConsoleCtrlHandler(shutdown_handler, false) ) { errorBelch("warning: failed to uninstall default console handler"); } } -/* - * Function: blockUserSignals() - * - * Temporarily block the delivery of further console events. Needed to - * avoid race conditions when GCing the stack of outstanding handlers or - * when emptying the stack by running the handlers. - * +/* Temporarily block the delivery of further console events. Needed to + * avoid race conditions when emptying the stack by running the handlers. */ -void -blockUserSignals(void) +static void blockUserSignals(void) { deliver_event = false; } -/* - * Function: unblockUserSignals() - * - * The inverse of blockUserSignals(); re-enable the deliver of console events. +/* The inverse of blockUserSignals(); re-enable the deliver of console events. */ -void -unblockUserSignals(void) +static void unblockUserSignals(void) { deliver_event = true; } ===================================== rts/win32/ConsoleHandler.h ===================================== @@ -19,12 +19,31 @@ * handling code also. */ +/* + * Function: initConsoleEvents() + * + * Initialize the console handling substrate. + */ +void initConsoleEvents(void); + +/* Finalise signal and console events handling. + */ +void finiConsoleEvents(void); + #if !defined(THREADED_RTS) /* * under THREADED_RTS, console events are passed to the IO manager * thread, which starts up the handler. See ThrIOManager.c. */ +/* + * Function: startPendingSignalHandlers() + * + * If there are any queued up win32 console events, run the handlers + * associated with them. + */ +void startPendingSignalHandlers(Capability *cap); + /* * Function: rts_waitConsoleHandlerCompletion() * View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/0d32dcdfed5cc8318c58fb5cf7b19a3... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/0d32dcdfed5cc8318c58fb5cf7b19a3... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
participants (1)
-
Duncan Coutts (@dcoutts)