...
Java provides two options for program termination: Runtime.exit()
(this is equivalent to System.exit()
) and Runtime.halt()
.
Runtime.exit()
Runtime.exit() is the typical way of exiting a program:
...
The Runtime.addShutdownHook()
method can be used to customize Runtime.exit()
to perform additional actions at program termination.
This method takes a single Thread
, which must be initalized but unstarted. Then, when the JVM begins to shut down, the thread will be run. Since the JVM usually has a fixed time to shut down, these threads should not be long-running and should not attempt user interaction.
Runtime.halt()
Runtime.halt()
works similarly but does NOT run shutdown hooks or finalizers:
Forcibly terminates the currently running Java virtual machine. This method never returns normally.
This method should be used with extreme caution. Unlike the exit method, this method does not cause shutdown hooks to be started and does not run uninvoked finalizers if finalization-on-exit has been enabled. If the shutdown sequence has already been initiated then this method does not wait for any running shutdown hooks or finalizers to finish their work.
Differences from C/C++
In contrast with C and C++, Java does not flush unwritten buffered data or close open files when it exits, so programs must do this manually.
Risk Analysis
Using Runtime.halt()
in place of Runtime.exit()
may not perform necessary cleanup, potentially leaving sensitive data exposed or leaving data in an inconsistent state.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
ERR04-CPP | medium | low | medium | P4 | L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This rule appears in the C Secure Coding Standard as ERR04-C. Choose an appropriate termination strategy.
Bibliography
Wiki Markup |
---|
\[[ISO/IEC PDTR 24772|AA. Bibliography#ISO/IEC PDTR 24772]\] "REU Termination strategy" \[[MITRE 07|AA. Bibliography#MITRE 07]\] [CWE ID 705|http://cwe.mitre.org/data/definitions/705.html], "Incorrect Control Flow Scoping" |
...