C++: Simplify 'hasExactBufferType' and add comments.

This commit is contained in:
Mathias Vorreiter Pedersen
2024-04-09 16:04:20 +01:00
parent 291cc0a671
commit a53ef495ee

View File

@@ -3,6 +3,29 @@ private import semmle.code.cpp.ir.IR
private import codeql.typeflow.TypeFlow private import codeql.typeflow.TypeFlow
private module Input implements TypeFlowInput<Location> { private module Input implements TypeFlowInput<Location> {
/** Holds if `alloc` dynamically allocates a single object. */
private predicate isSingleObjectAllocation(AllocationExpr alloc) {
// i.e., `new int`;
alloc instanceof NewExpr
or
// i.e., `malloc(sizeof(int))`
exists(SizeofTypeOperator sizeOf | sizeOf = alloc.getSizeExpr() |
not sizeOf.getTypeOperand().getUnspecifiedType() instanceof ArrayType
)
}
/**
* Holds if `i` is the result of a dynamic allocation.
*
* `isObject` is `true` if the allocation allocated a single object,
* and `false` otherwise.
*/
private predicate isAllocation(Instruction i, boolean isObject) {
exists(AllocationExpr alloc | alloc = i.getUnconvertedResultExpression() |
if isSingleObjectAllocation(alloc) then isObject = true else isObject = false
)
}
private predicate hasExactSingleType(Instruction i) { private predicate hasExactSingleType(Instruction i) {
// The address of a variable is always a single object // The address of a variable is always a single object
i instanceof VariableAddressInstruction i instanceof VariableAddressInstruction
@@ -14,23 +37,16 @@ private module Input implements TypeFlowInput<Location> {
i instanceof InitializeThisInstruction i instanceof InitializeThisInstruction
or or
// An allocation of a non-array object // An allocation of a non-array object
exists(AllocationExpr alloc | alloc = i.getUnconvertedResultExpression() | isAllocation(i, true)
// i.e., `new int`;
alloc instanceof NewExpr
or
// i.e., `malloc(sizeof(int))`
exists(SizeofTypeOperator sizeOf | sizeOf = alloc.getSizeExpr() |
not sizeOf.getTypeOperand().getUnspecifiedType() instanceof ArrayType
)
)
} }
private predicate hasExactBufferType(Instruction i) { private predicate hasExactBufferType(Instruction i) {
// Anything with an array type is a buffer // Anything with an array type is a buffer
i.getResultLanguageType().hasUnspecifiedType(any(ArrayType at), false) i.getResultLanguageType().hasUnspecifiedType(any(ArrayType at), false)
or or
not hasExactSingleType(i) and // An allocation expression that we couldn't conclude allocated a single
i.getUnconvertedResultExpression() instanceof AllocationExpr // expression is assigned a buffer type.
isAllocation(i, false)
} }
private newtype TTypeFlowNode = private newtype TTypeFlowNode =