Skip to content

Commit 86cc59e

Browse files
authored
Merge pull request github#12650 from gsingh93/strlen-literal-range-expr
C++: Add StrlenLiteralRangeExpr
2 parents bb27ba7 + b87f12d commit 86cc59e

File tree

5 files changed

+33
-0
lines changed

5 files changed

+33
-0
lines changed

cpp/ql/lib/experimental/semmle/code/cpp/rangeanalysis/ExtendedRangeAnalysis.qll

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ import semmle.code.cpp.rangeanalysis.SimpleRangeAnalysis
33
// Import each extension we want to enable
44
import extensions.SubtractSelf
55
import extensions.ConstantBitwiseAndExprRange
6+
import extensions.StrlenLiteralRangeExpr
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
private import cpp
2+
private import experimental.semmle.code.cpp.models.interfaces.SimpleRangeAnalysisExpr
3+
4+
/**
5+
* Provides range analysis information for calls to `strlen` on literal strings.
6+
* For example, the range of `strlen("literal")` will be 7.
7+
*/
8+
class StrlenLiteralRangeExpr extends SimpleRangeAnalysisExpr, FunctionCall {
9+
StrlenLiteralRangeExpr() {
10+
getTarget().hasGlobalOrStdName("strlen") and getArgument(0).isConstant()
11+
}
12+
13+
override int getLowerBounds() { result = getArgument(0).getValue().length() }
14+
15+
override int getUpperBounds() { result = getArgument(0).getValue().length() }
16+
17+
override predicate dependsOnChild(Expr e) { none() }
18+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
| test.cpp:4:3:4:8 | call to strlen | 7.0 | 7.0 |
2+
| test.cpp:5:3:5:8 | call to strlen | 1.8446744073709552E19 | 0.0 |
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import cpp
2+
import semmle.code.cpp.rangeanalysis.SimpleRangeAnalysis
3+
import experimental.semmle.code.cpp.rangeanalysis.extensions.StrlenLiteralRangeExpr
4+
5+
from FunctionCall fc
6+
select fc, upperBound(fc), lowerBound(fc)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
unsigned long strlen(const char *);
2+
3+
void func(const char *s) {
4+
strlen("literal");
5+
strlen(s);
6+
}

0 commit comments

Comments
 (0)