Skip to content

Commit

Permalink
C++: Add StrlenLiteralRangeExpr
Browse files Browse the repository at this point in the history
  • Loading branch information
Gulshan Singh committed Mar 24, 2023
1 parent bb27ba7 commit b87f12d
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ import semmle.code.cpp.rangeanalysis.SimpleRangeAnalysis
// Import each extension we want to enable
import extensions.SubtractSelf
import extensions.ConstantBitwiseAndExprRange
import extensions.StrlenLiteralRangeExpr
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
private import cpp
private import experimental.semmle.code.cpp.models.interfaces.SimpleRangeAnalysisExpr

/**
* Provides range analysis information for calls to `strlen` on literal strings.
* For example, the range of `strlen("literal")` will be 7.
*/
class StrlenLiteralRangeExpr extends SimpleRangeAnalysisExpr, FunctionCall {
StrlenLiteralRangeExpr() {
getTarget().hasGlobalOrStdName("strlen") and getArgument(0).isConstant()
}

override int getLowerBounds() { result = getArgument(0).getValue().length() }

override int getUpperBounds() { result = getArgument(0).getValue().length() }

override predicate dependsOnChild(Expr e) { none() }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
| test.cpp:4:3:4:8 | call to strlen | 7.0 | 7.0 |
| test.cpp:5:3:5:8 | call to strlen | 1.8446744073709552E19 | 0.0 |
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import cpp
import semmle.code.cpp.rangeanalysis.SimpleRangeAnalysis
import experimental.semmle.code.cpp.rangeanalysis.extensions.StrlenLiteralRangeExpr

from FunctionCall fc
select fc, upperBound(fc), lowerBound(fc)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
unsigned long strlen(const char *);

void func(const char *s) {
strlen("literal");
strlen(s);
}

0 comments on commit b87f12d

Please sign in to comment.