...
Note that on the Windows platform, attempts to delete open files fail silently. See rule FIO03-J. Remove temporary files before termination for more information.
Noncompliant Code Example (File Handle)
This noncompliant code example opens a file and uses it, but fails to explicitly close the file.
Code Block | ||
---|---|---|
| ||
public int processFile(String fileName) throws IOException, FileNotFoundException { FileInputStream stream = new FileInputStream(fileName); BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = bufRead.readLine()) != null) { sendLine(line); } return 1; } |
Compliant Solution
This compliant solution releases all acquired resources, regardless of any exceptions that might occur. Even though dereferencing bufRead
might result in an exception, the FileInputStream
object is closed as required (if created in the first place).
Code Block | ||
---|---|---|
| ||
try { final FileInputStream stream = new FileInputStream(fileName); try { final BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = bufRead.readLine()) != null) { sendLine(line); } } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // forward to handler } } } } catch (IOException e) { // forward to handler } |
Compliant Solution (Java 1.7, try-with-resources)
This compliant solution uses the try-with-resources statement, introduced in Java 1.7, to release all acquired resources, regardless of any exceptions that might occur.
...
The try-with-resource construct sends any IOException
to the catch
clause, where it is forwarded to an exception handler. This includes exceptions generated during the allocation of resources (that is, the creation of the FileInputStream
or BufferedReader
. It also includes any IOException
thrown during the while loop. Finally, it includes any IOException
generated by closing bufRead
or stream
.
Noncompliant Code Example (SQL Connection)
The problem of resource pool exhaustion is exacerbated in the case of database connections. Many database servers allow only a fixed number of connections, depending on configuration and licensing. Consequently, failure to release database connections can result in rapid exhaustion of available connections. This noncompliant code example fails to close the connection when an error occurs during execution of the SQL statement or during processing of the results.
Code Block | ||
---|---|---|
| ||
public void getResults(String sqlQuery) { try { Connection conn = getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sqlQuery); processResults(rs); stmt.close(); } catch (SQLException e) { /* forward to handler */ } } |
Noncompliant Code Example
This noncompliant code example attempts to address exhaustion of database connections by adding clean-up code in a finally block. However, either or both of rs
and stmt
could be null
, causing the code in the finally block to throw a NullPointerException
.
Code Block | ||
---|---|---|
| ||
Statement stmt = null; ResultSet rs = null Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch(SQLException e) { // forward to handler } finally { rs.close(); stmt.close(); } |
Noncompliant Code Example
In this noncompliant code example, the call to rs.close()
might throw a SQLException
. Consequently, stmt.close()
is never called. This is a violation of ERR05-J. Do not let checked exceptions escape from a finally block.
Code Block | ||
---|---|---|
| ||
Statement stmt = null; ResultSet rs = null; Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch (SQLException e) { // forward to handler } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } |
Compliant Solution
This compliant solution ensures that resources are released as required.
Code Block | ||
---|---|---|
| ||
Statement stmt = null; ResultSet rs = null; Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch (SQLException e) { // forward to handler } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { // forward to handler } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { // forward to handler } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { // forward to handler } } } } } } |
Compliant Solution (Java 1.7, try-with-resources)
This compliant solution uses the try-with-resource construct, introduced in Java 1.7, to ensure that resources are released as required.
...
The try-with-resource construct sends any SQLException
to the catch
clause, where it gets forwarded to an exception handler. This includes exceptions generated during the allocation of resources (that is, the creation of the Connection
, Statement
, or ResultSet
). It also includes any SQLException
thrown by processResults()
. Finally, it includes any SQLException
generated by closing rs
, stmt
, or conn
.
Risk Assessment
Failure to explicitly release non-memory system resources when they are no longer needed can result in resource exhaustion.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FIO06-J | low | probable | medium | P4 | L3 |
Automated Detection
Although sound automated detection of this vulnerability is not feasible in the general case, many interesting cases can be soundly detected.
The Coverity Prevent Version 5.0 RESOURCE_LEAK checker can detect instances where there is leak of a socket resource or leak of a stream representing a file or other system resources.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
FIO42-C. Ensure files are properly closed when they are no longer needed | |
FIO42-CPP. Ensure files are properly closed when they are no longer needed | |
CWE-404 "Improper Resource Shutdown or Release" | |
| CWE-459 "Incomplete Cleanup" |
| CWE-770 "Allocation of Resources Without Limits or Throttling" |
| CWE-405 "Asymmetric Resource Consumption (Amplification)" |
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="918c5e80bbbf79df-4af5e91c-446346b1-b8fc8091-fa985867b7c333ddd39f91a0"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. Bibliography#API 06]] | [Class Object | http://java.sun.com/javase/6/docs/api/java/lang/Object.html] | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="98a276fd9beaa21d-e0346af0-4f3c48c4-8684a8ae-82053289d45e536e49edc99c"><ac:plain-text-body><![CDATA[ | [[Goetz 2006b | AA. Bibliography#Goetz 06b]] |
| ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="80538e4fc4ab87aa-00a82106-425d4105-a64696c6-bce0df7bffef890a0d4319a7"><ac:plain-text-body><![CDATA[ | [[J2SE 2011 | AA. Bibliography#J2SE 11]] | The try-with-resources Statement | ]]></ac:plain-text-body></ac:structured-macro> |
...