server: global state updated by signal handlers should have a volatile sig_atomic_t type

Signal handlers currently violate both C language and POSIX requirements:
1. To avoid undefined behavior (UB), variables accessed or modified by
   signal handlers be of atomic lock-free type.
2. The respected variables should be marked as volatile.
3. Signal handlers may only call a very limited subset of standard
   library functions.
4. Additionally, POSIX restricts signal handlers to signal-safe
   functions.

This patch addresses the first two issues by changing the type of global
variables that are accessed inside signal handler to `sig_atomic_t` and
adding `volatile` qualifiers.

Items 3 and 4 must be handled separately but are outside the scope of
this change.

Change-Id: I9c344e87bab9eefe7d99b0aad300a3ef4712df51
Signed-off-by: Parshintsev Anatoly <anatoly.parshintsev@syntacore.com>
Reviewed-on: https://review.openocd.org/c/openocd/+/8927
Tested-by: jenkins
Reviewed-by: Antonio Borneo <borneo.antonio@gmail.com>
Reviewed-by: Chris Head <chead@zaber.com>
This commit is contained in:
Parshintsev Anatoly
2025-05-20 10:10:43 +03:00
committed by Antonio Borneo
parent 4e493229c6
commit 23ab2062e7

View File

@@ -43,10 +43,10 @@ enum shutdown_reason {
SHUTDOWN_WITH_ERROR_CODE, /* set by shutdown command; quit with non-zero return code */
SHUTDOWN_WITH_SIGNAL_CODE /* set by sig_handler; exec shutdown then exit with signal as return code */
};
static enum shutdown_reason shutdown_openocd = CONTINUE_MAIN_LOOP;
static volatile sig_atomic_t shutdown_openocd = CONTINUE_MAIN_LOOP;
/* store received signal to exit application by killing ourselves */
static int last_signal;
static volatile sig_atomic_t last_signal;
/* set the polling period to 100ms */
static int polling_period = 100;
@@ -604,6 +604,7 @@ static void sig_handler(int sig)
/* store only first signal that hits us */
if (shutdown_openocd == CONTINUE_MAIN_LOOP) {
shutdown_openocd = SHUTDOWN_WITH_SIGNAL_CODE;
assert(sig >= SIG_ATOMIC_MIN && sig <= SIG_ATOMIC_MAX);
last_signal = sig;
LOG_DEBUG("Terminating on Signal %d", sig);
} else