From 23ab2062e7f0ae40b33abc6c5477388978f6dc48 Mon Sep 17 00:00:00 2001 From: Parshintsev Anatoly Date: Tue, 20 May 2025 10:10:43 +0300 Subject: [PATCH] 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 Reviewed-on: https://review.openocd.org/c/openocd/+/8927 Tested-by: jenkins Reviewed-by: Antonio Borneo Reviewed-by: Chris Head --- src/server/server.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/server/server.c b/src/server/server.c index 0649ec942..5f6bb584e 100644 --- a/src/server/server.c +++ b/src/server/server.c @@ -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