Skip to content

Commit 4c99d39

Browse files
authored
Merge pull request github#7701 from MathiasVP/remove-intentional-get-stack-pointer
C++: Remove FPs from `cpp/return-stack-allocated-memory`
2 parents 683f909 + 48064c1 commit 4c99d39

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

cpp/ql/src/Likely Bugs/Memory Management/ReturnStackAllocatedMemory.ql

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,24 @@ import cpp
1515
import semmle.code.cpp.ir.IR
1616
import semmle.code.cpp.ir.dataflow.DataFlow::DataFlow
1717

18+
/** Holds if `f` has a name that we intrepret as evidence of intentionally returning the value of the stack pointer. */
19+
predicate intentionallyReturnsStackPointer(Function f) {
20+
f.getName().toLowerCase().matches(["%stack%", "%sp%"])
21+
}
22+
1823
/**
1924
* Holds if `source` is a node that represents the use of a stack variable
2025
*/
2126
predicate isSource(Node source) {
22-
exists(VariableAddressInstruction var |
27+
exists(VariableAddressInstruction var, Function func |
2328
var = source.asInstruction() and
29+
func = var.getEnclosingFunction() and
2430
var.getASTVariable() instanceof StackVariable and
2531
// Pointer-to-member types aren't properly handled in the dbscheme.
2632
not var.getResultType() instanceof PointerToMemberType and
2733
// Rule out FPs caused by extraction errors.
28-
not any(ErrorExpr e).getEnclosingFunction() = var.getEnclosingFunction()
34+
not any(ErrorExpr e).getEnclosingFunction() = func and
35+
not intentionallyReturnsStackPointer(func)
2936
)
3037
}
3138

cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnStackAllocatedMemory/test.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,3 +216,8 @@ auto make_read_port()
216216
auto ptr = port.get();
217217
return ptr; // GOOD
218218
}
219+
220+
void* get_sp() {
221+
int p;
222+
return (void*)&p; // GOOD: The function name makes it sound like the programmer intended to get the value of the stack pointer.
223+
}

0 commit comments

Comments
 (0)