-
Notifications
You must be signed in to change notification settings - Fork 2k
Java: Add new quality query to detect finalize calls
#19075
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
jcogs33
merged 22 commits into
github:main
from
jcogs33:jcogs33/java/do-not-use-finalizers
Apr 22, 2025
Merged
Changes from 18 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
56ea9b6
Java: move original files
9a6e241
Java: update to only find 'finalize' calls and add 'super.finalize' e…
d9482ae
Java: update tests to use inline expectations
c689a0e
Java: add more test cases
dd57d1a
Java: add quality tag
44445db
Java: minor refactor
2e25498
Java: add change note
f73eda0
Java: add previous-id and change 'use' to 'call'
ed22a16
Java: exclude overloads of finalize
3631df0
Java: add to code-quality suite
caf21a8
Java: update qhelp and add 'performace' tag
416643c
Java: update qhelp recommendation and example
e621f9f
Java: update comments in tests
c4b8396
fix typo in query description
jcogs33 1a2c34d
Java: update qhelp implementation notes for clarity
05d7b9a
Java: add reliability tag
0380279
Java: update qhelp implementation notes for more clarity
fc21abc
Java: update qhelp implementation notes to say 'method declarations'
798907d
Java: remove change note
2b91605
Apply docs review suggestion
jcogs33 72d49f2
Merge branch 'main' into jcogs33/java/do-not-use-finalizers
jcogs33 3aa6b49
Java: Add new query to java-code-quality.qls.expected
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
59 changes: 59 additions & 0 deletions
59
java/ql/src/Violations of Best Practice/Undesirable Calls/DoNotCallFinalize.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| ## Overview | ||
|
|
||
| Triggering garbage collection by directly calling `finalize()` may either have no effect or may trigger unnecessary garbage collection, leading to erratic behavior, performance issues, or deadlock. | ||
|
|
||
| ## Recommendation | ||
|
|
||
| Avoid calling `finalize()` in application code. Allow the JVM to determine a garbage collection schedule instead. If you need to explicitly release resources, provide a specific method to do so, such as by implementing the `AutoCloseable` interface and overriding its `close` method. You can then use a `try-with-resources` block to ensure that the resource is closed. | ||
|
|
||
| ## Example | ||
|
|
||
| ```java | ||
| class LocalCache { | ||
| private Collection<File> cacheFiles = ...; | ||
| // ... | ||
| } | ||
|
|
||
| void main() { | ||
| LocalCache cache = new LocalCache(); | ||
| // ... | ||
| cache.finalize(); // NON_COMPLIANT | ||
| } | ||
|
|
||
| ``` | ||
|
|
||
| ```java | ||
| import java.lang.AutoCloseable; | ||
| import java.lang.Override; | ||
|
|
||
| class LocalCache implements AutoCloseable { | ||
| private Collection<File> cacheFiles = ...; | ||
| // ... | ||
|
|
||
| @Override | ||
| public void close() throws Exception { | ||
| // release resources here if required | ||
| } | ||
| } | ||
|
|
||
| void main() { | ||
| // COMPLIANT: uses try-with-resources to ensure that | ||
| // a resource implementing AutoCloseable is closed. | ||
| try (LocalCache cache = new LocalCache()) { | ||
| // ... | ||
| } | ||
| } | ||
|
|
||
| ``` | ||
|
|
||
| # Implementation Notes | ||
|
|
||
| This rule ignores `super.finalize()` calls that occur within `finalize()` overrides since calling the superclass finalizer is required when overriding `finalize()`. Also, although overriding `finalize()` is not recommended, this rule only alerts on direct calls to `finalize()` and does not alert on method declarations overriding `finalize()`. | ||
|
|
||
| ## References | ||
|
|
||
| - SEI CERT Oracle Coding Standard for Java: [MET12-J. Do not use finalizers](https://wiki.sei.cmu.edu/confluence/display/java/MET12-J.+Do+not+use+finalizers). | ||
| - Java API Specification: [Object.finalize()](https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#finalize()). | ||
| - Java API Specification: [Interface AutoCloseable](https://docs.oracle.com/javase/10/docs/api/java/lang/AutoCloseable.html). | ||
| - Java SE Documentation: [The try-with-resources Statement](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html). | ||
| - Common Weakness Enumeration: [CWE-586](https://cwe.mitre.org/data/definitions/586). | ||
30 changes: 30 additions & 0 deletions
30
java/ql/src/Violations of Best Practice/Undesirable Calls/DoNotCallFinalize.ql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| /** | ||
| * @id java/do-not-call-finalize | ||
| * @previous-id java/do-not-use-finalizers | ||
| * @name Do not call `finalize()` | ||
| * @description Calling `finalize()` in application code may cause | ||
| * inconsistent program state or unpredictable behavior. | ||
| * @kind problem | ||
| * @precision high | ||
| * @problem.severity error | ||
| * @tags quality | ||
| * reliability | ||
| * correctness | ||
| * performance | ||
| * external/cwe/cwe-586 | ||
| */ | ||
|
|
||
| import java | ||
|
|
||
| from MethodCall mc | ||
| where | ||
| mc.getMethod() instanceof FinalizeMethod and | ||
| // The Java documentation for `finalize()` states: "If a subclass overrides | ||
| // `finalize` it must invoke the superclass finalizer explicitly". Therefore, | ||
| // we do not alert on `super.finalize()` calls that occur within a callable | ||
| // that overrides `finalize`. | ||
| not exists(Callable caller, FinalizeMethod fm | caller = mc.getCaller() | | ||
| caller.(Method).overrides(fm) and | ||
| mc.getQualifier() instanceof SuperAccess | ||
| ) | ||
| select mc, "Call to 'finalize()'." |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| --- | ||
| category: newQuery | ||
| --- | ||
| * Added a new quality query, `java/do-not-call-finalize`, to detect calls to `finalize()`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 change: 1 addition & 0 deletions
1
java/ql/test/query-tests/DoNotCallFinalize/DoNotCallFinalize.expected
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| | Test.java:4:9:4:23 | finalize(...) | Call to 'finalize()'. | |
2 changes: 2 additions & 0 deletions
2
java/ql/test/query-tests/DoNotCallFinalize/DoNotCallFinalize.qlref
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| query: Violations of Best Practice/Undesirable Calls/DoNotCallFinalize.ql | ||
| postprocess: utils/test/InlineExpectationsTestQuery.ql |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| public class Test { | ||
| void f() throws Throwable { | ||
| // NON_COMPLIANT | ||
| this.finalize(); // $ Alert | ||
| } | ||
|
|
||
| void f1() throws Throwable { | ||
| f(); // COMPLIANT | ||
| } | ||
|
|
||
| @Override | ||
| protected void finalize() throws Throwable { | ||
| // COMPLIANT: If a subclass overrides `finalize()` | ||
| // it must invoke the superclass finalizer explicitly. | ||
| super.finalize(); | ||
| } | ||
|
|
||
| // Overload of `finalize` | ||
| protected void finalize(String s) throws Throwable { | ||
| // ... | ||
| } | ||
owen-mc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| void f2() throws Throwable { | ||
| // COMPLIANT: call to overload of `finalize` | ||
| this.finalize("overload"); | ||
| } | ||
|
|
||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.