diff --git a/.github/workflows/test-suite.yml b/.github/workflows/test-suite.yml index 9429b9366b15..653350fe88a8 100644 --- a/.github/workflows/test-suite.yml +++ b/.github/workflows/test-suite.yml @@ -166,6 +166,7 @@ jobs: with: configurationParameters: >- ${{ matrix.asan && 'CFLAGS="-fsanitize=undefined,address -DZEND_TRACK_ARENA_ALLOC" LDFLAGS="-fsanitize=undefined,address"' || '' }} + ${{ matrix.variation && '--disable-zend-signals' || '' }} ${{ matrix.variation && 'CFLAGS="-DZEND_RC_DEBUG=1 -DPROFITABILITY_CHECKS=0 -DZEND_VERIFY_FUNC_INFO=1 -DZEND_VERIFY_TYPE_INFERENCE"' || '' }} ${{ (matrix.variation && fromJson(inputs.branch).jobs.LINUX_X64.config.variation_enable_zend_max_execution_timers) && '--enable-zend-max-execution-timers' || '' }} --${{ matrix.debug && 'enable' || 'disable' }}-debug diff --git a/Zend/zend.c b/Zend/zend.c index 1b1dd9e12e05..abb17bc2eb3e 100644 --- a/Zend/zend.c +++ b/Zend/zend.c @@ -930,6 +930,10 @@ void zend_startup(zend_utility_functions *utility_functions) /* {{{ */ zend_cpu_startup(); +#if defined(ZTS) && !defined(ZEND_WIN32) + zend_signal_forward_startup(); +#endif + #ifdef ZEND_WIN32 php_win32_cp_set_by_id(65001); #endif @@ -1160,6 +1164,10 @@ zend_result zend_post_startup(void) /* {{{ */ void zend_shutdown(void) /* {{{ */ { +#if defined(ZTS) && !defined(ZEND_WIN32) + zend_signal_forward_shutdown(); +#endif + zend_vm_dtor(); zend_destroy_rsrc_list(&EG(persistent_list)); diff --git a/Zend/zend_atomic.h b/Zend/zend_atomic.h index 677d2ed0ccb2..fa35f061f3a5 100644 --- a/Zend/zend_atomic.h +++ b/Zend/zend_atomic.h @@ -35,6 +35,15 @@ #undef ZEND_GCC_PREREQ +/* Whether these atomics are lock-free, and therefore usable in a signal handler. */ +#if (defined(HAVE_C11_ATOMICS) || defined(HAVE_GNUC_ATOMICS)) \ + && __GCC_ATOMIC_INT_LOCK_FREE == 2 && __GCC_ATOMIC_BOOL_LOCK_FREE == 2 +# define ZEND_ATOMIC_SIGNAL_SAFE 1 +#elif defined(HAVE_SYNC_ATOMICS) \ + && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) +# define ZEND_ATOMIC_SIGNAL_SAFE 1 +#endif + /* Treat zend_atomic_* types as opaque. They have definitions only for size * and alignment purposes. */ diff --git a/Zend/zend_execute_API.c b/Zend/zend_execute_API.c index aeb68bdd6be5..e0d36aa1bf24 100644 --- a/Zend/zend_execute_API.c +++ b/Zend/zend_execute_API.c @@ -1475,8 +1475,6 @@ static void zend_timeout_handler(int dummy, siginfo_t *si, void *uc) /* {{{ */ { #ifdef ZTS if (!tsrm_is_managed_thread()) { - fprintf(stderr, "zend_timeout_handler() called in a thread not managed by PHP. The expected signal handler will not be called. This is probably a bug.\n"); - return; } #endif @@ -1500,11 +1498,15 @@ static void zend_timeout_handler(int dummy) /* {{{ */ { # endif #ifdef ZTS - if (!tsrm_is_managed_thread()) { - fprintf(stderr, "zend_timeout_handler() called in a thread not managed by PHP. The expected signal handler will not be called. This is probably a bug.\n"); + /* The timer is process-wide, so its signal may reach a thread that did not arm it. */ + if (!tsrm_is_managed_thread() || tsrm_is_shutdown()) { + zend_signal_forward(dummy); return; } + if (!EG(timeout_seconds) && zend_signal_forward(dummy)) { + return; + } #else if (zend_atomic_bool_load_ex(&EG(timed_out))) { /* Die on hard timeout */ @@ -1576,6 +1578,34 @@ VOID CALLBACK tq_timer_cb(PVOID arg, BOOLEAN timed_out) #define SIGPROF 27 #endif +#if defined(ZTS) && !defined(ZEND_WIN32) && !defined(ZEND_MAX_EXECUTION_TIMERS) && defined(HAVE_SETITIMER) +/* A handler installed with pcntl_signal(), for example, replaces the timeout handler. */ +static bool zend_timeout_handler_is_installed(int signo) +{ +# ifdef ZEND_SIGNALS + return SIGG(handlers)[signo-1].handler == (void *) zend_timeout_handler; +# else + struct sigaction current; + + return sigaction(signo, NULL, ¤t) == 0 && current.sa_handler == zend_timeout_handler; +# endif +} + +/* The process-wide disposition that delivers the signal of the execution timer. */ +static void zend_timeout_timer_action(struct sigaction *act) +{ +# ifdef ZEND_SIGNALS + zend_signal_timer_action(act); +# else + memset(act, 0, sizeof(*act)); + act->sa_handler = zend_timeout_handler; + sigemptyset(&act->sa_mask); + /* Without SA_RESETHAND: a signal forwarded from another thread must still find it. */ + act->sa_flags = SA_ONSTACK | SA_NODEFER; +# endif +} +#endif + static void zend_set_timeout_ex(zend_long seconds, bool reset_signals) /* {{{ */ { #ifdef ZEND_WIN32 @@ -1625,26 +1655,21 @@ static void zend_set_timeout_ex(zend_long seconds, bool reset_signals) /* {{{ */ { struct itimerval t_r; /* timeout requested */ int signo; + int timer; // Prevent EINVAL error if (seconds < 0 || seconds > 999999999) { seconds = 0; } - if(seconds) { - t_r.it_value.tv_sec = seconds; - t_r.it_value.tv_usec = t_r.it_interval.tv_sec = t_r.it_interval.tv_usec = 0; - # if defined(__CYGWIN__) || defined(__PASE__) || (defined(__aarch64__) && defined(__APPLE__)) - // ITIMER_PROF is broken in Apple Silicon system with MacOS >= 14 - // See https://openradar.appspot.com/radar?id=5583058442911744. - setitimer(ITIMER_REAL, &t_r, NULL); - } + // ITIMER_PROF is broken in Apple Silicon system with MacOS >= 14 + // See https://openradar.appspot.com/radar?id=5583058442911744. signo = SIGALRM; + timer = ITIMER_REAL; # else - setitimer(ITIMER_PROF, &t_r, NULL); - } signo = SIGPROF; + timer = ITIMER_PROF; # endif if (reset_signals) { @@ -1655,18 +1680,59 @@ static void zend_set_timeout_ex(zend_long seconds, bool reset_signals) /* {{{ */ # ifdef HAVE_SIGACTION struct sigaction act; +# ifdef ZTS + /* The disposition is process-wide, and another thread may handle this signal. */ + if (!zend_timeout_handler_is_installed(signo)) { + zend_timeout_timer_action(&act); + zend_signal_forward_timer_install(signo, &act); + } +# else act.sa_handler = zend_timeout_handler; sigemptyset(&act.sa_mask); act.sa_flags = SA_ONSTACK | SA_RESETHAND | SA_NODEFER; sigaction(signo, &act, NULL); +# endif # else signal(signo, zend_timeout_handler); # endif /* HAVE_SIGACTION */ sigemptyset(&sigset); sigaddset(&sigset, signo); +# ifdef ZTS + tsrm_sigmask(SIG_UNBLOCK, &sigset, NULL); +# else sigprocmask(SIG_UNBLOCK, &sigset, NULL); +# endif # endif /* ZEND_SIGNALS */ } + +# ifdef ZTS + /* A previous timer must not expire on behalf of the one that is about to start. */ + if (seconds) { + memset(&t_r, 0, sizeof(t_r)); + setitimer(timer, &t_r, NULL); + } + + /* The timer is still running while another thread's handler is installed. */ +# ifdef ZEND_SIGNALS + if (seconds && (zend_timeout_handler_is_installed(signo) || zend_signal_forward_has_handler(signo))) { +# else + if (seconds) { +# endif + struct sigaction timer_action; + + zend_timeout_timer_action(&timer_action); + zend_signal_forward_timer_arm(signo, &timer_action); + } else { + zend_signal_forward_timer_disarm(); + } +# endif + + /* Last, as a signal must find its handler and its owner. */ + if (seconds) { + t_r.it_value.tv_sec = seconds; + t_r.it_value.tv_usec = t_r.it_interval.tv_sec = t_r.it_interval.tv_usec = 0; + setitimer(timer, &t_r, NULL); + } } #endif /* HAVE_SETITIMER */ } @@ -1709,6 +1775,9 @@ void zend_unset_timeout(void) /* {{{ */ setitimer(ITIMER_PROF, &no_timeout, NULL); # endif } +# ifdef ZTS + zend_signal_forward_timer_disarm(); +# endif #endif zend_atomic_bool_store_ex(&EG(timed_out), false); } diff --git a/Zend/zend_signal.c b/Zend/zend_signal.c index 83f8aa0852db..e07ff5295164 100644 --- a/Zend/zend_signal.c +++ b/Zend/zend_signal.c @@ -79,6 +79,17 @@ static const int zend_sigs[] = { TIMEOUT_SIG, SIGHUP, SIGINT, SIGQUIT, SIGTERM, static zend_signal_entry_t global_orig_handlers[NSIG]; static sigset_t global_sigmask; +#ifdef ZTS +/* A handler installed before PHP started keeps receiving the signals delivered + * to threads that never ran PHP. */ +static zend_always_inline bool zend_signal_may_forward(int signo) +{ + return signo < NSIG + && (global_orig_handlers[signo-1].handler == (void *) SIG_DFL + || global_orig_handlers[signo-1].handler == (void *) SIG_IGN); +} +#endif + /* {{{ zend_signal_handler_defer * Blocks signals if in critical section */ static void zend_signal_handler_defer(int signo, siginfo_t *siginfo, void *context) @@ -90,11 +101,23 @@ static void zend_signal_handler_defer(int signo, siginfo_t *siginfo, void *conte /* A signal could hit after TSRM shutdown, in this case globals are already freed. * Or it could be delivered to a thread that didn't execute PHP yet. * In the latter case we act as if SIGG(active) is false. */ - if (tsrm_is_shutdown() || !tsrm_is_managed_thread()) { + if (!tsrm_is_managed_thread() || tsrm_is_shutdown()) { + if (zend_signal_may_forward(signo) && zend_signal_forward(signo)) { + errno = errno_save; + return; + } /* Forward to default handler handler */ zend_signal_handler(signo, siginfo, context); return; } + + /* Another PHP thread may handle a signal that this one does not. */ + if (zend_signal_may_forward(signo) + && (SIGG(handlers)[signo-1].handler == (void *) SIG_DFL || SIGG(handlers)[signo-1].handler == (void *) SIG_IGN) + && zend_signal_forward(signo)) { + errno = errno_save; + return; + } #endif if (EXPECTED(SIGG(active))) { @@ -182,7 +205,10 @@ static void zend_signal_handler(int signo, siginfo_t *siginfo, void *context) sigset_t sigset; zend_signal_entry_t p_sig; #ifdef ZTS - if (tsrm_is_shutdown() || !tsrm_is_managed_thread()) { + /* Only a thread with TSRM storage may use SIGG() */ + bool has_globals = tsrm_is_managed_thread() && !tsrm_is_shutdown(); + + if (!has_globals) { p_sig = global_orig_handlers[signo-1]; } else #endif @@ -199,20 +225,17 @@ static void zend_signal_handler(int signo, siginfo_t *siginfo, void *context) if (sigaction(signo, &sa, NULL) == 0) { /* throw away any blocked signals */ zend_sigprocmask(SIG_UNBLOCK, &sigset, NULL); -#ifdef ZTS -# define RAISE_ERROR "raise() failed\n" - if (raise(signo) != 0) { - /* On some systems raise() fails with errno 3: No such process */ - kill(getpid(), signo); - } -#else + /* Not raise(), which is pthread_kill() on macOS and not safe in a handler there */ kill(getpid(), signo); -#endif } } } else if (p_sig.handler != SIG_IGN) { if (p_sig.flags & SA_SIGINFO) { +#ifdef ZTS + if ((p_sig.flags & SA_RESETHAND) && has_globals) { +#else if (p_sig.flags & SA_RESETHAND) { +#endif SIGG(handlers)[signo-1].flags = 0; SIGG(handlers)[signo-1].handler = SIG_DFL; } @@ -238,15 +261,11 @@ ZEND_API void zend_sigaction(int signo, const struct sigaction *act, struct siga oldact->sa_mask = global_sigmask; } if (act != NULL) { - SIGG(handlers)[signo-1].flags = act->sa_flags; - if (act->sa_flags & SA_SIGINFO) { - SIGG(handlers)[signo-1].handler = (void *) act->sa_sigaction; - } else { - SIGG(handlers)[signo-1].handler = (void *) act->sa_handler; - } + void *handler = (act->sa_flags & SA_SIGINFO) ? (void *) act->sa_sigaction : (void *) act->sa_handler; + int sigaction_result; memset(&sa, 0, sizeof(sa)); - if (SIGG(handlers)[signo-1].handler == (void *) SIG_IGN) { + if (handler == (void *) SIG_IGN) { sa.sa_sigaction = (void *) SIG_IGN; } else { sa.sa_flags = SA_ONSTACK | SA_SIGINFO | (act->sa_flags & SA_FLAGS_MASK); @@ -254,7 +273,22 @@ ZEND_API void zend_sigaction(int signo, const struct sigaction *act, struct siga sa.sa_mask = global_sigmask; } - if (sigaction(signo, &sa, NULL) < 0) { +#ifdef ZTS + /* While the handler is still there: a signal forwarded here afterwards + * would take the default action. */ + if (handler == (void *) SIG_DFL || handler == (void *) SIG_IGN) { + sigaction_result = zend_signal_forward_release(signo, &sa); + SIGG(handlers)[signo-1].flags = act->sa_flags; + SIGG(handlers)[signo-1].handler = handler; + } else +#endif + { + SIGG(handlers)[signo-1].flags = act->sa_flags; + SIGG(handlers)[signo-1].handler = handler; + sigaction_result = sigaction(signo, &sa, NULL); + } + + if (sigaction_result < 0) { zend_error_noreturn(E_ERROR, "Error installing signal handler for %d", signo); } @@ -266,6 +300,17 @@ ZEND_API void zend_sigaction(int signo, const struct sigaction *act, struct siga } /* }}} */ +#ifdef ZTS +/* The process-wide disposition of a signal that zend_signal() handles for a thread. */ +void zend_signal_timer_action(struct sigaction *act) +{ + memset(act, 0, sizeof(*act)); + act->sa_flags = SA_ONSTACK | SA_SIGINFO; + act->sa_sigaction = zend_signal_handler_defer; + act->sa_mask = global_sigmask; +} +#endif + /* {{{ zend_signal * Register a signal handler that will be deferred in critical sections */ ZEND_API void zend_signal(int signo, void (*handler)(int)) @@ -393,9 +438,13 @@ void zend_signal_init(void) /* {{{ */ struct sigaction sa; /* Save previously registered signal handlers into orig_handlers */ - memset(&global_orig_handlers, 0, sizeof(global_orig_handlers)); for (signo = 1; signo < NSIG; ++signo) { if (sigaction(signo, NULL, &sa) == 0) { + /* Left installed by an earlier startup in this process, which already + * saved the original handler. */ + if ((sa.sa_flags & SA_SIGINFO) && sa.sa_sigaction == zend_signal_handler_defer) { + continue; + } global_orig_handlers[signo-1].flags = sa.sa_flags; if (sa.sa_flags & SA_SIGINFO) { global_orig_handlers[signo-1].handler = (void *) sa.sa_sigaction; diff --git a/Zend/zend_signal.h b/Zend/zend_signal.h index e88892da35aa..bf7016b3dd21 100644 --- a/Zend/zend_signal.h +++ b/Zend/zend_signal.h @@ -21,6 +21,8 @@ #ifndef ZEND_SIGNAL_H #define ZEND_SIGNAL_H +#include "zend_signal_forward.h" + #ifdef ZEND_SIGNALS #include @@ -94,6 +96,9 @@ END_EXTERN_C() void zend_signal_init(void); ZEND_API void zend_signal(int signo, void (*handler)(int)); +#ifdef ZTS +void zend_signal_timer_action(struct sigaction *act); +#endif ZEND_API void zend_sigaction(int signo, const struct sigaction *act, struct sigaction *oldact); #else /* ZEND_SIGNALS */ diff --git a/Zend/zend_signal_forward.c b/Zend/zend_signal_forward.c new file mode 100644 index 000000000000..4127ca993b8f --- /dev/null +++ b/Zend/zend_signal_forward.c @@ -0,0 +1,1302 @@ +/* + +----------------------------------------------------------------------+ + | Zend Signal Forwarding | + +----------------------------------------------------------------------+ + | Copyright (c) The PHP Group | + +----------------------------------------------------------------------+ + | This source file is subject to version 3.01 of the PHP license, | + | that is bundled with this package in the file LICENSE, and is | + | available through the world-wide-web at the following url: | + | https://www.php.net/license/3_01.txt | + | If you did not receive a copy of the PHP license and are unable to | + | obtain it through the world-wide-web, please send a note to | + | license@php.net so we can mail you a copy immediately. | + +----------------------------------------------------------------------+ +*/ + +/* A process-directed signal may be delivered to any thread that does not block + * it, including one that has no TSRM storage and cannot run PHP's handlers. Such + * a signal is forwarded to the thread that owns it. + * + * Owner: the thread that most recently registered a handler for the signal, or + * otherwise the thread that most recently armed the execution timer delivering it. + * + * Signal handlers must not call pthread_kill(): POSIX allows it, but on macOS it + * takes a libpthread lock that the interrupted thread may already hold, which aborts + * the process. A helper thread reads a pipe and sends the signal instead. It runs from + * the first registration that needs it until shutdown. + * + * Invariants: + * + * 1. Handlers only use lock-free atomics and async-signal-safe functions, take no + * lock, do not allocate, and preserve errno. + * 2. A handler publishes the pending flag before it writes to the pipe. + * 3. A nonzero flag means that a handler is about to write, that a byte is unread, + * or that the helper has yet to scan that flag. Only the handler that sets a flag + * from zero writes, so that a flag cannot wait for a wakeup that nobody will send. + * 4. EAGAIN is a wakeup: the pipe was full after the flag was published, so a read and + * a scan are still to come. Any other write error clears the flag again, and so does + * a handler that finds the helper gone after it published the flag: the helper clears + * the pid before its final scan, so either that scan or the handler sees the flag. + * 5. The helper scans every flag when it starts, after every successful read, and before + * it exits because a read failed. + * 6. A flag coalesces the signals that arrive between two scans into one delivery. It + * keeps neither their number nor their siginfo: a forwarded signal has the siginfo + * of the pthread_kill(), so si_pid, si_uid, si_code and any payload are lost. + * 7. pthread_kill() only runs on the helper with the mutex held, and a record leaves + * the list under that mutex before its thread exits, so that a signal never targets + * an exited thread. On Linux, the signal is sent with tgkill(): pthread_kill() takes + * a lock in the target's descriptor, and a target that forks at that moment leaves + * the lock held forever in its child, where the next forward would hang. + * 8. The pipe stays open as long as this process may write to it. After a failed read, + * the helper starts a new one with a new pipe. The old descriptors are left alone: + * their numbers may already belong to something else. + * 9. A forked child never reads the inherited list or mutex, which another thread may + * have been updating. It only keeps the record of the calling thread. + * 10. zend_signal_forward_pid is only set while this process can notify a helper. + * 11. zend_signal_forward_shutdown() requires that no other thread runs PHP. + * 12. The mutex is the only lock. Handlers never take it, and the helper only sends + * signals while it holds it, so that no lock order can deadlock. + * 13. Registrations, and the dispositions that this component decides on, only change + * under the mutex. A timer records itself and settles the disposition in one critical + * section, so that a handler cannot be registered or released between the two. + * 14. A thread that started to exit cannot register again, so that no record outlives it. + * This takes a registration from before the thread exits: one that a destructor of + * another key makes first, on the last pass over the destructors, is not supported. + * + * Memory ordering: every atomic operation is sequentially consistent, with each backend + * of zend_atomic.h. Invariant 4 depends on it. A handler stores the flag and then loads + * the pid, and a helper that exits stores the pid and then loads the flag: with a weaker + * order, both could miss the other's store. + * + * Platform assumption: POSIX does not list pthread_getspecific() as async-signal-safe, but + * nothing portable tells a handler whether its thread has TSRM storage, and + * zend_signal_handler_defer() has always relied on it. In glibc, musl, the macOS libpthread + * and the FreeBSD libthr, it reads the storage of the calling thread without taking a lock + * or allocating. Forwarding is compiled out on other systems. + * + * POSIX constraints: a handler may only call async-signal-safe functions, which excludes + * mutexes and malloc(). After fork(), only the calling thread exists and every lock that + * another thread held stays locked, including the one pthread_kill() takes in the thread + * descriptor. pthread_atfork() cannot help: taking the mutex there deadlocks against a + * thread that was interrupted inside malloc(). */ + +#include "zend.h" + +#if defined(ZTS) && !defined(ZEND_WIN32) + +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef __linux__ +# include +#endif + +#include "zend_atomic.h" + +#ifndef NSIG +# define NSIG 65 +#endif + +/* How long the signal of a timer that was just disarmed may still arrive. */ +#define ZEND_SIGNAL_FORWARD_TIMER_GRACE 2 + +typedef struct _zend_signal_forward_thread { + pthread_t thread; +#ifdef SYS_tgkill + pid_t tid; +#endif + pid_t process; + uint64_t handler[NSIG]; /* Registration order, 0 without a handler */ + bool ignored[NSIG]; + bool installed[NSIG]; /* The handler was installed through this component */ + bool active; + int timer_signo; + uint64_t timer_order; + bool has_timer_action; + struct sigaction timer_action; + struct _zend_signal_forward_thread *prev; + struct _zend_signal_forward_thread *next; +} zend_signal_forward_thread; + +/* The state of each process, which a forked child abandons instead of reusing. */ +typedef struct _zend_signal_forward_abandoned { + pthread_mutex_t mutex; + int process; + zend_signal_forward_thread *inherited_threads; + struct _zend_signal_forward_abandoned *previous; +} zend_signal_forward_abandoned; + +/* Protected by the mutex, except for what the calling thread reads of its own record */ +static zend_signal_forward_abandoned *zend_signal_forward_lock_state; +static pthread_mutex_t *zend_signal_forward_mutex; +static zend_signal_forward_thread *zend_signal_forward_threads; +static uint64_t zend_signal_forward_order; +static pthread_t zend_signal_forward_helper; +static bool zend_signal_forward_helper_running; +static bool zend_signal_forward_helper_stop; +static bool zend_signal_forward_shutting_down; +static bool zend_signal_forward_shared_fds; + +static pthread_key_t zend_signal_forward_key; +/* The thread has started to exit. A key that keeps a value would make the system run the + * destructors again, and FreeBSD reports every thread that still has one afterwards. */ +static TSRM_TLS bool zend_signal_forward_exiting; +static int zend_signal_forward_pipe[2] = {-1, -1}; +/* In a forked child: the handler of a thread that does not exist there. */ +static void (*zend_signal_forward_orphaned[NSIG])(int); +static pid_t zend_signal_forward_pipe_process; +static zend_atomic_bool zend_signal_forward_started; +static zend_atomic_int zend_signal_forward_process; +static zend_atomic_int zend_signal_forward_init_lock; + +/* Read by signal handlers */ +static zend_atomic_int zend_signal_forward_pid; +static zend_atomic_int zend_signal_forward_fd; +static zend_atomic_int zend_signal_forward_targets[NSIG]; +static zend_atomic_int zend_signal_forward_handlers[NSIG]; +static zend_atomic_int zend_signal_forward_ignoring[NSIG]; +static zend_atomic_int zend_signal_forward_pending[NSIG]; +static zend_atomic_int zend_signal_forward_generation[NSIG]; +static zend_atomic_int zend_signal_forward_disarmed_at[NSIG]; + +#if ZEND_DEBUG +static zend_atomic_bool zend_signal_forward_test_hold; +static zend_atomic_bool zend_signal_forward_test_held; +static zend_atomic_bool zend_signal_forward_test_fail_read; +static zend_atomic_bool zend_signal_forward_test_eagain; +static zend_atomic_bool zend_signal_forward_test_stall; +static zend_atomic_bool zend_signal_forward_test_stalled; +static zend_atomic_bool zend_signal_forward_test_resume; +static zend_atomic_bool zend_signal_forward_test_fail_pipe; +static zend_atomic_bool zend_signal_forward_test_fail_create; +static zend_atomic_bool zend_signal_forward_test_fail_init; +#endif + +static zend_always_inline zend_signal_forward_thread *zend_signal_forward_current(void) +{ + return zend_signal_forward_exiting ? NULL : pthread_getspecific(zend_signal_forward_key); +} + +static zend_always_inline bool zend_signal_forward_is_trackable(int signo) +{ + /* A fault must stay on the faulting thread: the instruction would run again as + * soon as the handler returned. Signals from NSIG up are not tracked. */ + return signo >= 1 && signo < NSIG + && signo != SIGSEGV && signo != SIGFPE && signo != SIGILL +#ifdef SIGBUS + && signo != SIGBUS +#endif +#ifdef SIGTRAP + && signo != SIGTRAP +#endif + ; +} + +/* Wraps around with the clock, which does not fit an int after 2038. */ +static zend_always_inline bool zend_signal_forward_recently_disarmed(int signo) +{ + int disarmed_at = zend_atomic_int_load_ex(&zend_signal_forward_disarmed_at[signo-1]); + + /* Signed, as the clock may have been set back since. */ + return disarmed_at != 0 && (int) ((unsigned int) time(NULL) - (unsigned int) disarmed_at) <= ZEND_SIGNAL_FORWARD_TIMER_GRACE; +} + +static void zend_signal_forward_update(int signo) +{ + int targets = 0, handlers = 0, ignoring = 0; + + for (zend_signal_forward_thread *thread = zend_signal_forward_threads; thread; thread = thread->next) { + targets += thread->handler[signo-1] || thread->timer_signo == signo; + handlers += thread->handler[signo-1] != 0; + ignoring += thread->ignored[signo-1]; + } + /* In this order, so that a handler never sees a signal as unhandled in between. */ + zend_atomic_int_store_ex(&zend_signal_forward_ignoring[signo-1], ignoring); + zend_atomic_int_store_ex(&zend_signal_forward_handlers[signo-1], handlers); + zend_atomic_int_store_ex(&zend_signal_forward_targets[signo-1], targets); +} + +/* The timer is process-wide, so the most recent one is the one that runs. */ +static zend_signal_forward_thread *zend_signal_forward_timer_owner(int signo) +{ + zend_signal_forward_thread *timer = NULL; + + for (zend_signal_forward_thread *thread = zend_signal_forward_threads; thread; thread = thread->next) { + if (thread->timer_signo == signo && (!timer || thread->timer_order > timer->timer_order)) { + timer = thread; + } + } + return timer; +} + +static zend_signal_forward_thread *zend_signal_forward_owner(int signo, bool *is_timer) +{ + zend_signal_forward_thread *owner = NULL; + + for (zend_signal_forward_thread *thread = zend_signal_forward_threads; thread; thread = thread->next) { + if (thread->handler[signo-1] && (!owner || thread->handler[signo-1] > owner->handler[signo-1])) { + owner = thread; + } + } + *is_timer = !owner; + return owner ? owner : zend_signal_forward_timer_owner(signo); +} + +static void zend_signal_forward_next_generation(int signo) +{ + int generation = zend_atomic_int_load_ex(&zend_signal_forward_generation[signo-1]); + + zend_atomic_int_store_ex(&zend_signal_forward_generation[signo-1], generation >= INT_MAX - 1 ? 0 : generation + 1); +} + +static zend_always_inline void zend_signal_forward_identify(zend_signal_forward_thread *thread) +{ + thread->thread = pthread_self(); +#ifdef SYS_tgkill + thread->tid = (pid_t) syscall(SYS_gettid); +#endif +} + +static zend_always_inline void zend_signal_forward_kill(const zend_signal_forward_thread *thread, int signo) +{ +#ifdef SYS_tgkill + syscall(SYS_tgkill, getpid(), thread->tid, signo); +#else + pthread_kill(thread->thread, signo); +#endif +} + +static void zend_signal_forward_deliver(int signo, int pending) +{ + bool is_timer; + zend_signal_forward_thread *owner = zend_signal_forward_owner(signo, &is_timer); + + if (owner) { + /* A timer that was re-armed meanwhile did not expire. */ + if (!is_timer || pending == zend_atomic_int_load_ex(&zend_signal_forward_generation[signo-1]) + 1) { + zend_signal_forward_kill(owner, signo); + } + } else if (zend_atomic_int_load_ex(&zend_signal_forward_ignoring[signo-1]) == 0 + && pending == zend_atomic_int_load_ex(&zend_signal_forward_generation[signo-1]) + 1 + && !zend_signal_forward_recently_disarmed(signo)) { + /* The owner left meanwhile: the signal now takes its current action. A timer + * that was disarmed since the signal was raised has a new generation. */ + kill(getpid(), signo); + } +} + +static void zend_signal_forward_scan(void) +{ + for (int signo = 1; signo < NSIG; signo++) { + int pending = zend_atomic_int_exchange_ex(&zend_signal_forward_pending[signo-1], 0); + + if (pending) { + zend_signal_forward_deliver(signo, pending); + } + } +} + +static void zend_signal_forward_helper_start(void); + +static void *zend_signal_forward_helper_main(void *arg) +{ + char buffer[64]; + + while (1) { + int fd; + ssize_t bytes; + + pthread_mutex_lock(zend_signal_forward_mutex); + if (zend_signal_forward_helper_stop) { + pthread_mutex_unlock(zend_signal_forward_mutex); + return NULL; + } + zend_signal_forward_scan(); + fd = zend_signal_forward_pipe[0]; + pthread_mutex_unlock(zend_signal_forward_mutex); + + bytes = read(fd, buffer, sizeof(buffer)); +#if ZEND_DEBUG + if (zend_atomic_bool_load_ex(&zend_signal_forward_test_hold)) { + zend_atomic_bool_store_ex(&zend_signal_forward_test_held, true); + while (zend_atomic_bool_load_ex(&zend_signal_forward_test_hold)) { + usleep(1000); + } + zend_atomic_bool_store_ex(&zend_signal_forward_test_held, false); + } + if (zend_atomic_bool_exchange_ex(&zend_signal_forward_test_fail_read, false)) { + bytes = 0; + } +#endif + if (bytes > 0 || (bytes < 0 && errno == EINTR)) { + continue; + } + + /* The pipe is unusable, and the read may have consumed a notification. */ + pthread_mutex_lock(zend_signal_forward_mutex); + if (!zend_signal_forward_helper_stop) { + zend_atomic_int_store_ex(&zend_signal_forward_pid, 0); + zend_signal_forward_scan(); + zend_signal_forward_pipe[0] = zend_signal_forward_pipe[1] = -1; + zend_signal_forward_helper_running = false; + pthread_detach(pthread_self()); + /* The registrations that exist still need a helper. */ + zend_signal_forward_helper_start(); + } + pthread_mutex_unlock(zend_signal_forward_mutex); + return NULL; + } +} + +static bool zend_signal_forward_open_pipe(void) +{ + int fds[2]; + int flags; + + if (zend_signal_forward_pipe[0] != -1) { + return true; + } +#if ZEND_DEBUG + if (zend_atomic_bool_exchange_ex(&zend_signal_forward_test_fail_pipe, false)) { + return false; + } +#endif + if (pipe(fds) != 0) { + return false; + } + + /* With a standard stream closed, its number must not end up on the pipe. */ + for (int i = 0; i < 2; i++) { + if (fds[i] < 3) { + int fd = fcntl(fds[i], F_DUPFD, 3); + + close(fds[i]); + fds[i] = fd; + } + } + + /* A full pipe already guarantees that the helper will wake up. */ + flags = fds[1] == -1 ? -1 : fcntl(fds[1], F_GETFL); + if (fds[0] == -1 || flags == -1 || fcntl(fds[1], F_SETFL, flags | O_NONBLOCK) == -1 + || fcntl(fds[0], F_SETFD, FD_CLOEXEC) == -1 || fcntl(fds[1], F_SETFD, FD_CLOEXEC) == -1) { + if (fds[0] != -1) { + close(fds[0]); + } + if (fds[1] != -1) { + close(fds[1]); + } + return false; + } + + zend_signal_forward_pipe[0] = fds[0]; + zend_signal_forward_pipe[1] = fds[1]; + zend_signal_forward_pipe_process = getpid(); + return true; +} + +static void zend_signal_forward_helper_start(void) +{ + sigset_t all, old; + bool created; + + /* A pipe opened in a table shared with the parent would outlive this process. */ + if (zend_signal_forward_helper_running || zend_signal_forward_shared_fds || zend_signal_forward_shutting_down + || !zend_signal_forward_open_pipe()) { + return; + } + + zend_atomic_int_store_ex(&zend_signal_forward_fd, zend_signal_forward_pipe[1]); + zend_atomic_int_store_ex(&zend_signal_forward_pid, (int) getpid()); + + /* The helper inherits this mask, so that it never takes a signal for another thread: + * it would reach its handler late, and after signals that were sent later. */ + sigfillset(&all); + pthread_sigmask(SIG_BLOCK, &all, &old); + zend_signal_forward_helper_stop = false; +#if ZEND_DEBUG + if (zend_atomic_bool_exchange_ex(&zend_signal_forward_test_fail_create, false)) { + created = false; + } else +#endif + created = pthread_create(&zend_signal_forward_helper, NULL, zend_signal_forward_helper_main, NULL) == 0; + pthread_sigmask(SIG_SETMASK, &old, NULL); + + if (!created) { + zend_atomic_int_store_ex(&zend_signal_forward_pid, 0); + zend_signal_forward_scan(); + return; + } + zend_signal_forward_helper_running = true; +} + +static void zend_signal_forward_helper_start_if_needed(void) +{ + for (int signo = 1; signo < NSIG; signo++) { + if (zend_atomic_int_load_ex(&zend_signal_forward_targets[signo-1]) > 0) { + zend_signal_forward_helper_start(); + break; + } + } +} + +/* A helper that cannot be woken up is left behind: it never touches anything again. */ +static void zend_signal_forward_helper_join(void) +{ + ssize_t written; + + do { + written = write(zend_signal_forward_pipe[1], "", 1); + } while (written < 0 && errno == EINTR); + + if (written < 0 && errno != EAGAIN && errno != EWOULDBLOCK) { + pthread_detach(zend_signal_forward_helper); + zend_signal_forward_pipe[0] = zend_signal_forward_pipe[1] = -1; + } else { + pthread_join(zend_signal_forward_helper, NULL); + } +} + +/* Runs on first use in each process. In the child of a fork(), only the forking thread + * exists, but this may run on another thread, so the records are kept reachable. */ +static void zend_signal_forward_init(int process) +{ + zend_signal_forward_thread *self = zend_signal_forward_current(); + + zend_atomic_int_store_ex(&zend_signal_forward_pid, 0); + +#if ZEND_DEBUG + zend_atomic_bool_store_ex(&zend_signal_forward_test_hold, false); + zend_atomic_bool_store_ex(&zend_signal_forward_test_held, false); +#endif + + /* PHP may also start again in the same process. */ + if (!zend_signal_forward_lock_state || zend_signal_forward_lock_state->process != process) { + zend_signal_forward_abandoned *state = malloc(sizeof(zend_signal_forward_abandoned)); + bool failed = !state; + +#if ZEND_DEBUG + failed = zend_atomic_bool_exchange_ex(&zend_signal_forward_test_fail_init, false) || failed; +#endif + if (failed || pthread_mutex_init(&state->mutex, NULL) != 0) { + free(state); + zend_atomic_bool_store_ex(&zend_signal_forward_started, false); + return; + } + state->process = process; + state->inherited_threads = NULL; + state->previous = zend_signal_forward_lock_state; + zend_signal_forward_lock_state = state; + zend_signal_forward_mutex = &state->mutex; + } + + /* Kept reachable, but never read: another thread may have been updating it. */ + zend_signal_forward_lock_state->inherited_threads = zend_signal_forward_threads; + if (self) { + /* The inherited record stays as it is, in the list that was kept reachable. */ + zend_signal_forward_thread *copy = malloc(sizeof(zend_signal_forward_thread)); + + if (copy && pthread_setspecific(zend_signal_forward_key, copy) == 0) { + *copy = *self; + self = copy; + } else { + free(copy); + } + } + zend_signal_forward_threads = self; + if (self) { + self->prev = self->next = NULL; + self->process = process; + zend_signal_forward_identify(self); + /* Timers are not inherited by a child. */ + self->timer_signo = 0; + self->has_timer_action = false; + } + + /* A child must not share the pipe of its parent. Otherwise the pipe stays open + * for the lifetime of the process, as a signal handler may be writing to it. */ + if (zend_signal_forward_pipe[0] != -1 && zend_signal_forward_pipe_process != process) { + close(zend_signal_forward_pipe[0]); + close(zend_signal_forward_pipe[1]); + zend_signal_forward_pipe[0] = zend_signal_forward_pipe[1] = -1; + } + zend_signal_forward_helper_running = false; + zend_signal_forward_shutting_down = false; + + for (int signo = 1; signo < NSIG; signo++) { + bool handled = zend_atomic_int_load_ex(&zend_signal_forward_handlers[signo-1]) > 0; + + zend_atomic_int_store_ex(&zend_signal_forward_pending[signo-1], 0); + zend_atomic_int_store_ex(&zend_signal_forward_disarmed_at[signo-1], 0); + zend_signal_forward_update(signo); + if (handled && zend_atomic_int_load_ex(&zend_signal_forward_handlers[signo-1]) == 0) { + struct sigaction inherited; + + if (sigaction(signo, NULL, &inherited) == 0) { + zend_signal_forward_orphaned[signo-1] = inherited.sa_handler; + } + } + } + + zend_atomic_int_store_ex(&zend_signal_forward_process, process); +} + +static bool zend_signal_forward_lock(void) +{ + int process; + + if (!zend_atomic_bool_load_ex(&zend_signal_forward_started)) { + return false; + } + + process = (int) getpid(); + if (UNEXPECTED(zend_atomic_int_load_ex(&zend_signal_forward_process) != process)) { + int holder = 0; + + /* A holder from another process does not exist in this one. */ + while (!zend_atomic_int_compare_exchange_ex(&zend_signal_forward_init_lock, &holder, process)) { + if (holder != process && zend_atomic_int_compare_exchange_ex(&zend_signal_forward_init_lock, &holder, process)) { + break; + } + holder = 0; + } + if (zend_atomic_int_load_ex(&zend_signal_forward_process) != process) { + zend_signal_forward_init(process); + } + zend_atomic_int_store_ex(&zend_signal_forward_init_lock, 0); + + if (!zend_atomic_bool_load_ex(&zend_signal_forward_started)) { + return false; + } + } + + pthread_mutex_lock(zend_signal_forward_mutex); + if (!zend_atomic_bool_load_ex(&zend_signal_forward_started)) { + pthread_mutex_unlock(zend_signal_forward_mutex); + return false; + } + return true; +} + +static zend_always_inline void zend_signal_forward_unlock(void) +{ + pthread_mutex_unlock(zend_signal_forward_mutex); +} + +/* A signal already sent to this thread is delivered when a system call returns, + * while the handler that it expects is still there. */ +static zend_always_inline void zend_signal_forward_flush(void) +{ + sigset_t pending; + + sigpending(&pending); +} + +static zend_signal_forward_thread *zend_signal_forward_self(void) +{ + zend_signal_forward_thread *self = pthread_getspecific(zend_signal_forward_key); + pid_t process = getpid(); + + if (zend_signal_forward_exiting) { + return NULL; + } + + if (self && self->process == process) { + return self; + } + + if (self) { + /* Left behind by a fork() that another thread of the child noticed first. */ + memset(self, 0, sizeof(*self)); + } else { + self = calloc(1, sizeof(zend_signal_forward_thread)); + if (!self) { + return NULL; + } + /* Without the key, nothing would remove the record when this thread exits. */ + if (pthread_setspecific(zend_signal_forward_key, self) != 0) { + free(self); + return NULL; + } + } + + zend_signal_forward_identify(self); + self->process = process; + self->next = zend_signal_forward_threads; + if (self->next) { + self->next->prev = self; + } + zend_signal_forward_threads = self; + return self; +} + +static void zend_signal_forward_disarm_self(zend_signal_forward_thread *self) +{ + int signo = self->timer_signo; + + if (signo) { + self->timer_signo = 0; + self->has_timer_action = false; + zend_atomic_int_store_ex(&zend_signal_forward_disarmed_at[signo-1], (int) time(NULL)); + zend_signal_forward_next_generation(signo); + zend_signal_forward_update(signo); + } +} + +static bool zend_signal_forward_clear_self(zend_signal_forward_thread *self) +{ + bool cleared = false; + + for (int signo = 1; signo < NSIG; signo++) { + if (self->handler[signo-1] || self->ignored[signo-1]) { + self->handler[signo-1] = 0; + self->installed[signo-1] = false; + self->ignored[signo-1] = false; + zend_signal_forward_update(signo); + cleared = true; + } + } + if (self->timer_signo) { + zend_signal_forward_disarm_self(self); + cleared = true; + } + self->active = false; + return cleared; +} + +/* The disposition is process-wide, so it follows what the remaining threads need. */ +static int zend_signal_forward_apply(int signo, const struct sigaction *act) +{ + struct sigaction ignore; + const struct sigaction *timer_action = NULL; + bool timer = false; + + for (zend_signal_forward_thread *thread = zend_signal_forward_threads; thread; thread = thread->next) { + if (thread->handler[signo-1]) { + return 0; + } + if (thread->timer_signo == signo) { + timer = true; + if (thread->has_timer_action) { + timer_action = &thread->timer_action; + } + } + } + + if (timer_action) { + return sigaction(signo, timer_action, NULL); + } + if (timer && act->sa_handler == SIG_IGN) { + /* With zend signals, the armed timer needs signals to keep being delivered. */ + return 0; + } + + if (!timer && zend_atomic_int_load_ex(&zend_signal_forward_ignoring[signo-1]) > 0) { + memset(&ignore, 0, sizeof(ignore)); + ignore.sa_handler = SIG_IGN; + sigemptyset(&ignore.sa_mask); + return sigaction(signo, &ignore, NULL); + } + + return sigaction(signo, act, NULL); +} + +static void zend_signal_forward_thread_exit(void *data) +{ + zend_signal_forward_thread *self = data; + zend_signal_forward_thread *thread; + sigset_t handled, installed, pending, blocked; +#ifdef HAVE_SETITIMER + int timer_signo; +#endif + + /* Destructors of other keys still run, and must not register this thread again. */ + zend_signal_forward_exiting = true; + + if (!zend_signal_forward_lock()) { + return; + } + + /* The record is left behind if this process was forked meanwhile. */ + for (thread = zend_signal_forward_threads; thread && thread != self; thread = thread->next); + if (!thread) { + zend_signal_forward_unlock(); + return; + } + + sigemptyset(&handled); + sigemptyset(&installed); + for (int signo = 1; signo < NSIG; signo++) { + if (self->handler[signo-1]) { + sigaddset(&handled, signo); + if (self->installed[signo-1]) { + sigaddset(&installed, signo); + } + } + } + +#ifdef HAVE_SETITIMER + /* Nothing else would stop the timer of a thread that exits during a request. */ + timer_signo = self->timer_signo; + if ((timer_signo == SIGALRM || timer_signo == SIGPROF) && zend_signal_forward_timer_owner(timer_signo) == self) { + bool timer_in_use = false; + + for (thread = zend_signal_forward_threads; thread; thread = thread->next) { + timer_in_use = timer_in_use || (thread != self && thread->timer_signo == timer_signo); + } + if (!timer_in_use) { + struct itimerval no_timeout; + + memset(&no_timeout, 0, sizeof(no_timeout)); + setitimer(timer_signo == SIGALRM ? ITIMER_REAL : ITIMER_PROF, &no_timeout, NULL); + } + } +#endif + + zend_signal_forward_clear_self(self); + if (self->prev) { + self->prev->next = self->next; + } else { + zend_signal_forward_threads = self->next; + } + if (self->next) { + self->next->prev = self->prev; + } + free(self); + + /* While the current disposition is still in place. */ + zend_signal_forward_flush(); + + /* A handler installed for this thread must not outlive it. */ + for (int signo = 1; signo < NSIG; signo++) { + if (sigismember(&installed, signo) == 1) { + struct sigaction default_action; + + memset(&default_action, 0, sizeof(default_action)); + default_action.sa_handler = SIG_DFL; + sigemptyset(&default_action.sa_mask); + zend_signal_forward_apply(signo, &default_action); + } + } + + zend_signal_forward_unlock(); + + /* A signal that this thread blocks would be lost with it. */ + sigpending(&pending); + pthread_sigmask(SIG_BLOCK, NULL, &blocked); + for (int signo = 1; signo < NSIG; signo++) { + if (sigismember(&handled, signo) == 1 && sigismember(&pending, signo) == 1 && sigismember(&blocked, signo) == 1) { + kill(getpid(), signo); + } + } +} + +void zend_signal_forward_startup(void) +{ +#ifndef ZEND_SIGNAL_FORWARD_ENABLED + return; +#endif + if (pthread_key_create(&zend_signal_forward_key, zend_signal_forward_thread_exit) != 0) { + return; + } + zend_atomic_int_store_ex(&zend_signal_forward_process, 0); + zend_signal_forward_shutting_down = false; + zend_atomic_bool_store_ex(&zend_signal_forward_started, true); +} + +void zend_signal_forward_shutdown(void) +{ + zend_signal_forward_thread *thread; + + if (!zend_atomic_bool_load_ex(&zend_signal_forward_started)) { + return; + } + + zend_atomic_int_store_ex(&zend_signal_forward_pid, 0); + + /* The helper goes first: a thread that exits from now on may leave its record behind. */ + if (zend_atomic_int_load_ex(&zend_signal_forward_process) == (int) getpid()) { + bool helper_running; + + pthread_mutex_lock(zend_signal_forward_mutex); + zend_signal_forward_helper_stop = true; + zend_signal_forward_shutting_down = true; + zend_atomic_int_store_ex(&zend_signal_forward_pid, 0); + helper_running = zend_signal_forward_helper_running; + pthread_mutex_unlock(zend_signal_forward_mutex); + + if (helper_running) { + zend_signal_forward_helper_join(); + zend_signal_forward_helper_running = false; + } + } + + zend_atomic_bool_store_ex(&zend_signal_forward_started, false); + + if (zend_atomic_int_load_ex(&zend_signal_forward_process) == (int) getpid()) { + pthread_mutex_lock(zend_signal_forward_mutex); + thread = zend_signal_forward_threads; + while (thread) { + zend_signal_forward_thread *next = thread->next; + + free(thread); + thread = next; + } + zend_signal_forward_threads = NULL; + for (int signo = 1; signo < NSIG; signo++) { + zend_signal_forward_update(signo); + } + pthread_mutex_unlock(zend_signal_forward_mutex); + } + + pthread_setspecific(zend_signal_forward_key, NULL); + pthread_key_delete(zend_signal_forward_key); +} + +ZEND_API bool zend_signal_forward(int signo) +{ +#ifndef ZEND_SIGNAL_FORWARD_ENABLED + return false; +#else + int errno_save = errno; + bool forwarded = false; + + if (zend_signal_forward_is_trackable(signo) + && zend_atomic_int_load_ex(&zend_signal_forward_pid) == (int) getpid()) { + if (zend_atomic_int_load_ex(&zend_signal_forward_targets[signo-1]) > 0) { + int value = zend_atomic_int_load_ex(&zend_signal_forward_generation[signo-1]) + 1; + int previous; + bool failed = false; + +#if ZEND_DEBUG + if (zend_atomic_bool_exchange_ex(&zend_signal_forward_test_stall, false)) { + zend_atomic_bool_store_ex(&zend_signal_forward_test_stalled, true); + while (!zend_atomic_bool_load_ex(&zend_signal_forward_test_resume)) { + usleep(1000); + } + zend_atomic_bool_store_ex(&zend_signal_forward_test_resume, false); + zend_atomic_bool_store_ex(&zend_signal_forward_test_stalled, false); + } +#endif + previous = zend_atomic_int_exchange_ex(&zend_signal_forward_pending[signo-1], value); + + /* A handler that was interrupted since it read the generation must not replace + * the signal of the timer that runs now. */ + if (previous != 0 && previous != value + && previous == zend_atomic_int_load_ex(&zend_signal_forward_generation[signo-1]) + 1) { + previous = zend_atomic_int_exchange_ex(&zend_signal_forward_pending[signo-1], previous); + } + + if (previous == 0) { + ssize_t written; + + do { + written = write(zend_atomic_int_load_ex(&zend_signal_forward_fd), "", 1); + } while (written < 0 && errno == EINTR); + + failed = written < 0 && errno != EAGAIN && errno != EWOULDBLOCK; +#if ZEND_DEBUG + if (written < 0 && !failed) { + zend_atomic_bool_store_ex(&zend_signal_forward_test_eagain, true); + } +#endif + } + + /* If the helper took the flag meanwhile, the signal is on its way. */ + forwarded = true; + if (failed || zend_atomic_int_load_ex(&zend_signal_forward_pid) != (int) getpid()) { + forwarded = zend_atomic_int_exchange_ex(&zend_signal_forward_pending[signo-1], 0) == 0; + } + } else { + /* Ignored by a PHP thread, or the signal of a timer that was just disarmed. */ + forwarded = zend_atomic_int_load_ex(&zend_signal_forward_ignoring[signo-1]) > 0 + || zend_signal_forward_recently_disarmed(signo); + } + } + + errno = errno_save; + return forwarded; +#endif +} + +ZEND_API void zend_signal_forward_or_default(int signo) +{ + /* The instruction of a fault would run again as soon as the handler returned. */ + if (!zend_signal_forward_is_trackable(signo)) { + signal(signo, SIG_DFL); + kill(getpid(), signo); + return; + } + +#ifdef ZEND_SIGNAL_FORWARD_ENABLED + if (!zend_signal_forward(signo)) { + int errno_save = errno; + + /* A handler is registered in this process, but forwarding could not be set up. + * Without forwarding, the registrations of this process are not recorded at all. */ + if (zend_atomic_bool_load_ex(&zend_signal_forward_started) + && (zend_atomic_int_load_ex(&zend_signal_forward_process) != (int) getpid() + || zend_atomic_int_load_ex(&zend_signal_forward_handlers[signo-1]) == 0)) { + signal(signo, SIG_DFL); + kill(getpid(), signo); + } + errno = errno_save; + } +#endif +} + +bool zend_signal_forward_has_handler(int signo) +{ + return zend_signal_forward_is_trackable(signo) + && zend_atomic_int_load_ex(&zend_signal_forward_handlers[signo-1]) > 0; +} + +ZEND_API int zend_signal_forward_acquire(int signo, const struct sigaction *act) +{ + zend_signal_forward_thread *self; + int result = 0; + + if (!zend_signal_forward_is_trackable(signo) || !zend_signal_forward_lock()) { + return act ? sigaction(signo, act, NULL) : 0; + } + + self = zend_signal_forward_self(); + if (self) { + self->handler[signo-1] = ++zend_signal_forward_order; + zend_signal_forward_orphaned[signo-1] = NULL; + self->ignored[signo-1] = false; + self->installed[signo-1] = act != NULL; + self->active = true; + zend_signal_forward_update(signo); + zend_signal_forward_helper_start(); + } + + if (act) { + result = sigaction(signo, act, NULL); + if (result != 0 && self) { + self->handler[signo-1] = 0; + zend_signal_forward_update(signo); + } + } + + zend_signal_forward_unlock(); + return result; +} + +ZEND_API void zend_signal_forward_mark_installed(int signo) +{ + zend_signal_forward_thread *self; + + if (!zend_signal_forward_is_trackable(signo) || !zend_signal_forward_lock()) { + return; + } + + self = zend_signal_forward_current(); + if (self && self->handler[signo-1]) { + self->installed[signo-1] = true; + } + + zend_signal_forward_unlock(); +} + +ZEND_API bool zend_signal_forward_suspend(void) +{ + bool running; + + if (!zend_signal_forward_lock()) { + return false; + } + + /* The pid stays: a signal meanwhile waits for the helper that resuming starts. */ + running = zend_signal_forward_helper_running; + if (running) { + zend_signal_forward_helper_stop = true; + zend_signal_forward_helper_running = false; + } + zend_signal_forward_unlock(); + + if (running) { + zend_signal_forward_helper_join(); + } + return running; +} + +ZEND_API void zend_signal_forward_resume(void) +{ + if (!zend_signal_forward_lock()) { + return; + } + + zend_signal_forward_helper_start_if_needed(); + if (!zend_signal_forward_helper_running) { + zend_atomic_int_store_ex(&zend_signal_forward_pid, 0); + zend_signal_forward_scan(); + } + + zend_signal_forward_unlock(); +} + +ZEND_API int zend_signal_forward_release(int signo, const struct sigaction *act) +{ + zend_signal_forward_thread *self; + bool ignore = act && act->sa_handler == SIG_IGN; + int result = 0; + + if (!zend_signal_forward_is_trackable(signo) || !zend_signal_forward_lock()) { + return act ? sigaction(signo, act, NULL) : 0; + } + + self = ignore ? zend_signal_forward_self() : zend_signal_forward_current(); + if (self) { + self->handler[signo-1] = 0; + self->installed[signo-1] = false; + self->ignored[signo-1] = ignore; + self->active = self->active || ignore; + /* This thread replaced the handler of its own timer. */ + if (self->timer_signo == signo) { + zend_signal_forward_disarm_self(self); + } + zend_signal_forward_update(signo); + } + + /* While the current disposition is still in place. */ + zend_signal_forward_flush(); + if (act) { + result = zend_signal_forward_apply(signo, act); + } + + zend_signal_forward_unlock(); + return result; +} + +ZEND_API void zend_signal_forward_timer_arm(int signo, const struct sigaction *act) +{ + zend_signal_forward_thread *self; + + if (!zend_signal_forward_is_trackable(signo) || !zend_signal_forward_lock()) { + return; + } + + self = zend_signal_forward_self(); + if (self) { + struct sigaction current; + bool runs = !self->ignored[signo-1]; + + /* With the default action, the timer would end the process when it expires. */ + if (runs && act && zend_atomic_int_load_ex(&zend_signal_forward_handlers[signo-1]) == 0 + && sigaction(signo, NULL, ¤t) == 0 && current.sa_handler != act->sa_handler) { + if (current.sa_handler == SIG_DFL || current.sa_handler == SIG_IGN + || current.sa_handler == zend_signal_forward_orphaned[signo-1]) { + sigaction(signo, act, NULL); + } else { + runs = false; + } + } + + zend_signal_forward_disarm_self(self); + if (runs) { + self->timer_signo = signo; + self->timer_order = ++zend_signal_forward_order; + self->has_timer_action = act != NULL; + if (act) { + self->timer_action = *act; + } + self->active = true; + zend_atomic_int_store_ex(&zend_signal_forward_disarmed_at[signo-1], 0); + zend_signal_forward_next_generation(signo); + zend_signal_forward_update(signo); + zend_signal_forward_helper_start(); + } + } + + zend_signal_forward_unlock(); +} + +ZEND_API int zend_signal_forward_timer_install(int signo, const struct sigaction *act) +{ + int result = 0; + + bool locked; + + if (!zend_signal_forward_is_trackable(signo)) { + return sigaction(signo, act, NULL); + } + + locked = zend_signal_forward_lock(); + if (zend_atomic_int_load_ex(&zend_signal_forward_handlers[signo-1]) == 0) { + result = sigaction(signo, act, NULL); + } + + if (locked) { + zend_signal_forward_unlock(); + } + return result; +} + +ZEND_API void zend_signal_forward_timer_disarm(void) +{ + zend_signal_forward_thread *self; + + if (!zend_atomic_bool_load_ex(&zend_signal_forward_started)) { + return; + } + + /* A request without a running timer must not contend on the mutex. */ + self = zend_signal_forward_current(); + if (!self || !self->timer_signo || !zend_signal_forward_lock()) { + return; + } + + /* After a fork(), taking the lock replaced the record. */ + self = zend_signal_forward_current(); + if (self) { + zend_signal_forward_disarm_self(self); + } + zend_signal_forward_unlock(); +} + +void zend_signal_forward_request_shutdown(void) +{ + zend_signal_forward_thread *self; + bool cleared; + + if (!zend_atomic_bool_load_ex(&zend_signal_forward_started)) { + return; + } + + /* Most requests register nothing, and must not contend on the mutex. */ + self = zend_signal_forward_current(); + if (!self || !self->active || !zend_signal_forward_lock()) { + return; + } + + /* After a fork(), taking the lock replaced the record. */ + self = zend_signal_forward_current(); + cleared = self && zend_signal_forward_clear_self(self); + zend_signal_forward_unlock(); + + if (cleared) { + zend_signal_forward_flush(); + } +} + +ZEND_API void zend_signal_forward_fork_child(bool shares_fds) +{ + /* Closing the pipe would close it for the parent too. */ + zend_signal_forward_shared_fds = shares_fds; + if (shares_fds) { + zend_signal_forward_pipe[0] = zend_signal_forward_pipe[1] = -1; + } + + if (!zend_signal_forward_lock()) { + return; + } + + zend_signal_forward_helper_start_if_needed(); + + zend_signal_forward_unlock(); +} + +#if ZEND_DEBUG +ZEND_API int zend_signal_forward_test(zend_signal_forward_test_op op) +{ + int result = 1; + int write_fd; + + if (op == ZEND_SIGNAL_FORWARD_TEST_RESTART) { + zend_signal_forward_shutdown(); + zend_signal_forward_startup(); + return 1; + } + + switch (op) { + case ZEND_SIGNAL_FORWARD_TEST_UNLOCK: + zend_signal_forward_unlock(); + return 1; + case ZEND_SIGNAL_FORWARD_TEST_STALL_HANDLER: + zend_atomic_bool_store_ex(&zend_signal_forward_test_stall, true); + return 1; + case ZEND_SIGNAL_FORWARD_TEST_WAIT_STALLED: + for (time_t start = time(NULL); !zend_atomic_bool_load_ex(&zend_signal_forward_test_stalled); usleep(1000)) { + if (time(NULL) - start > 30) { + return 0; + } + } + return 1; + case ZEND_SIGNAL_FORWARD_TEST_RESUME_HANDLER: + zend_atomic_bool_store_ex(&zend_signal_forward_test_resume, true); + for (time_t start = time(NULL); zend_atomic_bool_load_ex(&zend_signal_forward_test_stalled); usleep(1000)) { + if (time(NULL) - start > 30) { + return 0; + } + } + return 1; + case ZEND_SIGNAL_FORWARD_TEST_FAIL_PIPE: + zend_atomic_bool_store_ex(&zend_signal_forward_test_fail_pipe, true); + return 1; + case ZEND_SIGNAL_FORWARD_TEST_FAIL_CREATE: + zend_atomic_bool_store_ex(&zend_signal_forward_test_fail_create, true); + return 1; + case ZEND_SIGNAL_FORWARD_TEST_FAIL_INIT: + zend_atomic_bool_store_ex(&zend_signal_forward_test_fail_init, true); + return 1; + default: + break; + } + if (op == ZEND_SIGNAL_FORWARD_TEST_PID) { + return zend_atomic_int_load_ex(&zend_signal_forward_pid); + } + + if (!zend_signal_forward_lock()) { + return 0; + } + if (op == ZEND_SIGNAL_FORWARD_TEST_LOCK) { + return 1; + } + write_fd = zend_signal_forward_pipe[1]; + if (op == ZEND_SIGNAL_FORWARD_TEST_RUNNING) { + result = zend_signal_forward_helper_running; + } else if (op == ZEND_SIGNAL_FORWARD_TEST_READ_FD) { + result = zend_signal_forward_pipe[0]; + } else if (op == ZEND_SIGNAL_FORWARD_TEST_WRITE_FD) { + result = write_fd; + } + zend_signal_forward_unlock(); + + switch (op) { + case ZEND_SIGNAL_FORWARD_TEST_HOLD: + zend_atomic_bool_store_ex(&zend_signal_forward_test_hold, true); + while (write(write_fd, "", 1) < 0 && errno == EINTR); + while (!zend_atomic_bool_load_ex(&zend_signal_forward_test_held)) { + usleep(1000); + } + break; + case ZEND_SIGNAL_FORWARD_TEST_RELEASE: + zend_atomic_bool_store_ex(&zend_signal_forward_test_hold, false); + while (zend_atomic_bool_load_ex(&zend_signal_forward_test_held)) { + usleep(1000); + } + break; + case ZEND_SIGNAL_FORWARD_TEST_SATURATE: + while (write(write_fd, "", 1) == 1); + result = errno == EAGAIN; + break; + case ZEND_SIGNAL_FORWARD_TEST_FAIL_READ: + zend_atomic_bool_store_ex(&zend_signal_forward_test_fail_read, true); + break; + case ZEND_SIGNAL_FORWARD_TEST_HANDLER_EAGAIN: + result = zend_atomic_bool_exchange_ex(&zend_signal_forward_test_eagain, false); + break; + default: + break; + } + return result; +} +#endif + +#endif /* defined(ZTS) && !defined(ZEND_WIN32) */ diff --git a/Zend/zend_signal_forward.h b/Zend/zend_signal_forward.h new file mode 100644 index 000000000000..6e9a0355010e --- /dev/null +++ b/Zend/zend_signal_forward.h @@ -0,0 +1,108 @@ +/* + +----------------------------------------------------------------------+ + | Zend Signal Forwarding | + +----------------------------------------------------------------------+ + | Copyright (c) The PHP Group | + +----------------------------------------------------------------------+ + | This source file is subject to version 3.01 of the PHP license, | + | that is bundled with this package in the file LICENSE, and is | + | available through the world-wide-web at the following url: | + | https://www.php.net/license/3_01.txt | + | If you did not receive a copy of the PHP license and are unable to | + | obtain it through the world-wide-web, please send a note to | + | license@php.net so we can mail you a copy immediately. | + +----------------------------------------------------------------------+ +*/ + +#ifndef ZEND_SIGNAL_FORWARD_H +#define ZEND_SIGNAL_FORWARD_H + +#if defined(ZTS) && !defined(ZEND_WIN32) + +#include + +#include "zend_atomic.h" +#include "zend_portability.h" + +/* See the assumptions at the top of zend_signal_forward.c. Elsewhere, a signal on a thread + * without PHP context is not forwarded. */ +#if defined(ZEND_ATOMIC_SIGNAL_SAFE) && !defined(ZEND_SIGNAL_FORWARD_DISABLED) \ + && ((defined(__linux__) && !defined(__BIONIC__) && !defined(__UCLIBC__)) \ + || defined(__APPLE__) || defined(__FreeBSD__)) +# define ZEND_SIGNAL_FORWARD_ENABLED 1 +#endif + +BEGIN_EXTERN_C() + +void zend_signal_forward_startup(void); +void zend_signal_forward_shutdown(void); + +/* For signal handlers. Hands the signal over to the thread that owns it, and + * returns false if the caller has to apply the default policy for the signal. */ +ZEND_API bool zend_signal_forward(int signo); +/* For signal handlers. As above, taking the default action when there is no owner. */ +ZEND_API void zend_signal_forward_or_default(int signo); + +/* The calling thread handles signo. If act is given, it is installed. */ +ZEND_API int zend_signal_forward_acquire(int signo, const struct sigaction *act); +/* The handler that the calling thread registered for signo was installed for it, and is + * removed with the thread. */ +ZEND_API void zend_signal_forward_mark_installed(int signo); +/* The helper thread stops and starts again, for a system call that requires a process + * with a single thread. Signals meanwhile are forwarded when it has started again. + * Returns whether a helper was stopped. The system may count the thread for a moment + * after it was joined. */ +ZEND_API bool zend_signal_forward_suspend(void); +ZEND_API void zend_signal_forward_resume(void); +/* The calling thread no longer handles signo. If act is given, it is installed + * unless the process-wide disposition is still needed by another thread. */ +ZEND_API int zend_signal_forward_release(int signo, const struct sigaction *act); + +/* Whether a thread has a handler for signo, which the execution timer must not replace. */ +bool zend_signal_forward_has_handler(int signo); + +/* The calling thread armed the execution timer, which delivers signo. If act is given, + * it becomes the disposition unless a thread handles signo, this thread ignores it, or + * something else was installed for it, and it is restored when a handler is released. */ +ZEND_API void zend_signal_forward_timer_arm(int signo, const struct sigaction *act); +ZEND_API void zend_signal_forward_timer_disarm(void); +/* Installs the handler of the execution timer, unless a thread has a handler for signo. */ +ZEND_API int zend_signal_forward_timer_install(int signo, const struct sigaction *act); + +/* Everything registered by the calling thread ends with the request. */ +void zend_signal_forward_request_shutdown(void); +/* To call in the child of a fork(), where only the calling thread exists. shares_fds + * tells that the child shares its file descriptor table with its parent. */ +ZEND_API void zend_signal_forward_fork_child(bool shares_fds); + +#if ZEND_DEBUG +/* Lets ext/zend_test reach states that depend on the timing of the helper thread. */ +typedef enum { + ZEND_SIGNAL_FORWARD_TEST_HOLD, + ZEND_SIGNAL_FORWARD_TEST_RELEASE, + ZEND_SIGNAL_FORWARD_TEST_SATURATE, + ZEND_SIGNAL_FORWARD_TEST_FAIL_READ, + ZEND_SIGNAL_FORWARD_TEST_HANDLER_EAGAIN, + ZEND_SIGNAL_FORWARD_TEST_RUNNING, + ZEND_SIGNAL_FORWARD_TEST_RESTART, + ZEND_SIGNAL_FORWARD_TEST_READ_FD, + ZEND_SIGNAL_FORWARD_TEST_WRITE_FD, + ZEND_SIGNAL_FORWARD_TEST_LOCK, + ZEND_SIGNAL_FORWARD_TEST_UNLOCK, + ZEND_SIGNAL_FORWARD_TEST_PID, + ZEND_SIGNAL_FORWARD_TEST_STALL_HANDLER, + ZEND_SIGNAL_FORWARD_TEST_WAIT_STALLED, + ZEND_SIGNAL_FORWARD_TEST_RESUME_HANDLER, + ZEND_SIGNAL_FORWARD_TEST_FAIL_PIPE, + ZEND_SIGNAL_FORWARD_TEST_FAIL_CREATE, + ZEND_SIGNAL_FORWARD_TEST_FAIL_INIT +} zend_signal_forward_test_op; + +ZEND_API int zend_signal_forward_test(zend_signal_forward_test_op op); +#endif + +END_EXTERN_C() + +#endif /* defined(ZTS) && !defined(ZEND_WIN32) */ + +#endif /* ZEND_SIGNAL_FORWARD_H */ diff --git a/configure.ac b/configure.ac index 5612a0696a1f..00e29960547b 100644 --- a/configure.ac +++ b/configure.ac @@ -1753,6 +1753,7 @@ PHP_ADD_SOURCES([Zend], m4_normalize([ zend_property_hooks.c zend_ptr_stack.c zend_signal.c + zend_signal_forward.c zend_smart_str.c zend_sort.c zend_stack.c diff --git a/ext/pcntl/pcntl.c b/ext/pcntl/pcntl.c index 67b129a15096..e3990309066f 100644 --- a/ext/pcntl/pcntl.c +++ b/ext/pcntl/pcntl.c @@ -176,6 +176,42 @@ ZEND_GET_MODULE(pcntl) static void (*orig_interrupt_function)(zend_execute_data *execute_data); +/* sigprocmask() applies to every thread on some systems, such as macOS. */ +#ifdef ZTS +# define pcntl_thread_sigmask tsrm_sigmask +#else +# define pcntl_thread_sigmask sigprocmask +#endif + +#if defined(ZTS) && !defined(ZEND_SIGNALS) +static zend_always_inline void pcntl_signal_set_handled(int signo, bool handled) +{ + if (signo < NSIG) { + zend_atomic_bool_store_ex(&PCNTL_G(handled_signals)[signo-1], handled); + } +} + +static int pcntl_signal_restore(int signo, Sigfunc *func, int restart) +{ + struct sigaction act; + int result; + + memset(&act, 0, sizeof(act)); +#ifdef HAVE_STRUCT_SIGINFO_T + act.sa_sigaction = func; +#else + act.sa_handler = func; +#endif + sigemptyset(&act.sa_mask); + act.sa_flags = restart ? SA_RESTART : 0; + /* A signal already forwarded to this thread is still handled during the release. */ + result = zend_signal_forward_release(signo, &act); + pcntl_signal_set_handled(signo, false); + + return result; +} +#endif + #ifdef HAVE_STRUCT_SIGINFO_T static void pcntl_signal_handler(int, siginfo_t*, void*); static void pcntl_siginfo_to_zval(int, siginfo_t*, zval*); @@ -236,7 +272,11 @@ PHP_RSHUTDOWN_FUNCTION(pcntl) /* Reset all signals to their default disposition */ ZEND_HASH_FOREACH_NUM_KEY_VAL(&PCNTL_G(php_signal_table), signo, handle) { if (Z_TYPE_P(handle) != IS_LONG || Z_LVAL_P(handle) != (zend_long)SIG_DFL) { +#if defined(ZTS) && !defined(ZEND_SIGNALS) + pcntl_signal_restore((int) signo, (Sigfunc *)(zend_long)SIG_DFL, 0); +#else php_signal(signo, (Sigfunc *)(zend_long)SIG_DFL, 0); +#endif } } ZEND_HASH_FOREACH_END(); @@ -294,6 +334,9 @@ PHP_FUNCTION(pcntl_fork) } } else if (id == 0) { +#if defined(ZTS) + zend_signal_forward_fork_child(false); +#endif zend_max_execution_timer_init(); php_clear_stat_cache(true, NULL, 0); } @@ -800,7 +843,11 @@ PHP_FUNCTION(pcntl_signal) /* Special long value case for SIG_DFL and SIG_IGN */ if (Z_TYPE_P(handle) == IS_LONG) { +#if defined(ZTS) && !defined(ZEND_SIGNALS) + if (pcntl_signal_restore((int) signo, (Sigfunc *) Z_LVAL_P(handle), (int) restart_syscalls) != 0) { +#else if (php_signal(signo, (Sigfunc *) Z_LVAL_P(handle), (int) restart_syscalls) == (void *)SIG_ERR) { +#endif PCNTL_G(last_error) = errno; php_error_docref(NULL, E_WARNING, "Error assigning signal"); RETURN_FALSE; @@ -810,11 +857,28 @@ PHP_FUNCTION(pcntl_signal) } /* Register with the OS first so that on failure we don't record a handler that was never installed */ +#ifdef ZTS + /* Before the handler is installed, so that no signal finds it without a thread to go to */ +# ifndef ZEND_SIGNALS + pcntl_signal_set_handled((int) signo, true); +# endif + zend_signal_forward_acquire((int) signo, NULL); +#endif if (php_signal4(signo, pcntl_signal_handler, (int) restart_syscalls, 1) == (void *)SIG_ERR) { PCNTL_G(last_error) = errno; +#ifdef ZTS + zend_signal_forward_release((int) signo, NULL); +# ifndef ZEND_SIGNALS + pcntl_signal_set_handled((int) signo, false); +# endif +#endif php_error_docref(NULL, E_WARNING, "Error assigning signal"); RETURN_FALSE; } +#if defined(ZTS) && !defined(ZEND_SIGNALS) + /* Installed directly, so it must not outlive the threads that handle the signal. */ + zend_signal_forward_mark_installed((int) signo); +#endif /* Add the function name to our signal table */ handle = zend_hash_index_update(&PCNTL_G(php_signal_table), signo, handle); @@ -1297,6 +1361,17 @@ static void pcntl_signal_handler(int signo, siginfo_t *siginfo, void *context) static void pcntl_signal_handler(int signo) #endif { +#if defined(ZTS) && !defined(ZEND_SIGNALS) + /* Without zend signals this handler is installed directly, and PCNTL_G() + * would dereference the missing TSRM storage of a thread that never ran PHP. + * The signal may also reach a PHP thread when another one handles it. */ + if (!tsrm_is_managed_thread() + || (signo < NSIG && !zend_atomic_bool_load_ex(&PCNTL_G(handled_signals)[signo-1]))) { + zend_signal_forward_or_default(signo); + return; + } +#endif + struct php_pcntl_pending_signal *psig = PCNTL_G(spares); if (!psig) { /* oops, too many signals for us to track, so we'll forget about this one */ @@ -1341,11 +1416,11 @@ void pcntl_signal_dispatch(void) /* Mask all signals */ sigfillset(&mask); - sigprocmask(SIG_BLOCK, &mask, &old_mask); + pcntl_thread_sigmask(SIG_BLOCK, &mask, &old_mask); /* Bail if the queue is empty or if we are already playing the queue */ if (!PCNTL_G(head) || PCNTL_G(processing_signal_queue)) { - sigprocmask(SIG_SETMASK, &old_mask, NULL); + pcntl_thread_sigmask(SIG_SETMASK, &old_mask, NULL); return; } @@ -1449,7 +1524,7 @@ void pcntl_signal_dispatch(void) zend_fiber_switch_unblock(); /* return signal mask to previous state */ - sigprocmask(SIG_SETMASK, &old_mask, NULL); + pcntl_thread_sigmask(SIG_SETMASK, &old_mask, NULL); } static void pcntl_signal_dispatch_tick_function(int dummy_int, void *dummy_pointer) @@ -1486,7 +1561,20 @@ PHP_FUNCTION(pcntl_unshare) Z_PARAM_LONG(flags) ZEND_PARSE_PARAMETERS_END(); - if (unshare(flags) == -1) { + int result = unshare(flags); +#ifdef ZTS + if (result == -1 && errno == EINVAL && zend_signal_forward_suspend()) { + /* The kernel may require a single thread, which the signal forwarding helper is not. */ + for (int i = 0; i < 100 && (result = unshare(flags)) == -1 && errno == EINVAL; i++) { + usleep(1000); + } + int unshare_errno = errno; + zend_signal_forward_resume(); + errno = unshare_errno; + } +#endif + + if (result == -1) { PCNTL_G(last_error) = errno; switch (errno) { #ifdef EINVAL @@ -1582,6 +1670,9 @@ PHP_FUNCTION(pcntl_rfork) php_error_docref(NULL, E_WARNING, "Error %d", errno); } } else if (pid == 0) { +#if defined(ZTS) + zend_signal_forward_fork_child((flags & RFFDG) == 0); +#endif zend_max_execution_timer_init(); php_clear_stat_cache(true, NULL, 0); } @@ -1628,6 +1719,9 @@ PHP_FUNCTION(pcntl_forkx) php_error_docref(NULL, E_WARNING, "Error %d", errno); } } else if (pid == 0) { +#if defined(ZTS) + zend_signal_forward_fork_child(false); +#endif zend_max_execution_timer_init(); php_clear_stat_cache(true, NULL, 0); } @@ -1681,6 +1775,16 @@ PHP_FUNCTION(pcntl_setns) } ret = setns(fd, (int)nstype); int setns_errno = errno; +#ifdef ZTS + if (ret == -1 && setns_errno == EINVAL && zend_signal_forward_suspend()) { + /* The kernel may require a single thread, which the signal forwarding helper is not. */ + for (int i = 0; i < 100 && (ret = setns(fd, (int)nstype)) == -1 && errno == EINVAL; i++) { + usleep(1000); + } + setns_errno = errno; + zend_signal_forward_resume(); + } +#endif close(fd); if (ret == -1) { diff --git a/ext/pcntl/php_pcntl.h b/ext/pcntl/php_pcntl.h index f09ccadcd3cd..eb8eaa3e622f 100644 --- a/ext/pcntl/php_pcntl.h +++ b/ext/pcntl/php_pcntl.h @@ -41,6 +41,13 @@ struct php_pcntl_pending_signal { #endif }; +#if defined(ZTS) && !defined(ZEND_SIGNALS) +# include +# ifndef NSIG +# define NSIG 65 +# endif +#endif + ZEND_BEGIN_MODULE_GLOBALS(pcntl) HashTable php_signal_table; int processing_signal_queue; @@ -49,6 +56,10 @@ ZEND_BEGIN_MODULE_GLOBALS(pcntl) volatile char pending_signals; bool async_signals; unsigned num_signals; +#if defined(ZTS) && !defined(ZEND_SIGNALS) + /* Read by the signal handler, where the signal table cannot be used */ + zend_atomic_bool handled_signals[NSIG]; +#endif ZEND_END_MODULE_GLOBALS(pcntl) #if defined(ZTS) && defined(COMPILE_DL_PCNTL) diff --git a/ext/pcntl/tests/gh25541.phpt b/ext/pcntl/tests/gh25541.phpt new file mode 100644 index 000000000000..0b32a3473646 --- /dev/null +++ b/ext/pcntl/tests/gh25541.phpt @@ -0,0 +1,32 @@ +--TEST-- +GH-25541 (pcntl handler for a signal delivered on a thread that never ran PHP) +--EXTENSIONS-- +pcntl +zend_test +--SKIPIF-- + +--FILE-- + +--EXPECT-- +handled SIGUSR1 +done diff --git a/ext/pcntl/tests/gh25541_fault.phpt b/ext/pcntl/tests/gh25541_fault.phpt new file mode 100644 index 000000000000..372b1fe6df4e --- /dev/null +++ b/ext/pcntl/tests/gh25541_fault.phpt @@ -0,0 +1,36 @@ +--TEST-- +GH-25541 (a fault on a thread that never ran PHP is not forwarded) +--EXTENSIONS-- +pcntl +zend_test +--SKIPIF-- + +--FILE-- + SIGSEGV, 'SIGTRAP' => SIGTRAP] as $name => $signo) { + $code = << ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); + echo stream_get_contents($pipes[1]); + do { + $status = proc_get_status($process); + usleep(10000); + } while ($status['running']); + echo $name, ': ', var_export($status['signaled'] && $status['termsig'] === $signo, true), "\n"; +} +?> +--EXPECT-- +SIGSEGV: true +SIGTRAP: true diff --git a/ext/pcntl/tests/gh25541_fork.phpt b/ext/pcntl/tests/gh25541_fork.phpt new file mode 100644 index 000000000000..0f5d56817dce --- /dev/null +++ b/ext/pcntl/tests/gh25541_fork.phpt @@ -0,0 +1,40 @@ +--TEST-- +GH-25541 (signal on a thread that never ran PHP, in the child of pcntl_fork()) +--EXTENSIONS-- +pcntl +posix +zend_test +--SKIPIF-- + +--FILE-- + +--EXPECT-- +child handled +bool(true) diff --git a/ext/pcntl/tests/gh25541_rfork.phpt b/ext/pcntl/tests/gh25541_rfork.phpt new file mode 100644 index 000000000000..8d1896393d0b --- /dev/null +++ b/ext/pcntl/tests/gh25541_rfork.phpt @@ -0,0 +1,40 @@ +--TEST-- +GH-25541 (forwarding keeps working in the parent of pcntl_rfork()) +--EXTENSIONS-- +pcntl +posix +zend_test +--SKIPIF-- + +--FILE-- + +--EXPECT-- +bool(true) diff --git a/ext/pcntl/tests/gh25541_unshare.phpt b/ext/pcntl/tests/gh25541_unshare.phpt new file mode 100644 index 000000000000..94825c0fadb2 --- /dev/null +++ b/ext/pcntl/tests/gh25541_unshare.phpt @@ -0,0 +1,36 @@ +--TEST-- +GH-25541 (pcntl_unshare() still works, and forwarding goes on, with a signal handler) +--EXTENSIONS-- +pcntl +zend_test +--SKIPIF-- + +--FILE-- + +--EXPECT-- +bool(true) +bool(true) diff --git a/ext/pcntl/tests/gh25548.phpt b/ext/pcntl/tests/gh25548.phpt new file mode 100644 index 000000000000..fdf14a49b994 --- /dev/null +++ b/ext/pcntl/tests/gh25548.phpt @@ -0,0 +1,22 @@ +--TEST-- +GH-25548 (execution timeout delivered to a thread that never ran PHP) +--EXTENSIONS-- +pcntl +zend_test +--SKIPIF-- + +--FILE-- + +--EXPECTF-- +Fatal error: Maximum execution time of 1 second exceeded in %s on line %d diff --git a/ext/pcntl/tests/gh25548_stale_timer.phpt b/ext/pcntl/tests/gh25548_stale_timer.phpt new file mode 100644 index 000000000000..93af77e65950 --- /dev/null +++ b/ext/pcntl/tests/gh25548_stale_timer.phpt @@ -0,0 +1,21 @@ +--TEST-- +GH-25548 (signal of a disarmed execution timer delivered to a thread that never ran PHP) +--EXTENSIONS-- +pcntl +zend_test +--SKIPIF-- + +--FILE-- + +--EXPECT-- +survived diff --git a/ext/zend_test/config.m4 b/ext/zend_test/config.m4 index f49221b9fb64..66c7140d212e 100644 --- a/ext/zend_test/config.m4 +++ b/ext/zend_test/config.m4 @@ -9,6 +9,7 @@ if test "$PHP_ZEND_TEST" != "no"; then iterators.c object_handlers.c observer.c + signal_forwarding.c test.c zend_mm_custom_handlers.c ]), diff --git a/ext/zend_test/config.w32 b/ext/zend_test/config.w32 index 65fe6d359ba7..106b9d156ca9 100644 --- a/ext/zend_test/config.w32 +++ b/ext/zend_test/config.w32 @@ -3,6 +3,6 @@ ARG_ENABLE("zend-test", "enable zend_test extension", "no"); if (PHP_ZEND_TEST != "no") { - EXTENSION("zend_test", "test.c observer.c fiber.c iterators.c object_handlers.c zend_mm_custom_handlers.c", PHP_ZEND_TEST_SHARED, "/DZEND_ENABLE_STATIC_TSRMLS_CACHE=1"); + EXTENSION("zend_test", "test.c observer.c fiber.c iterators.c object_handlers.c signal_forwarding.c zend_mm_custom_handlers.c", PHP_ZEND_TEST_SHARED, "/DZEND_ENABLE_STATIC_TSRMLS_CACHE=1"); ADD_FLAG("CFLAGS_ZEND_TEST", "/D PHP_ZEND_TEST_EXPORTS "); } diff --git a/ext/zend_test/signal_forwarding.c b/ext/zend_test/signal_forwarding.c new file mode 100644 index 000000000000..61190c2f126e --- /dev/null +++ b/ext/zend_test/signal_forwarding.c @@ -0,0 +1,1122 @@ +/* + +----------------------------------------------------------------------+ + | Copyright (c) The PHP Group | + +----------------------------------------------------------------------+ + | This source file is subject to version 3.01 of the PHP license, | + | that is bundled with this package in the file LICENSE, and is | + | available through the world-wide-web at the following url: | + | https://www.php.net/license/3_01.txt | + | If you did not receive a copy of the PHP license and are unable to | + | obtain it through the world-wide-web, please send a note to | + | license@php.net so we can mail you a copy immediately. | + +----------------------------------------------------------------------+ +*/ + +#include "signal_forwarding.h" + +#if defined(ZTS) && !defined(PHP_WIN32) + +#include +#include +#include +#include +#include +#include + +#include "zend_atomic.h" +#include "zend_signal.h" + +static void *zend_test_raise_thread(void *arg) +{ + raise((int) (intptr_t) arg); + return NULL; +} + +bool zend_test_signal_forwarding_raise(int signo) +{ + pthread_t thread; + + if (pthread_create(&thread, NULL, zend_test_raise_thread, (void *) (intptr_t) signo) != 0) { + return false; + } + pthread_join(thread, NULL); + return true; +} + +/* Drives the record of which threads handle a signal, without running PHP code + * on the other threads. */ +/* Ignored by default, so that a forward arriving after a scenario is harmless. */ +#define ZEND_TEST_FORWARD_SIGNAL SIGURG +#define ZEND_TEST_FORWARD_WORKERS 4 + +enum { + ZEND_TEST_FORWARD_IDLE, + ZEND_TEST_FORWARD_RECORD, + ZEND_TEST_FORWARD_RECORD_TIMER, + ZEND_TEST_FORWARD_FORGET, + ZEND_TEST_FORWARD_RAISE, + ZEND_TEST_FORWARD_BLOCK, + ZEND_TEST_FORWARD_WAIT_PENDING, + ZEND_TEST_FORWARD_EXIT +}; + +static pthread_t zend_test_forward_main; +static pthread_t zend_test_forward_helper; +static zend_atomic_bool zend_test_forward_helper_set; +static zend_atomic_bool zend_test_forward_helper_registered; +static zend_atomic_int zend_test_forward_main_hits; +static zend_atomic_int zend_test_forward_helper_hits; +static zend_atomic_int zend_test_forward_command; +static zend_atomic_bool zend_test_forward_stop; +static zend_atomic_bool zend_test_forward_result; +static zend_atomic_int zend_test_forward_replacement_hits; + +/* Polls instead of sleeping, so that a passing run does not depend on timing. */ +static bool zend_test_forward_wait_pending(void) +{ + time_t start = time(NULL); + + /* Measured in time, as signals interrupt the sleep. */ + while (time(NULL) - start < 30) { + sigset_t pending; + + sigpending(&pending); + if (sigismember(&pending, ZEND_TEST_FORWARD_SIGNAL) == 1) { + return true; + } + usleep(1000); + } + return false; +} + +static void zend_test_forward_replacement_handler(int signo) +{ + zend_atomic_int_store(&zend_test_forward_replacement_hits, zend_atomic_int_load(&zend_test_forward_replacement_hits) + 1); +} + +static void zend_test_forward_handler(int signo) +{ + pthread_t self = pthread_self(); + + if (pthread_equal(self, zend_test_forward_main)) { + zend_atomic_int_store(&zend_test_forward_main_hits, zend_atomic_int_load(&zend_test_forward_main_hits) + 1); + } else if (zend_atomic_bool_load(&zend_test_forward_helper_set) && pthread_equal(self, zend_test_forward_helper) + && zend_atomic_bool_load(&zend_test_forward_helper_registered)) { + zend_atomic_int_store(&zend_test_forward_helper_hits, zend_atomic_int_load(&zend_test_forward_helper_hits) + 1); + } else { + zend_atomic_bool_store(&zend_test_forward_result, zend_signal_forward(signo)); + } +} + +static void *zend_test_forward_helper_main(void *arg) +{ + while (1) { + int command = zend_atomic_int_load(&zend_test_forward_command); + + if (command == ZEND_TEST_FORWARD_IDLE) { + usleep(100); + continue; + } + if (command == ZEND_TEST_FORWARD_EXIT) { + return NULL; + } + if (command == ZEND_TEST_FORWARD_RECORD) { + zend_atomic_bool_store(&zend_test_forward_helper_registered, true); + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + } else if (command == ZEND_TEST_FORWARD_RECORD_TIMER) { + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, NULL); + } else if (command == ZEND_TEST_FORWARD_FORGET) { + zend_atomic_bool_store(&zend_test_forward_helper_registered, false); + zend_signal_forward_release(ZEND_TEST_FORWARD_SIGNAL, NULL); + } else if (command == ZEND_TEST_FORWARD_RAISE) { + raise(ZEND_TEST_FORWARD_SIGNAL); + } else if (command == ZEND_TEST_FORWARD_BLOCK) { + sigset_t block; + + sigemptyset(&block); + sigaddset(&block, ZEND_TEST_FORWARD_SIGNAL); + pthread_sigmask(SIG_BLOCK, &block, NULL); + } else if (command == ZEND_TEST_FORWARD_WAIT_PENDING) { + zend_test_forward_wait_pending(); + } + zend_atomic_int_store(&zend_test_forward_command, ZEND_TEST_FORWARD_IDLE); + } +} + +static void zend_test_forward_send(int command) +{ + zend_atomic_int_store(&zend_test_forward_command, command); + while (zend_atomic_int_load(&zend_test_forward_command) != ZEND_TEST_FORWARD_IDLE) { + usleep(100); + } +} + +static void zend_test_forward_helper_start(void) +{ + zend_atomic_int_store(&zend_test_forward_command, ZEND_TEST_FORWARD_IDLE); + pthread_create(&zend_test_forward_helper, NULL, zend_test_forward_helper_main, NULL); + zend_atomic_bool_store(&zend_test_forward_helper_set, true); +} + +/* Returns once the thread has exited, which removes its record. */ +static void zend_test_forward_helper_exit(void) +{ + zend_atomic_int_store(&zend_test_forward_command, ZEND_TEST_FORWARD_EXIT); + pthread_join(zend_test_forward_helper, NULL); + zend_atomic_bool_store(&zend_test_forward_helper_set, false); + zend_atomic_bool_store(&zend_test_forward_helper_registered, false); +} + +static void *zend_test_forward_raise_main(void *arg) +{ + sigset_t unblock; + + /* A new thread inherits the signal mask of its creator. */ + sigemptyset(&unblock); + sigaddset(&unblock, ZEND_TEST_FORWARD_SIGNAL); + pthread_sigmask(SIG_UNBLOCK, &unblock, NULL); + + raise(ZEND_TEST_FORWARD_SIGNAL); + return NULL; +} + +static void zend_test_forward_raise_foreign(void) +{ + pthread_t thread; + + pthread_create(&thread, NULL, zend_test_forward_raise_main, NULL); + pthread_join(thread, NULL); +} + +static bool zend_test_forward_wait(zend_atomic_int *hits) +{ + time_t start = time(NULL); + + while (time(NULL) - start < 30) { + if (zend_atomic_int_load(hits) > 0) { + return true; + } + usleep(1000); + } + return false; +} + +static void *zend_test_forward_worker_main(void *arg) +{ + for (int i = 0; i < 2000; i++) { + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_release(ZEND_TEST_FORWARD_SIGNAL, NULL); + } + return NULL; +} + +static void *zend_test_forward_short_lived_main(void *arg) +{ + /* The record is removed when the thread exits. */ + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + return NULL; +} + +static void *zend_test_forward_storm_main(void *arg) +{ + while (!zend_atomic_bool_load(&zend_test_forward_stop)) { + raise(ZEND_TEST_FORWARD_SIGNAL); + usleep(50); + } + return NULL; +} + +static void *zend_test_forward_churn_main(void *arg) +{ + while (!zend_atomic_bool_load(&zend_test_forward_stop)) { + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_release(ZEND_TEST_FORWARD_SIGNAL, NULL); + } + return NULL; +} + +#if ZEND_DEBUG +static void zend_test_forward_exit_marker(int signo) +{ +} + +static pthread_key_t zend_test_forward_exit_key; + +static void zend_test_forward_exit_destructor(void *arg) +{ + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); +#ifndef PTHREAD_DESTRUCTOR_ITERATIONS +# define PTHREAD_DESTRUCTOR_ITERATIONS 4 +#endif + /* Runs again on every pass that the system makes over the destructors, and leaves + * nothing behind after the last one. */ + if ((intptr_t) arg < PTHREAD_DESTRUCTOR_ITERATIONS - 1) { + pthread_setspecific(zend_test_forward_exit_key, (void *) ((intptr_t) arg + 1)); + } +} + +static void *zend_test_forward_timer_install_main(void *arg) +{ + zend_signal_forward_timer_install(ZEND_TEST_FORWARD_SIGNAL, arg); + return NULL; +} + +static void *zend_test_forward_exit_main(void *arg) +{ + pthread_setspecific(zend_test_forward_exit_key, (void *) 1); + return NULL; +} +#endif + +/* A hang in a child fails the test instead of stalling it. */ +static bool zend_test_forward_wait_child(pid_t pid) +{ + time_t start = time(NULL); + + while (time(NULL) - start < 60) { + int status = 0; + pid_t result = waitpid(pid, &status, WNOHANG); + + if (result == pid) { + return WIFEXITED(status) && WEXITSTATUS(status) == 0; + } + if (result < 0) { + return false; + } + usleep(1000); + } + kill(pid, SIGKILL); + waitpid(pid, NULL, 0); + return false; +} + +/* Forwarding must work in the child, where only the calling thread exists. */ +static bool zend_test_forward_child_delivers(void) +{ + zend_test_forward_main = pthread_self(); + zend_atomic_bool_store(&zend_test_forward_helper_set, false); + zend_atomic_int_store(&zend_test_forward_main_hits, 0); + zend_signal_forward_fork_child(false); + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_raise_foreign(); + return zend_test_forward_wait(&zend_test_forward_main_hits); +} + +static bool zend_test_forward_fork_and_check(void) +{ + pid_t pid = fork(); + + if (pid == 0) { + _exit(zend_test_forward_child_delivers() ? 0 : 1); + } + return pid > 0 && zend_test_forward_wait_child(pid); +} + +static bool zend_test_forward_fork_chain(int depth) +{ + pid_t pid = fork(); + + if (pid == 0) { + bool result = zend_test_forward_child_delivers(); + + _exit(result && (depth == 0 || zend_test_forward_fork_chain(depth - 1)) ? 0 : 1); + } + return pid > 0 && zend_test_forward_wait_child(pid); +} + +static bool zend_test_forward_scenario(const char *scenario) +{ + if (strcmp(scenario, "unmanaged") == 0) { + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_raise_foreign(); + return zend_test_forward_wait(&zend_test_forward_main_hits); + } + + if (strcmp(scenario, "successor") == 0) { + bool result; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_helper_start(); + zend_test_forward_send(ZEND_TEST_FORWARD_RECORD); + zend_test_forward_send(ZEND_TEST_FORWARD_FORGET); + zend_test_forward_raise_foreign(); + result = zend_test_forward_wait(&zend_test_forward_main_hits); + zend_test_forward_helper_exit(); + return result; + } + + if (strcmp(scenario, "most_recent_owner") == 0) { + bool result; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_helper_start(); + zend_test_forward_send(ZEND_TEST_FORWARD_RECORD); + zend_test_forward_raise_foreign(); + result = zend_test_forward_wait(&zend_test_forward_helper_hits) + && zend_atomic_int_load(&zend_test_forward_main_hits) == 0; + zend_test_forward_helper_exit(); + return result; + } + + if (strcmp(scenario, "owner_exit") == 0) { + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_helper_start(); + zend_test_forward_send(ZEND_TEST_FORWARD_RECORD); + zend_test_forward_helper_exit(); + zend_test_forward_raise_foreign(); + return zend_test_forward_wait(&zend_test_forward_main_hits); + } + + if (strcmp(scenario, "last_owner_exit") == 0) { + zend_test_forward_helper_start(); + zend_test_forward_send(ZEND_TEST_FORWARD_RECORD); + zend_test_forward_helper_exit(); + zend_test_forward_raise_foreign(); + usleep(50000); + return zend_atomic_int_load(&zend_test_forward_main_hits) == 0 + && zend_atomic_int_load(&zend_test_forward_helper_hits) == 0; + } + + if (strcmp(scenario, "thread_without_handler") == 0) { + bool result; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_helper_start(); + zend_test_forward_send(ZEND_TEST_FORWARD_RAISE); + result = zend_test_forward_wait(&zend_test_forward_main_hits); + zend_test_forward_helper_exit(); + return result; + } + + if (strcmp(scenario, "concurrent_registration") == 0) { + pthread_t workers[ZEND_TEST_FORWARD_WORKERS], storm; + + zend_atomic_bool_store(&zend_test_forward_stop, false); + pthread_create(&storm, NULL, zend_test_forward_storm_main, NULL); + for (int i = 0; i < ZEND_TEST_FORWARD_WORKERS; i++) { + pthread_create(&workers[i], NULL, zend_test_forward_worker_main, NULL); + } + for (int i = 0; i < ZEND_TEST_FORWARD_WORKERS; i++) { + pthread_join(workers[i], NULL); + } + zend_atomic_bool_store(&zend_test_forward_stop, true); + pthread_join(storm, NULL); + + zend_atomic_int_store(&zend_test_forward_main_hits, 0); + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_raise_foreign(); + return zend_test_forward_wait(&zend_test_forward_main_hits); + } + + if (strcmp(scenario, "timer_owner") == 0) { + bool result; + + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_raise_foreign(); + result = zend_test_forward_wait(&zend_test_forward_main_hits); + zend_signal_forward_timer_disarm(); + return result; + } + + if (strcmp(scenario, "handler_outranks_timer") == 0) { + bool result; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_helper_start(); + zend_test_forward_send(ZEND_TEST_FORWARD_RECORD_TIMER); + zend_test_forward_raise_foreign(); + result = zend_test_forward_wait(&zend_test_forward_main_hits); + zend_test_forward_helper_exit(); + return result; + } + + if (strcmp(scenario, "stale_timer") == 0) { + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_timer_disarm(); + zend_atomic_bool_store(&zend_test_forward_result, false); + zend_test_forward_raise_foreign(); + /* The signal is consumed, and reaches nobody. */ + return zend_atomic_bool_load(&zend_test_forward_result) + && zend_atomic_int_load(&zend_test_forward_main_hits) == 0; + } + + if (strcmp(scenario, "repeated_signals") == 0) { + sigset_t block, old; + bool result; + + sigemptyset(&block); + sigaddset(&block, ZEND_TEST_FORWARD_SIGNAL); + pthread_sigmask(SIG_BLOCK, &block, &old); + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + for (int i = 0; i < 100; i++) { + zend_test_forward_raise_foreign(); + } + result = zend_test_forward_wait_pending(); + pthread_sigmask(SIG_SETMASK, &old, NULL); + result = zend_test_forward_wait(&zend_test_forward_main_hits) && result; + /* Repeated signals coalesce. */ + return result && zend_atomic_int_load(&zend_test_forward_main_hits) < 100; + } + + if (strcmp(scenario, "replaced_handler") == 0) { + struct sigaction replacement; + sigset_t block, old; + bool result; + + sigemptyset(&block); + sigaddset(&block, ZEND_TEST_FORWARD_SIGNAL); + pthread_sigmask(SIG_BLOCK, &block, &old); + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_raise_foreign(); + result = zend_test_forward_wait_pending(); + + memset(&replacement, 0, sizeof(replacement)); + replacement.sa_handler = zend_test_forward_replacement_handler; + sigfillset(&replacement.sa_mask); + sigaction(ZEND_TEST_FORWARD_SIGNAL, &replacement, NULL); + pthread_sigmask(SIG_SETMASK, &old, NULL); + + return zend_test_forward_wait(&zend_test_forward_replacement_hits) && result + && zend_atomic_int_load(&zend_test_forward_main_hits) == 0; + } + + if (strcmp(scenario, "owner_exit_with_pending_signal") == 0) { + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_helper_start(); + zend_test_forward_send(ZEND_TEST_FORWARD_BLOCK); + zend_test_forward_send(ZEND_TEST_FORWARD_RECORD); + zend_test_forward_raise_foreign(); + zend_test_forward_send(ZEND_TEST_FORWARD_WAIT_PENDING); + zend_test_forward_helper_exit(); + return zend_test_forward_wait(&zend_test_forward_main_hits); + } + + if (strcmp(scenario, "blocked_owner_no_failover") == 0) { + sigset_t block, previous; + bool result; + + /* Another thread handles the signal too, but the owner registered last. */ + zend_test_forward_helper_start(); + zend_test_forward_send(ZEND_TEST_FORWARD_RECORD); + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + + /* The signal waits for the owner, as it would for a thread that received it directly. */ + sigemptyset(&block); + sigaddset(&block, ZEND_TEST_FORWARD_SIGNAL); + pthread_sigmask(SIG_BLOCK, &block, &previous); + zend_test_forward_raise_foreign(); + result = zend_test_forward_wait_pending(); + usleep(100000); + result = result && zend_atomic_int_load(&zend_test_forward_main_hits) == 0 + && zend_atomic_int_load(&zend_test_forward_helper_hits) == 0; + pthread_sigmask(SIG_SETMASK, &previous, NULL); + + result = zend_test_forward_wait(&zend_test_forward_main_hits) && result; + zend_test_forward_helper_exit(); + return result && zend_atomic_int_load(&zend_test_forward_helper_hits) == 0; + } + + if (strcmp(scenario, "thread_identifier_reuse") == 0) { + pthread_t storm; + + zend_atomic_bool_store(&zend_test_forward_stop, false); + pthread_create(&storm, NULL, zend_test_forward_storm_main, NULL); + for (int i = 0; i < 500; i++) { + pthread_t thread; + + pthread_create(&thread, NULL, zend_test_forward_short_lived_main, NULL); + pthread_join(thread, NULL); + } + zend_atomic_bool_store(&zend_test_forward_stop, true); + pthread_join(storm, NULL); + + zend_atomic_int_store(&zend_test_forward_main_hits, 0); + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_raise_foreign(); + return zend_test_forward_wait(&zend_test_forward_main_hits); + } + + if (strcmp(scenario, "fork_during_registration") == 0) { + pthread_t workers[ZEND_TEST_FORWARD_WORKERS]; + bool result = true; + + zend_atomic_bool_store(&zend_test_forward_stop, false); + for (int i = 0; i < ZEND_TEST_FORWARD_WORKERS; i++) { + pthread_create(&workers[i], NULL, zend_test_forward_churn_main, NULL); + } + for (int i = 0; i < 50 && result; i++) { + result = zend_test_forward_fork_and_check(); + } + zend_atomic_bool_store(&zend_test_forward_stop, true); + for (int i = 0; i < ZEND_TEST_FORWARD_WORKERS; i++) { + pthread_join(workers[i], NULL); + } + return result; + } + + if (strcmp(scenario, "fork_during_notification") == 0) { + pthread_t storm; + bool result = true; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_atomic_bool_store(&zend_test_forward_stop, false); + pthread_create(&storm, NULL, zend_test_forward_storm_main, NULL); + for (int i = 0; i < 50 && result; i++) { + result = zend_test_forward_fork_and_check(); + } + zend_atomic_bool_store(&zend_test_forward_stop, true); + pthread_join(storm, NULL); + return result; + } + + if (strcmp(scenario, "repeated_fork") == 0) { + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + return zend_test_forward_fork_chain(3); + } + + if (strcmp(scenario, "timer_not_inherited") == 0) { + pid_t pid; + bool result; + + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, NULL); + pid = fork(); + if (pid == 0) { + zend_test_forward_main = pthread_self(); + zend_signal_forward_fork_child(false); + zend_atomic_bool_store(&zend_test_forward_result, true); + zend_test_forward_raise_foreign(); + _exit(!zend_atomic_bool_load(&zend_test_forward_result) + && zend_atomic_int_load(&zend_test_forward_main_hits) == 0 ? 0 : 1); + } + result = pid > 0 && zend_test_forward_wait_child(pid); + zend_signal_forward_timer_disarm(); + return result; + } + + if (strcmp(scenario, "fork") == 0) { + pid_t pid; + int status = 0; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_helper_start(); + zend_test_forward_send(ZEND_TEST_FORWARD_RECORD); + + pid = fork(); + if (pid == 0) { + zend_signal_forward_fork_child(false); + zend_atomic_bool_store(&zend_test_forward_helper_set, false); + zend_test_forward_raise_foreign(); + _exit(zend_test_forward_wait(&zend_test_forward_main_hits) ? 0 : 1); + } + + waitpid(pid, &status, 0); + zend_test_forward_helper_exit(); + return pid > 0 && WIFEXITED(status) && WEXITSTATUS(status) == 0; + } + +#if ZEND_DEBUG + if (strcmp(scenario, "handler_stalled_across_helper_exit") == 0) { + pthread_t raiser; + time_t start = time(NULL); + bool stopped = false; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_STALL_HANDLER); + pthread_create(&raiser, NULL, zend_test_forward_raise_main, NULL); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_WAIT_STALLED); + + /* The helper exits after the handler checked that it runs, and cannot start again. */ + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_FAIL_PIPE); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_FAIL_READ); + zend_test_forward_raise_foreign(); + while (!stopped && time(NULL) - start < 30) { + stopped = zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RUNNING) == 0; + usleep(1000); + } + stopped = zend_test_forward_wait(&zend_test_forward_main_hits) && stopped; + + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RESUME_HANDLER); + pthread_join(raiser, NULL); + + /* Not reported as forwarded, and not delivered to the next helper either. */ + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + usleep(100000); + return stopped && !zend_atomic_bool_load(&zend_test_forward_result) + && zend_atomic_int_load(&zend_test_forward_main_hits) == 1; + } + + if (strcmp(scenario, "fork_inherited_handler") == 0) { + struct sigaction handler, timer; + pid_t pid; + + memset(&handler, 0, sizeof(handler)); + handler.sa_handler = zend_test_forward_handler; + sigemptyset(&handler.sa_mask); + memset(&timer, 0, sizeof(timer)); + timer.sa_handler = zend_test_forward_replacement_handler; + sigemptyset(&timer.sa_mask); + + /* The thread that handles the signal does not exist in the child. */ + zend_test_forward_helper_start(); + zend_test_forward_send(ZEND_TEST_FORWARD_RECORD); + sigaction(ZEND_TEST_FORWARD_SIGNAL, &handler, NULL); + pid = fork(); + if (pid == 0) { + struct sigaction current; + pid_t grandchild; + int status = 1; + + zend_signal_forward_fork_child(false); + /* It stays orphaned in the child of this child. */ + grandchild = fork(); + if (grandchild == 0) { + zend_signal_forward_fork_child(false); + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, &timer); + sigaction(ZEND_TEST_FORWARD_SIGNAL, NULL, ¤t); + _exit(current.sa_handler == zend_test_forward_replacement_handler ? 0 : 1); + } + waitpid(grandchild, &status, 0); + if (grandchild < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) { + _exit(1); + } + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, &timer); + sigaction(ZEND_TEST_FORWARD_SIGNAL, NULL, ¤t); + if (current.sa_handler != zend_test_forward_replacement_handler) { + _exit(1); + } + zend_signal_forward_timer_disarm(); + + /* A handler that something else installed afterwards is not that handler. */ + sigaction(ZEND_TEST_FORWARD_SIGNAL, &handler, NULL); + handler.sa_handler = zend_test_forward_exit_marker; + sigaction(ZEND_TEST_FORWARD_SIGNAL, &handler, NULL); + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, &timer); + sigaction(ZEND_TEST_FORWARD_SIGNAL, NULL, ¤t); + _exit(current.sa_handler == zend_test_forward_exit_marker ? 0 : 1); + } + zend_test_forward_helper_exit(); + return pid > 0 && zend_test_forward_wait_child(pid); + } + + if (strcmp(scenario, "handler_stalled_across_rearm") == 0) { + pthread_t raiser; + bool result; + + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_HOLD); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_STALL_HANDLER); + pthread_create(&raiser, NULL, zend_test_forward_raise_main, NULL); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_WAIT_STALLED); + + /* The new timer expires while a handler of the old one is still running. */ + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_raise_foreign(); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RESUME_HANDLER); + pthread_join(raiser, NULL); + + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RELEASE); + result = zend_test_forward_wait(&zend_test_forward_main_hits); + zend_signal_forward_timer_disarm(); + return result; + } + + if (strcmp(scenario, "fork_with_pending_flag") == 0) { + pid_t pid; + bool result; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_HOLD); + zend_test_forward_raise_foreign(); + pid = fork(); + if (pid == 0) { + /* That signal was sent to the parent. */ + zend_test_forward_main = pthread_self(); + zend_atomic_int_store(&zend_test_forward_main_hits, 0); + zend_signal_forward_fork_child(false); + usleep(200000); + _exit(zend_atomic_int_load(&zend_test_forward_main_hits) == 0 ? 0 : 1); + } + result = pid > 0 && zend_test_forward_wait_child(pid); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RELEASE); + return zend_test_forward_wait(&zend_test_forward_main_hits) && result; + } + + if (strcmp(scenario, "saturation_storm") == 0) { + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + for (int round = 0; round < 20; round++) { + pthread_t raisers[ZEND_TEST_FORWARD_WORKERS]; + + zend_atomic_int_store(&zend_test_forward_main_hits, 0); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_HOLD); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_SATURATE); + for (int i = 0; i < ZEND_TEST_FORWARD_WORKERS; i++) { + pthread_create(&raisers[i], NULL, zend_test_forward_raise_main, NULL); + } + for (int i = 0; i < ZEND_TEST_FORWARD_WORKERS; i++) { + pthread_join(raisers[i], NULL); + } + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RELEASE); + if (!zend_test_forward_wait(&zend_test_forward_main_hits)) { + return false; + } + } + return true; + } + + if (strcmp(scenario, "timer_keeps_handler") == 0) { + struct sigaction handler, timer, current; + pthread_t installer; + bool result; + + memset(&handler, 0, sizeof(handler)); + handler.sa_handler = zend_test_forward_handler; + sigemptyset(&handler.sa_mask); + memset(&timer, 0, sizeof(timer)); + timer.sa_handler = zend_test_forward_replacement_handler; + sigemptyset(&timer.sa_mask); + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, &handler); + zend_signal_forward_timer_install(ZEND_TEST_FORWARD_SIGNAL, &timer); + sigaction(ZEND_TEST_FORWARD_SIGNAL, NULL, ¤t); + result = current.sa_handler == zend_test_forward_handler; + + zend_signal_forward_release(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_timer_install(ZEND_TEST_FORWARD_SIGNAL, &timer); + sigaction(ZEND_TEST_FORWARD_SIGNAL, NULL, ¤t); + result = result && current.sa_handler == zend_test_forward_replacement_handler; + + /* The disposition only changes under the mutex. */ + sigaction(ZEND_TEST_FORWARD_SIGNAL, &handler, NULL); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_LOCK); + pthread_create(&installer, NULL, zend_test_forward_timer_install_main, &timer); + usleep(100000); + sigaction(ZEND_TEST_FORWARD_SIGNAL, NULL, ¤t); + result = result && current.sa_handler == zend_test_forward_handler; + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_UNLOCK); + pthread_join(installer, NULL); + sigaction(ZEND_TEST_FORWARD_SIGNAL, NULL, ¤t); + return result && current.sa_handler == zend_test_forward_replacement_handler; + } + + if (strcmp(scenario, "timer_arm_disposition") == 0) { + struct sigaction timer, other, current; + bool result; + + memset(&timer, 0, sizeof(timer)); + timer.sa_handler = zend_test_forward_replacement_handler; + sigemptyset(&timer.sa_mask); + memset(&other, 0, sizeof(other)); + other.sa_handler = SIG_DFL; + sigemptyset(&other.sa_mask); + + /* A running timer must not meet the default action. */ + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_release(ZEND_TEST_FORWARD_SIGNAL, &other); + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, &timer); + sigaction(ZEND_TEST_FORWARD_SIGNAL, NULL, ¤t); + result = current.sa_handler == zend_test_forward_replacement_handler; + zend_signal_forward_timer_disarm(); + + /* A handler that something else installed stays. */ + other.sa_handler = zend_test_forward_handler; + sigaction(ZEND_TEST_FORWARD_SIGNAL, &other, NULL); + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, &timer); + sigaction(ZEND_TEST_FORWARD_SIGNAL, NULL, ¤t); + result = result && current.sa_handler == zend_test_forward_handler; + zend_signal_forward_timer_disarm(); + + /* So does a signal that this thread ignores. */ + other.sa_handler = SIG_IGN; + zend_signal_forward_release(ZEND_TEST_FORWARD_SIGNAL, &other); + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, &timer); + sigaction(ZEND_TEST_FORWARD_SIGNAL, NULL, ¤t); + zend_signal_forward_timer_disarm(); + return result && current.sa_handler == SIG_IGN; + } + + if (strcmp(scenario, "register_during_thread_exit") == 0) { + pthread_t thread; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + pthread_key_create(&zend_test_forward_exit_key, zend_test_forward_exit_destructor); + pthread_create(&thread, NULL, zend_test_forward_exit_main, NULL); + pthread_join(thread, NULL); + pthread_key_delete(zend_test_forward_exit_key); + + /* No record may be left of the thread that registered while it exited. */ + zend_test_forward_raise_foreign(); + return zend_test_forward_wait(&zend_test_forward_main_hits); + } + + if (strcmp(scenario, "helper_start_failure") == 0) { + pid_t pid; + bool result; + + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RESTART); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_FAIL_CREATE); + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + result = zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RUNNING) == 0 + && zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_PID) == 0; + + /* Without a helper, a signal is not reported as forwarded. */ + zend_atomic_bool_store(&zend_test_forward_result, true); + zend_test_forward_raise_foreign(); + result = result && !zend_atomic_bool_load(&zend_test_forward_result); + + /* The next registration starts over. */ + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_raise_foreign(); + result = zend_test_forward_wait(&zend_test_forward_main_hits) && result; + + pid = fork(); + if (pid == 0) { + bool running; + + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_FAIL_PIPE); + zend_signal_forward_fork_child(false); + running = zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RUNNING) == 1; + _exit(!running && zend_test_forward_child_delivers() ? 0 : 1); + } + return pid > 0 && zend_test_forward_wait_child(pid) && result; + } + + if (strcmp(scenario, "init_failure") == 0) { + struct sigaction current; + pid_t pid; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + pid = fork(); + if (pid == 0) { + bool handled; + + zend_test_forward_main = pthread_self(); + zend_atomic_int_store(&zend_test_forward_main_hits, 0); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_FAIL_INIT); + zend_signal_forward_fork_child(false); + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_atomic_bool_store(&zend_test_forward_result, true); + zend_test_forward_raise_foreign(); + usleep(100000); + /* A handler stays in place, including one registered after the failure. */ + memset(¤t, 0, sizeof(current)); + current.sa_handler = zend_test_forward_handler; + sigemptyset(¤t.sa_mask); + zend_signal_forward_acquire(SIGWINCH, ¤t); + zend_signal_forward_or_default(SIGWINCH); + zend_signal_forward_or_default(ZEND_TEST_FORWARD_SIGNAL); + sigaction(SIGWINCH, NULL, ¤t); + handled = current.sa_handler == zend_test_forward_handler; + sigaction(ZEND_TEST_FORWARD_SIGNAL, NULL, ¤t); + _exit(handled && !zend_atomic_bool_load(&zend_test_forward_result) + && current.sa_handler == zend_test_forward_handler + && zend_atomic_int_load(&zend_test_forward_main_hits) == 0 ? 0 : 1); + } + return pid > 0 && zend_test_forward_wait_child(pid); + } + + if (strcmp(scenario, "pipe_saturation") == 0) { + bool result; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_HOLD); + result = zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_SATURATE) == 1; + zend_test_forward_raise_foreign(); + result = zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_HANDLER_EAGAIN) == 1 && result; + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RELEASE); + result = zend_test_forward_wait(&zend_test_forward_main_hits) && result; + usleep(100000); + return result && zend_atomic_int_load(&zend_test_forward_main_hits) == 1; + } + + if (strcmp(scenario, "read_failure_keeps_signal") == 0) { + time_t start = time(NULL); + bool replaced = false; + int write_fd; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + write_fd = zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_WRITE_FD); + /* The read that fails comes before the notification of this signal is read. */ + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_HOLD); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_FAIL_READ); + zend_test_forward_raise_foreign(); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RELEASE); + if (!zend_test_forward_wait(&zend_test_forward_main_hits)) { + return false; + } + while (!replaced && time(NULL) - start < 30) { + replaced = zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RUNNING) == 1 + && zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_WRITE_FD) != write_fd; + usleep(1000); + } + + /* Forwarding goes on without a new registration. */ + zend_atomic_int_store(&zend_test_forward_main_hits, 0); + zend_test_forward_raise_foreign(); + return zend_test_forward_wait(&zend_test_forward_main_hits) && replaced; + } + + if (strcmp(scenario, "helper_suspended") == 0) { + bool result; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_suspend(); + result = zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RUNNING) == 0; + + /* A signal meanwhile waits for the helper. */ + zend_atomic_bool_store(&zend_test_forward_result, false); + zend_test_forward_raise_foreign(); + usleep(100000); + result = result && zend_atomic_bool_load(&zend_test_forward_result) + && zend_atomic_int_load(&zend_test_forward_main_hits) == 0; + + zend_signal_forward_resume(); + result = zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RUNNING) == 1 && result; + return zend_test_forward_wait(&zend_test_forward_main_hits) && result; + } + + if (strcmp(scenario, "stale_timer_after_grace") == 0) { + time_t start; + + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_HOLD); + zend_test_forward_raise_foreign(); + zend_signal_forward_timer_disarm(); + for (start = time(NULL); time(NULL) - start < 4; usleep(10000)); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RELEASE); + usleep(200000); + return zend_atomic_int_load(&zend_test_forward_main_hits) == 0; + } + + if (strcmp(scenario, "rearmed_timer") == 0) { + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_HOLD); + zend_test_forward_raise_foreign(); + zend_signal_forward_timer_arm(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RELEASE); + usleep(200000); + zend_signal_forward_timer_disarm(); + return zend_atomic_int_load(&zend_test_forward_main_hits) == 0; + } + + if (strcmp(scenario, "exit_during_forwarding") == 0) { + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_helper_start(); + zend_test_forward_send(ZEND_TEST_FORWARD_RECORD); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_HOLD); + zend_test_forward_raise_foreign(); + zend_test_forward_helper_exit(); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RELEASE); + return zend_test_forward_wait(&zend_test_forward_main_hits) + && zend_atomic_int_load(&zend_test_forward_helper_hits) == 0; + } + + if (strcmp(scenario, "concurrent_unregistration") == 0) { + pthread_t storm, workers[ZEND_TEST_FORWARD_WORKERS]; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_atomic_bool_store(&zend_test_forward_stop, false); + pthread_create(&storm, NULL, zend_test_forward_storm_main, NULL); + for (int i = 0; i < ZEND_TEST_FORWARD_WORKERS; i++) { + pthread_create(&workers[i], NULL, zend_test_forward_churn_main, NULL); + } + for (int i = 0; i < 300; i++) { + pthread_t thread; + + pthread_create(&thread, NULL, zend_test_forward_short_lived_main, NULL); + pthread_join(thread, NULL); + } + zend_atomic_bool_store(&zend_test_forward_stop, true); + for (int i = 0; i < ZEND_TEST_FORWARD_WORKERS; i++) { + pthread_join(workers[i], NULL); + } + pthread_join(storm, NULL); + + zend_atomic_int_store(&zend_test_forward_main_hits, 0); + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_raise_foreign(); + return zend_test_forward_wait(&zend_test_forward_main_hits); + } + + if (strcmp(scenario, "fork_while_held") == 0) { + bool result; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_HOLD); + /* The child inherits a locked mutex and a helper that does not exist there. */ + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_LOCK); + result = zend_test_forward_fork_and_check(); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_UNLOCK); + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RELEASE); + zend_test_forward_raise_foreign(); + return zend_test_forward_wait(&zend_test_forward_main_hits) && result; + } + + if (strcmp(scenario, "helper_restart") == 0) { + for (int i = 0; i < 4; i++) { + zend_atomic_int_store(&zend_test_forward_main_hits, 0); + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + zend_test_forward_raise_foreign(); + if (!zend_test_forward_wait(&zend_test_forward_main_hits)) { + return false; + } + zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_RESTART); + } + return true; + } + + if (strcmp(scenario, "closed_stdio") == 0) { + pid_t pid; + + zend_signal_forward_acquire(ZEND_TEST_FORWARD_SIGNAL, NULL); + pid = fork(); + if (pid == 0) { + bool result; + + close(0); + close(1); + close(2); + result = zend_test_forward_child_delivers(); + _exit(result && zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_READ_FD) > 2 + && zend_signal_forward_test(ZEND_SIGNAL_FORWARD_TEST_WRITE_FD) > 2 ? 0 : 1); + } + return pid > 0 && zend_test_forward_wait_child(pid); + } +#endif + + zend_throw_error(NULL, "Unknown scenario"); + return false; +} + +bool zend_test_signal_forwarding_run(const char *scenario) +{ + struct sigaction action, previous; + bool result; + + if (strcmp(scenario, "supported") == 0) { +#ifdef ZEND_SIGNAL_FORWARD_ENABLED + return true; +#else + return false; +#endif + } + + zend_test_forward_main = pthread_self(); + zend_atomic_int_store(&zend_test_forward_main_hits, 0); + zend_atomic_int_store(&zend_test_forward_helper_hits, 0); + zend_atomic_int_store(&zend_test_forward_replacement_hits, 0); + + memset(&action, 0, sizeof(action)); + action.sa_handler = zend_test_forward_handler; + action.sa_flags = SA_RESTART; + sigfillset(&action.sa_mask); + sigaction(ZEND_TEST_FORWARD_SIGNAL, &action, &previous); + + result = zend_test_forward_scenario(scenario); + + zend_signal_forward_release(ZEND_TEST_FORWARD_SIGNAL, NULL); + sigaction(ZEND_TEST_FORWARD_SIGNAL, &previous, NULL); + + return result; +} + +#endif diff --git a/ext/zend_test/signal_forwarding.h b/ext/zend_test/signal_forwarding.h new file mode 100644 index 000000000000..9919e94bef97 --- /dev/null +++ b/ext/zend_test/signal_forwarding.h @@ -0,0 +1,23 @@ +/* + +----------------------------------------------------------------------+ + | Copyright (c) The PHP Group | + +----------------------------------------------------------------------+ + | This source file is subject to version 3.01 of the PHP license, | + | that is bundled with this package in the file LICENSE, and is | + | available through the world-wide-web at the following url: | + | https://www.php.net/license/3_01.txt | + | If you did not receive a copy of the PHP license and are unable to | + | obtain it through the world-wide-web, please send a note to | + | license@php.net so we can mail you a copy immediately. | + +----------------------------------------------------------------------+ +*/ + +#ifndef ZEND_TEST_SIGNAL_FORWARDING_H +#define ZEND_TEST_SIGNAL_FORWARDING_H + +#include "php.h" + +bool zend_test_signal_forwarding_raise(int signo); +bool zend_test_signal_forwarding_run(const char *scenario); + +#endif diff --git a/ext/zend_test/test.c b/ext/zend_test/test.c index 4bd96976a965..06dc348d5947 100644 --- a/ext/zend_test/test.c +++ b/ext/zend_test/test.c @@ -41,6 +41,9 @@ #include "zend_system_id.h" #include "zend_mm_custom_handlers.h" #include +#if defined(ZTS) && !defined(PHP_WIN32) +# include "signal_forwarding.h" +#endif // `php.h` sets `NDEBUG` when not `PHP_DEBUG` which will make `assert()` from // assert.h a no-op. In order to have `assert()` working on NDEBUG builds, we @@ -783,6 +786,55 @@ static ZEND_FUNCTION(zend_test_raise_and_throw) zend_throw_exception(NULL, "Exception after raise()", 0); } +#if defined(ZTS) && !defined(PHP_WIN32) +/* Raises a signal on a thread that never ran PHP, where the OS may deliver a + * process-directed one (kill(), alarm()) too. */ +static ZEND_FUNCTION(zend_test_raise_on_foreign_thread) +{ + zend_long signo; + + ZEND_PARSE_PARAMETERS_START(1, 1) + Z_PARAM_LONG(signo) + ZEND_PARSE_PARAMETERS_END(); + + if (!zend_test_signal_forwarding_raise((int) signo)) { + zend_throw_error(NULL, "pthread_create() failed"); + RETURN_THROWS(); + } +} + +static ZEND_FUNCTION(zend_test_signal_forwarding) +{ + zend_string *scenario; + bool result; + + ZEND_PARSE_PARAMETERS_START(1, 1) + Z_PARAM_STR(scenario) + ZEND_PARSE_PARAMETERS_END(); + + result = zend_test_signal_forwarding_run(ZSTR_VAL(scenario)); + + if (EG(exception)) { + RETURN_THROWS(); + } + RETURN_BOOL(result); +} + +/* The signal of the execution timer, if it is process-wide. */ +static ZEND_FUNCTION(zend_test_timeout_signal) +{ + ZEND_PARSE_PARAMETERS_NONE(); + +#if defined(ZEND_MAX_EXECUTION_TIMERS) || !defined(HAVE_SETITIMER) + RETURN_NULL(); +#elif defined(__CYGWIN__) || defined(__PASE__) || (defined(__aarch64__) && defined(__APPLE__)) + RETURN_LONG(SIGALRM); +#else + RETURN_LONG(SIGPROF); +#endif +} +#endif + static bool has_opline(zend_execute_data *execute_data) { return execute_data diff --git a/ext/zend_test/test.stub.php b/ext/zend_test/test.stub.php index 785390dd70cc..7de0b83c1217 100644 --- a/ext/zend_test/test.stub.php +++ b/ext/zend_test/test.stub.php @@ -307,6 +307,14 @@ function zend_test_crash(?string $message = null): void {} function zend_test_raise_and_throw(int $signal): void {} +#if defined(ZTS) && !defined(PHP_WIN32) + function zend_test_raise_on_foreign_thread(int $signal): void {} + + function zend_test_signal_forwarding(string $scenario): bool {} + + function zend_test_timeout_signal(): ?int {} +#endif + function zend_test_fill_packed_array(array &$array): void {} /** @return resource */ diff --git a/ext/zend_test/test_arginfo.h b/ext/zend_test/test_arginfo.h index 45545edf5db8..665c64a976d8 100644 --- a/ext/zend_test/test_arginfo.h +++ b/ext/zend_test/test_arginfo.h @@ -1,5 +1,5 @@ /* This is a generated file, edit the .stub.php file instead. - * Stub hash: 20856900222b20ff71d57bf575ad7034ffc34bf4 */ + * Stub hash: 15d8c6232303394616d452b623132947154e59d7 */ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_array_return, 0, 0, IS_ARRAY, 0) ZEND_END_ARG_INFO() @@ -155,6 +155,19 @@ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_raise_and_throw, 0, 1, ZEND_ARG_TYPE_INFO(0, signal, IS_LONG, 0) ZEND_END_ARG_INFO() +#if defined(ZTS) && !defined(PHP_WIN32) +ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_raise_on_foreign_thread, 0, 1, IS_VOID, 0) + ZEND_ARG_TYPE_INFO(0, signal, IS_LONG, 0) +ZEND_END_ARG_INFO() + +ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_signal_forwarding, 0, 1, _IS_BOOL, 0) + ZEND_ARG_TYPE_INFO(0, scenario, IS_STRING, 0) +ZEND_END_ARG_INFO() + +ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_timeout_signal, 0, 0, IS_LONG, 1) +ZEND_END_ARG_INFO() +#endif + ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_zend_test_fill_packed_array, 0, 1, IS_VOID, 0) ZEND_ARG_TYPE_INFO(1, array, IS_ARRAY, 0) ZEND_END_ARG_INFO() @@ -336,6 +349,11 @@ static ZEND_FUNCTION(zend_test_is_string_marked_as_valid_utf8); static ZEND_FUNCTION(zend_get_map_ptr_last); static ZEND_FUNCTION(zend_test_crash); static ZEND_FUNCTION(zend_test_raise_and_throw); +#if defined(ZTS) && !defined(PHP_WIN32) +static ZEND_FUNCTION(zend_test_raise_on_foreign_thread); +static ZEND_FUNCTION(zend_test_signal_forwarding); +static ZEND_FUNCTION(zend_test_timeout_signal); +#endif static ZEND_FUNCTION(zend_test_fill_packed_array); static ZEND_FUNCTION(zend_test_create_throwing_resource); static ZEND_FUNCTION(get_open_basedir); @@ -452,6 +470,11 @@ static const zend_function_entry ext_functions[] = { ZEND_FE(zend_get_map_ptr_last, arginfo_zend_get_map_ptr_last) ZEND_FE(zend_test_crash, arginfo_zend_test_crash) ZEND_FE(zend_test_raise_and_throw, arginfo_zend_test_raise_and_throw) +#if defined(ZTS) && !defined(PHP_WIN32) + ZEND_FE(zend_test_raise_on_foreign_thread, arginfo_zend_test_raise_on_foreign_thread) + ZEND_FE(zend_test_signal_forwarding, arginfo_zend_test_signal_forwarding) + ZEND_FE(zend_test_timeout_signal, arginfo_zend_test_timeout_signal) +#endif ZEND_FE(zend_test_fill_packed_array, arginfo_zend_test_fill_packed_array) ZEND_FE(zend_test_create_throwing_resource, arginfo_zend_test_create_throwing_resource) ZEND_FE(get_open_basedir, arginfo_get_open_basedir) diff --git a/ext/zend_test/tests/signal_forwarding.phpt b/ext/zend_test/tests/signal_forwarding.phpt new file mode 100644 index 000000000000..08b3156fa758 --- /dev/null +++ b/ext/zend_test/tests/signal_forwarding.phpt @@ -0,0 +1,60 @@ +--TEST-- +Forwarding a signal to the thread that handles it (GH-25541, GH-25549) +--EXTENSIONS-- +zend_test +--SKIPIF-- + +--FILE-- + +--EXPECT-- +unmanaged: bool(true) +successor: bool(true) +most_recent_owner: bool(true) +owner_exit: bool(true) +last_owner_exit: bool(true) +thread_without_handler: bool(true) +concurrent_registration: bool(true) +timer_owner: bool(true) +handler_outranks_timer: bool(true) +stale_timer: bool(true) +repeated_signals: bool(true) +replaced_handler: bool(true) +owner_exit_with_pending_signal: bool(true) +blocked_owner_no_failover: bool(true) +thread_identifier_reuse: bool(true) +fork: bool(true) +fork_during_registration: bool(true) +fork_during_notification: bool(true) +repeated_fork: bool(true) +timer_not_inherited: bool(true) diff --git a/ext/zend_test/tests/signal_forwarding_debug.phpt b/ext/zend_test/tests/signal_forwarding_debug.phpt new file mode 100644 index 000000000000..d3f357f5920c --- /dev/null +++ b/ext/zend_test/tests/signal_forwarding_debug.phpt @@ -0,0 +1,63 @@ +--TEST-- +Forwarding a signal in states that depend on the timing of the helper thread +--EXTENSIONS-- +zend_test +--SKIPIF-- + +--INI-- +max_execution_time=0 +--FILE-- + +--EXPECT-- +pipe_saturation: bool(true) +read_failure_keeps_signal: bool(true) +helper_suspended: bool(true) +stale_timer_after_grace: bool(true) +rearmed_timer: bool(true) +exit_during_forwarding: bool(true) +concurrent_unregistration: bool(true) +fork_while_held: bool(true) +helper_restart: bool(true) +closed_stdio: bool(true) +handler_stalled_across_helper_exit: bool(true) +fork_inherited_handler: bool(true) +handler_stalled_across_rearm: bool(true) +fork_with_pending_flag: bool(true) +saturation_storm: bool(true) +timer_keeps_handler: bool(true) +timer_arm_disposition: bool(true) +register_during_thread_exit: bool(true) +helper_start_failure: bool(true) +init_failure: bool(true) diff --git a/ext/zend_test/tests/signal_forwarding_nts.phpt b/ext/zend_test/tests/signal_forwarding_nts.phpt new file mode 100644 index 000000000000..b11ec6d6b6f4 --- /dev/null +++ b/ext/zend_test/tests/signal_forwarding_nts.phpt @@ -0,0 +1,16 @@ +--TEST-- +Signal forwarding is compiled out without thread safety +--EXTENSIONS-- +zend_test +--SKIPIF-- + +--FILE-- + +--EXPECT-- +bool(false) +bool(false) diff --git a/main/main.c b/main/main.c index bc1725fa9bfd..c8b5ba518909 100644 --- a/main/main.c +++ b/main/main.c @@ -2029,6 +2029,10 @@ void php_request_shutdown(void *dummy) zend_set_memory_limit(PG(memory_limit)); /* 16. Deactivate Zend signals */ +#if defined(ZTS) && !defined(PHP_WIN32) + /* User code can no longer run, and this thread may exit after this request. */ + zend_signal_forward_request_shutdown(); +#endif #ifdef ZEND_SIGNALS zend_signal_deactivate(); #endif