C++: Ignore free calls that are macro defined or #if/#ifdef guarded

This commit is contained in:
Jeroen Ketema
2024-11-14 12:51:04 +01:00
parent a31e983e9e
commit 176acabd9d
3 changed files with 16 additions and 7 deletions

View File

@@ -18,6 +18,17 @@ class FreeCall extends FunctionCall {
FreeCall() { this.getTarget().hasGlobalName("free") }
}
predicate isAffectedByMacro(FreeCall fc, BasicBlock bb) {
fc.isInMacroExpansion()
or
exists(PreprocessorBranch ppb, Location bbLoc, Location ppbLoc |
bbLoc = bb.(Stmt).getLocation() and ppbLoc = ppb.getLocation()
|
bbLoc.getStartLine() < ppbLoc.getStartLine() and
ppbLoc.getEndLine() < bbLoc.getEndLine()
)
}
from GuardCondition gc, FreeCall fc, Variable v, BasicBlock bb
where
gc.ensuresEq(v.getAnAccess(), 0, bb, false) and
@@ -28,5 +39,6 @@ where
or
strictcount(bb.(BlockStmt).getAStmt()) = 1
) and
strictcount(BasicBlock bb2 | gc.ensuresEq(_, 0, bb2, _) | bb2) = 1
strictcount(BasicBlock bb2 | gc.ensuresEq(_, 0, bb2, _) | bb2) = 1 and
not isAffectedByMacro(fc, bb)
select gc, "unnecessary NULL check before call to $@", fc, "free"

View File

@@ -3,8 +3,5 @@
| test.cpp:31:7:31:24 | ... \|\| ... | unnecessary NULL check before call to $@ | test.cpp:35:3:35:6 | call to free | free |
| test.cpp:42:7:42:7 | x | unnecessary NULL check before call to $@ | test.cpp:43:5:43:8 | call to free | free |
| test.cpp:49:7:49:7 | x | unnecessary NULL check before call to $@ | test.cpp:50:5:50:8 | call to free | free |
| test.cpp:75:7:75:7 | x | unnecessary NULL check before call to $@ | test.cpp:76:5:76:14 | call to free | free |
| test.cpp:81:7:81:7 | x | unnecessary NULL check before call to $@ | test.cpp:85:5:85:8 | call to free | free |
| test.cpp:94:12:94:12 | x | unnecessary NULL check before call to $@ | test.cpp:94:3:94:13 | call to free | free |
| test.cpp:106:7:106:18 | ... != ... | unnecessary NULL check before call to $@ | test.cpp:107:5:107:8 | call to free | free |
| test.cpp:113:7:113:18 | ... != ... | unnecessary NULL check before call to $@ | test.cpp:114:17:114:20 | call to free | free |

View File

@@ -72,13 +72,13 @@ bool test8(char *x) {
#endif
void test9(char *x) {
if (x) { // GOOD [FALSE POSITIVE]: macro may make free behave unexpectedly when compiled differently
if (x) { // GOOD: macro may make free behave unexpectedly when compiled differently
my_free(x);
}
}
void test10(char *x) {
if (x) { // GOOD [FALSE POSITIVE]: #ifdef may make free behave unexpectedly when compiled differently
if (x) { // GOOD: #ifdef may make free behave unexpectedly when compiled differently
#ifdef FOO
free(x - 1);
#else
@@ -91,7 +91,7 @@ void test10(char *x) {
if (x) free(x);
void test11(char *x) {
TRY_FREE(x) // BAD
TRY_FREE(x) // BAD [NOT DETECTED]
}
bool test12(char *x) {