[clang] [analyzer] Compute length of string literal initializers (#66990) (PR #68368)

via cfe-commits cfe-commits at lists.llvm.org
Mon Oct 9 03:31:56 PDT 2023


================
@@ -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);
----------------
DonatNagyE wrote:

```suggestion
    [[fallthrough]];
```
Use this convention (which is technically an annotated empty statement) to create a clean fallthrough instead of duplicating the logic of the other branches.

https://github.com/llvm/llvm-project/pull/68368


More information about the cfe-commits mailing list