Accessing or modifying shared objects in signal handlers can lead to race conditions, opening up security holes.
According to the C99 Rationale:
The C89 Committee concluded that about the only thing a strictly conforming program can do in a signal handler is to assign a value to a volatile static variable which can be written uninterruptedly and promptly return.
Non-Compliant Coding Example
err_msg is updated to reflect the SIGINT signal that was encountered. Issues will occur if a SIGINT is generated prior to the malloc of err_msg finishing.
| Code Block | ||
|---|---|---|
| ||
#include <signal.h>
char *err_msg;
void handler() {
strcpy(err_msg, "SIGSEGVSIGINT encountered.");
}
int main() {
signal(SIGSEGVSIGINT, handler);
err_msg = malloc(24);
strcpy(err_msg, "No errors yet.");
/* main code loop */
return 0;
}
|
Compliant Solution
Signal handlers
| Code Block | ||
|---|---|---|
| ||
#include <signal.h> char *err_msg; volatile static int e_flag = 0; void handler() { e_flag = 1; } int main() { signal(SIGSEGVSIGINT, handler); err_msg = malloc(24); strcpy(err_msg, "No errors yet."); /* main code loop */ if(e_flag) strcpy(err_msg, "SIGSEGVSIGINT received."); return 0; } |
Risk Assessment
...