[clang] [clang][analyzer] Add StoreToImmutable checker (PR #150417)
Balazs Benics via cfe-commits
cfe-commits at lists.llvm.org
Fri Jul 25 05:52:23 PDT 2025
Endre =?utf-8?q?Fülöp?= <endre.fulop at sigmatechnology.com>
Message-ID:
In-Reply-To: <llvm.org/llvm/llvm-project/pull/150417 at github.com>
================
@@ -0,0 +1,134 @@
+//=== StoreToImmutableChecker.cpp - Store to immutable memory ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines StoreToImmutableChecker, a checker that detects writes
+// to immutable memory regions. This implements part of SEI CERT Rule ENV30-C.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+class StoreToImmutableChecker : public Checker<check::Bind> {
+ const BugType BT{this, "Write to immutable memory", "CERT Environment (ENV)"};
+
+public:
+ void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &C) const;
+
+private:
+ bool isConstVariable(const MemRegion *MR, CheckerContext &C) const;
+ bool isConstQualifiedType(const MemRegion *MR, CheckerContext &C) const;
+};
+} // end anonymous namespace
+
+bool StoreToImmutableChecker::isConstVariable(const MemRegion *MR,
+ CheckerContext &C) const {
+ // Check if the region is in the global immutable space
+ const MemSpaceRegion *MS = MR->getMemorySpace(C.getState());
+ if (isa<GlobalImmutableSpaceRegion>(MS))
+ return true;
+
+ // Check if this is a VarRegion with a const-qualified type
+ if (const VarRegion *VR = dyn_cast<VarRegion>(MR)) {
+ const VarDecl *VD = VR->getDecl();
+ if (VD && VD->getType().isConstQualified())
+ return true;
+ }
----------------
steakhal wrote:
How can a const VarRegion live outside of the immutable space? Could you point me to an example? I know now that at least one test case covers this, but I can't help myself see how.
https://github.com/llvm/llvm-project/pull/150417
More information about the cfe-commits
mailing list