CERT.STDLIB.SIGNAL

Returning from a computational exception signal handler for SIGFPE, SIGBUS, SIGSEGV, SIGILL, SIGEMT, or SIGTRAP results in undefined behavior.

The CERT.STDLIB.SIGNAL checker flags returns from a computational exception signal handler for SIGFPE, SIGBUS, SIGSEGV, SIGILL, SIGEMT, and SIGTRAP. This checker flags all calls to signal() with any of the specified signal types as being a defect. Therefore, this defect should be interpreted as meaning that the line of code should be reviewed, not that it is necessarily always a defect.

Vulnerability and risk

The behavior is undefined if the program returns from the computational exception signal handler.

Mitigation and prevention

Do not return from the signal handler if the signal is the result of a computational error such as SIGFPE, SIGBUS, SIGSEGV, SIGILL, SIGEMT or SIGTRAP.

Vulnerable code example

1     #include <errno.h>
2     #include <limits.h>
3     #include <signal.h>
4     #include <stdlib.h>
5
6     volatile sig_atomic_t denom;
7
8     void sighandle(int s)
9     {
10        if (denom == 0) {
11            denom = 1;
12        }
13    }
14
15    int main(int argc, char *argv[])
16    {
17        if (argc < 2) {
18            return 0;
19        }
20
21        char *end = NULL;
22        long temp = strtol(argv[1], &end, 10);
23
24        if (end == argv[1] || 0 != *end ||
25            ((LONG_MIN == temp || LONG_MAX == temp) && errno == ERANGE)) {
26            /* Handle error */
27        }
28
29        denom = (sig_atomic_t)temp;
30
31        signal(SIGFPE, sighandle);  
32
33        long result = 100 / (long)denom;
34        return 0;
35    }

In this noncompliant example, Klocwork reports a CERT.STDLIB.SIGNAL defect on Line 31, because the program is returning from the computational signal handler and the behavior is undefined. This noncompliant code example will loop infinitely if given the input 0 and the above program does not behave as expected even after using the signal handler (with signal SIGFPE) to fix the error condition.

Fixed code example

1     #include <errno.h>
2     #include <limits.h>
3     #include <signal.h>
4     #include <stdlib.h>
5
6     int main(int argc, char *argv[]) {
7       if (argc < 2) {
8         return 0;
9       }
10
11      char *end = NULL;
12      long denom = strtol(argv[1], &end, 10);
13
14      if (end == argv[1] || 0 != *end ||
15          ((LONG_MIN == denom || LONG_MAX == denom) && errno == ERANGE)) {
16        /* Handle error */
17      }
18
19      long result = 100 / denom;
20      return 0;
21    }

The above code is compliant because the program is not returning from the SIGFPE handler and instead is invoking the abort (), quick_exit(), or Exit function.

Related checkers

  • MISRA.STDLIB.SIGNAL

External guidance