Calling the signal()
function in a multithreaded program is undefined behavior according to C11 (Section the C Standard, subclause 7.14.1.1, paragraph 7 )[ISO/IEC 9899:2011].
This rule is a specific instance of SIG02-C. Avoid using signals to implement normal functionality.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <signal.h> #include <threads.h> volatile sig_atomic_t flag = 0; void handler(int signum) { flag = 1; } int func(void *data) { /* keepRuns running until user sends SIGUSR1. */ int func(void *data) { while (!flag) { /* ... */ } return 0; } int main(void) { signal(SIGUSR1, handler); /* Undefined! */ int result; thrd_t tid; if ((result = thrd_create(&tid, func, NULL)) != thrd_success) { /* Handle Error */ } /* ... */ return 0; } |
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdatomic.h> #include <threads.h> atomic_flag flag = ATOMIC_VAR_INIT(0); int func(void *data) { /* keep running until user sends SIGUSR1 */ while (!flag) { /* ... */ } return 0; } int main(void) { int result; thrd_t tid; if ((result = thrd_create(&tid, func, NULL)) != thrd_success) { /* Handle Error */ } /* ... */ /* Set flag when done. */ while (!atomic_flag_test_and_set( &flag)) { ; /* tryContinue againattempts. */ } return 0; } |
Exceptions
CON37:EX0-EX1: Platforms that provide defined behavior when multithreaded programs use custom signal handlers are exempt from this rule. This would include POSIX, for example.
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON37-C | low | probable | low | P6 | L2 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Bibliography
[ISO/IEC 9899:2011] | Subclause 7.14.1.1, "The signal function" |