[clang] [analyzer] Compute length of string literal initializers (#66990) (PR #68368)
via cfe-commits
cfe-commits at lists.llvm.org
Mon Oct 9 03:33:15 PDT 2023
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang
<details>
<summary>Changes</summary>
Fix issue https://github.com/llvm/llvm-project/issues/66990
---
Full diff: https://github.com/llvm/llvm-project/pull/68368.diff
2 Files Affected:
- (modified) clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp (+16-1)
- (modified) clang/test/Analysis/string.c (+11)
``````````diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
index f1539f2733298d9..b3b15c35450acdc 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -930,9 +930,24 @@ SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
return svalBuilder.makeIntVal(strLit->getLength(), sizeTy);
}
+ case MemRegion::NonParamVarRegionKind: {
+ // If we have a global constant with a string literal initializer,
+ // compute the initializer's length.
+ const VarDecl *decl = cast<NonParamVarRegion>(MR)->getDecl();
+ if (decl->hasGlobalStorage()) {
+ if (const Expr *init = decl->getInit()) {
+ if (auto *strLit = dyn_cast<StringLiteral>(init)) {
+ SValBuilder &svalBuilder = C.getSValBuilder();
+ QualType sizeTy = svalBuilder.getContext().getSizeType();
+ return svalBuilder.makeIntVal(strLit->getLength(), sizeTy);
+ }
+ }
+ }
+ // Otherwise, fallback to this.
+ return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
+ }
case MemRegion::SymbolicRegionKind:
case MemRegion::AllocaRegionKind:
- case MemRegion::NonParamVarRegionKind:
case MemRegion::ParamVarRegionKind:
case MemRegion::FieldRegionKind:
case MemRegion::ObjCIvarRegionKind:
diff --git a/clang/test/Analysis/string.c b/clang/test/Analysis/string.c
index d369ee9f7d854a1..8da905b33145562 100644
--- a/clang/test/Analysis/string.c
+++ b/clang/test/Analysis/string.c
@@ -97,6 +97,17 @@ void strlen_constant2(char x) {
clang_analyzer_eval(strlen(a) == 3); // expected-warning{{UNKNOWN}}
}
+const char *const global_str_ptr = "abcd";
+const char global_str_arr[] = "efgh";
+
+void strlen_global_constant_ptr(void) {
+ clang_analyzer_eval(strlen(global_str_ptr) == 4); // expected-warning{{TRUE}}
+}
+
+void strlen_global_constant_arr(void) {
+ clang_analyzer_eval(strlen(global_str_arr) == 4); // expected-warning{{TRUE}}
+}
+
size_t strlen_null(void) {
return strlen(0); // expected-warning{{Null pointer passed as 1st argument to string length function}}
}
``````````
</details>
https://github.com/llvm/llvm-project/pull/68368
More information about the cfe-commits
mailing list