Some errors, such as a value out of range, might be the result of erroneous user input. If the input is interactive, the program can prompt the user for an acceptable value. With other errors, such as a resource allocation failure, the system may have little choice other but to shut down.
[[ISO/IEC PDTR 24772]] Section 6.47, "REU Termination strategy," says:
When a fault is detected, there are many ways in which a system can react. The quickest and most noticeable way is to fail hard, also known as fail fast or fail stop. The reaction to a detected fault is to immediately halt the system. Alternatively, the reaction to a detected fault could be to fail soft. The system would keep working with the faults present, but the performance of the system would be degraded. Systems used in a high availability environment such as telephone switching centers, e-commerce, etc. would likely use a fail soft approach. What is actually done in a fail soft approach can vary depending on whether the system is used for safety critical or security critical purposes. For fail safe systems, such as flight controllers, traffic signals, or medical monitoring systems, there would be no effort to meet normal operational requirements, but rather to limit the damage or danger caused by the fault. A system that fails securely, such as cryptologic systems, would maintain maximum security when a fault is detected, possibly through a denial of service.
And also:
The reaction to a fault in a system can depend on the criticality of the part in which the fault originates. When a program consists of several tasks, the tasks each may be critical, or not. If a task is critical, it may or may not be restartable by the rest of the program. Ideally, a task which detects a fault within itself should be able to halt leaving its resources available for use by the rest of the program, halt clearing away its resources, or halt the entire program. The latency of any such communication, and whether other tasks can ignore such a communication, should be clearly specified. Having inconsistent reactions to a fault, such as the fault reaction to a crypto fault, can potentially be a vulnerability.
C99 provides several options for program termination, including exit()
, returning from main()
, _Exit()
, and abort()
.
exit()
The C standard exit()
function is typically used to end a program. It takes one argument, which should be either EXIT_SUCCESS
or EXIT_FAILURE
indicating normal or abnormal termination. Zero is equally portable and well understood. C99 Section 7.20.4.3 says "If the value of status is zero or EXIT_SUCCESS
, an implementation-defined form of the status successful termination is returned." The exit()
function never returns.
#include <stdlib.h> /* ... */ if (/* something really bad happened */) { exit(EXIT_FAILURE); }
Calling exit()
- Flushes unwritten buffered data.
- Closes all open files.
- Removes temporary files.
- Returns an integer exit status to the operating system.
The C standard atexit()
function can be used to customize exit()
to perform additional actions at program termination.
For example, calling
atexit(turn_gizmo_off);
registers the turn_gizmo_off()
function so that a subsequent call to exit()
will invoke turn_gizmo_off()
as it terminates the program. C99 requires that atexit()
can register at least 32 functions.
Functions registered by the atexit()
function are called by exit()
or upon normal completion of main()
.
return
from main()
Because main()
is defined to have return type int
, another valid exit strategy is to simply use a return
statement.
int main(int argc, char **argv) { /* ... */ if (/* something really bad happened */) { return EXIT_FAILURE; } /* ... */ return EXIT_SUCCESS; }
C99, Section 5.1.2.2.3, has this to say about returning from main()
[[ISO/IEC 9899:1999]]:
If the return type of the
main
function is a type compatible withint
, a return from the initial call to themain
function is equivalent to calling theexit
function with the value returned by themain
function as its argument; reaching the}
that terminates themain
function returns a value of 0. If the return type is not compatible withint
, the termination status returned to the host environment is unspecified.
Consequently, returning from main()
is equivalent to calling exit()
. Many compilers implement this behavior with something analogous to
void _start(void) { /* ... */ exit(main(argc, argv)); }
However, exiting from main is conditional on correctly handling all errors in a way that does not force premature termination (see ERR00-C. Adopt and implement a consistent and comprehensive error-handling policy and ERR05-C. Application-independent code should provide error detection without dictating error handling).
_Exit()
A more abrupt function, _Exit()
also takes one argument and never returns. The standard specifies that _Exit()
also closes open file descriptors but does not specify whether _Exit()
flushes file buffers or deletes temporary files. Functions registered by atexit()
are not executed.
#include <stdlib.h> /* ... */ if (/* something really bad happened */) { _Exit(EXIT_FAILURE); }
The _exit()
function is a synonym for _Exit()
.
abort()
The quickest and most abrupt way to terminate a program, abort()
takes no arguments and always signifies abnormal termination to the operating system.
#include <stdlib.h> /* ... */ if (/* something really bad happened */) { abort(); }
The abort()
function causes abnormal program termination to occur, unless the signal SIGABRT
is caught and the signal handler does not return.
Whether open streams with unwritten buffered data are flushed, open streams are closed, or temporary files are removed is implementation-defined. Functions registered by atexit()
are not executed (see ERR06-C. Understand the termination behavior of assert() and abort()).
Summary
The table below summarizes the exit behavior of the program termination functions.
Function |
Closes file descriptors |
Flushes buffers |
Deletes temporary files |
Calls |
---|---|---|---|---|
|
unspecified |
unspecified |
unspecified |
no |
|
yes |
unspecified |
unspecified |
no |
|
yes |
yes |
yes |
yes |
return from |
yes |
yes |
yes |
yes |
Noncompliant Code Example
The abort()
function should not be called if it is important to perform application-specific cleanup before exiting. In this noncompliant code example, abort()
is called after data is sent to an open file descriptor. The data may or may not actually get written to the file.
#include <stdlib.h> #include <stdio.h> int write_data(void) { const char *filename = "hello.txt"; FILE *f = fopen(filename, "w"); if (f == NULL) { /* Handle error */ } fprintf(f, "Hello, World\n"); /* ... */ abort(); /* oops! data might not get written! */ /* ... */ return 0; } int main(void) { write_data(); return 0; }
Compliant Solution
In this compliant solution, the call to abort()
is replaced with exit()
, which guarantees that buffered I/O data is flushed to the file descriptor and the file descriptor is properly closed.
#include <stdlib.h> #include <stdio.h> int write_data(void) { const char *filename = "hello.txt"; FILE *f = fopen(filename, "w"); if (f == NULL) { /* Handle error */ } fprintf(f, "Hello, World\n"); /* ... */ exit(EXIT_FAILURE); /* writes data & closes f. */ /* ... */ return 0; } int main(void) { write_data(); return 0; }
While this particular example benefits from calling exit()
over abort()
, there will be situations where abort()
is the better choice. Usually this occurs when a programmer does not need to close any file descriptors or call any handlers registered with atexit()
, for instance, if the speed of terminating the program is critical.
For more details on proper usage of abort()
, see ERR06-C. Understand the termination behavior of assert() and abort().
Risk Analysis
Using abort()
or _Exit()
in place of exit()
may leave written files in an inconsistent state, and may also leave sensitive temporary files on the file system.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
ERR04-C |
medium |
probable |
high |
P4 |
L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[ISO/IEC 9899:1999]] Section 5.1.2.2.3, "Program termination," and Section 7.20.4, "Communication with the environment"
[[ISO/IEC PDTR 24772]] "REU Termination strategy"
[[MITRE 07]] CWE ID 705, "Incorrect Control Flow Scoping"
ERR03-C. Use runtime-constraint handlers when calling functions defined by TR24731-1 12. Error Handling (ERR)