Using range analysis for C and C++¶
You can use range analysis to determine the upper or lower bounds on an expression, or whether an expression could potentially over or underflow.
About the range analysis library¶
The range analysis library (defined insemmle.code.cpp.rangeanalysis.SimpleRangeAnalysis
) provides a set of predicates for determining constant upper and lower bounds on expressions, as well as recognizing integer overflows. For performance, the library performs automatic widening and therefore may not provide the tightest possible bounds.
Bounds predicates¶
TheupperBound
andlowerBound
predicates provide constant bounds on expressions. No conversions of the argument are included in the bound. In the common case that your query needs to take conversions into account, call them on the converted form, such asupperBound(expr.getFullyConverted())
.
Overflow predicates¶
exprMightOverflow
and related predicates hold if the relevant expression might overflow, as determined by the range analysis library. TheconvertedExprMightOverflow
family of predicates will take conversions into account.
Example¶
This query usesupperBound
to determine whether the result ofsnprintf
is checked when used in a loop.
fromFunctionCallcall,DataFlow::Nodesource,DataFlow::Nodesink,ExprconvSinkwhere// the call is an snprintf with a string format argumentcall.getTarget().getName()="snprintf"andcall.getArgument(2).getValue().regexpMatch(".*%s.*")and// the result of the call influences its size argument in later iterationsTaintTracking::localTaint(source,sink)andsource.asExpr()=callandsink.asExpr()=call.getArgument(1)and// there is no fixed bound on the snprintf's size argumentupperBound(convSink)=typeUpperBound(convSink.getType().getUnspecifiedType())andconvSink=call.getArgument(1).getFullyConverted()selectcall,upperBound(call.getArgument(1).getFullyConverted())