CERT.EXIT.HANDLER_TERMINATE

Do not call an exit function from exit handler registered functions.

The CERT.EXIT.HANDLER_TERMINATE checker flags code that calls an exit function from an exit handler function. In addition to calling exit() and quick_exit(), this checker also flags calls to longjmp(), as specified by CERT rule ENV32-C.

Note that this checker will only flags cases where the exit handler and the call that installs it are in the same compilation unit.

Vulnerability and risk

Calling the exit function from an exit handler function that has further called any exit function can lead to a nested call, and a nested call to an exit function is an undefined behavior.

Mitigation and prevention

Ensure all exit handlers return normally.

Vulnerable code example

1    #include <stdlib.h>
2
3    void exit1(void)
4    {
5        return;
6   }
7
8    void exit2(void)
9    {
10       extern int some_condition;
11       if (some_condition) {
12           exit(0);
13       }
14       return;
15   }
16
17   int main(void)
18   {
19       if (atexit(exit1) != 0) {
20           /* Handle error */
21       }
22       if (atexit(exit2) != 0) {
23           /* Handle error */
24       }
25       return 0;
26   }		

This non-compliant code example flags defect CERT.EXIT.HANDLER_TERMINATE at Line 12 as exit is called from the exit handler function and the exit handler function ‘exit2’ is not returned normally.

Fixed code example

1   #include <stdlib.h>
2  
3   void exit1(void)
4   {
5       /* ... Cleanup code ... */
6       return;
7   }
8
9   void exit2(void)
10  {
11      extern int some_condition;
12      if (some_condition) {
13          /* ... More cleanup code ... */
14      }
15      return;
16  }
17
18  int main(void)
19  {
20      if (atexit(exit1) != 0) {
21          /* Handle error */
22      }
23      if (atexit(exit2) != 0) {
24          /* Handle error */
25      }
26      /* ... Program code ... */
27      return 0;
28  }
			

The problem from the previous snippet is fixed. In the compliant example above, both exit handler functions ‘exit1’ and ‘exit2’ are returning normally.

External guidance