[clang] [analyzer] Add alpha.cplusplus.PlacementSelfCopy checker (PR #233525)
DonĂ¡t Nagy via cfe-commits
cfe-commits at lists.llvm.org
Thu Nov 26 01:29:14 PST 2026
================
@@ -0,0 +1,545 @@
+//===- PlacementSelfCopyChecker.cpp -----------------------------*- 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
+//
+//===----------------------------------------------------------------------===//
+//
+// Defines a checker that finds placement new expressions that access the
+// target storage through the old object, either in the new-initializer or
+// during construction, e.g. `::new (p) T(*p)`. A call that is not inlined is
+// assumed to access the old object passed to it; when it is the copy or move
+// constructor called by placement new itself, it is reported as a self-copy.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/ParentMap.h"
+#include "clang/Basic/Builtins.h"
+#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/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+
+using namespace clang;
+using namespace ento;
+
+using PlacementKey = std::pair<const CXXNewExpr *, const StackFrame *>;
+REGISTER_MAP_WITH_PROGRAMSTATE(PlacementTargets, PlacementKey,
+ const MemRegion *)
+// Variables that refer to the old storage, mapped to the placement target.
+REGISTER_MAP_WITH_PROGRAMSTATE(SourceVars, const MemRegion *, const MemRegion *)
+// Frames of methods called on the old storage, mapped to the placement target.
+REGISTER_MAP_WITH_PROGRAMSTATE(SourceFrames, const StackFrame *,
+ const MemRegion *)
+REGISTER_TRAIT_WITH_PROGRAMSTATE(PendingSelfCopy, const MemRegion *)
+
+namespace {
+class PlacementSelfCopyChecker
+ : public Checker<check::PostCall, check::PreCall, check::Bind,
+ check::Location, check::PostStmt<LambdaExpr>,
+ check::PostStmt<CXXNewExpr>> {
+ const BugType BT{this, "Placement new initialized from its own storage",
+ categories::MemoryError};
+ const BugType AccessBT{this, "Placement new accesses its own storage",
+ categories::MemoryError};
+
+ void reportAccess(const Expr *E, CheckerContext &C) const;
+ void reportSelfCopy(const Expr *Arg, CheckerContext &C) const;
+ void reportPendingSelfCopy(const CallEvent &Call, CheckerContext &C) const;
+
+public:
+ void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
+ void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
+ void checkBind(SVal Loc, SVal Val, const Stmt *S, bool AtDeclInit,
+ CheckerContext &C) const;
+ void checkLocation(SVal Loc, bool IsLoad, const Stmt *S,
+ CheckerContext &C) const;
+ void checkPostStmt(const LambdaExpr *LE, CheckerContext &C) const;
+ void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
+};
+} // namespace
+
+namespace {
+struct MemorySpan {
+ const MemRegion *Base;
+ int64_t Begin;
+ int64_t End;
+};
+} // namespace
+
+// Base class subobjects keep their own memory span.
+static const MemRegion *stripCasts(const MemRegion *R) {
+ return R->StripCasts(/*StripBaseAndDerivedCasts=*/false);
+}
+
+static std::optional<MemorySpan> getMemorySpan(const MemRegion *R,
+ ASTContext &Ctx) {
+ RegionOffset Offset = R->getAsOffset();
+ if (!Offset.isValid() || Offset.hasSymbolicOffset())
+ return std::nullopt;
+ QualType Ty;
+ if (const auto *TR = dyn_cast<TypedValueRegion>(R))
+ Ty = TR->getValueType();
+ else if (const auto *SR = dyn_cast<SymbolicRegion>(R))
+ Ty = SR->getPointeeStaticType();
+ if (Ty.isNull() || Ty->isIncompleteType())
+ return std::nullopt;
+ int64_t End = Offset.getOffset() + Ctx.getTypeSize(Ty);
+ return MemorySpan{Offset.getRegion(), Offset.getOffset(), End};
+}
+
+// Returns the spans of A and B if both are known within the same base.
+static std::optional<std::pair<MemorySpan, MemorySpan>>
+getMemorySpans(const MemRegion *A, const MemRegion *B, ASTContext &Ctx) {
+ std::optional<MemorySpan> SA = getMemorySpan(A, Ctx);
+ std::optional<MemorySpan> SB = getMemorySpan(B, Ctx);
+ if (!SA || !SB || SA->Base != SB->Base)
+ return std::nullopt;
+ return std::make_pair(*SA, *SB);
+}
+
+// Target keeps its element layer, which limits it to the placed object.
+static bool overlaps(const MemRegion *R, const MemRegion *Target,
+ ASTContext &Ctx) {
+ if (auto S = getMemorySpans(R, Target, Ctx))
+ return S->first.Begin < S->second.End && S->second.Begin < S->first.End;
+ R = stripCasts(R);
+ return R == stripCasts(Target) || R->isSubRegionOf(Target) ||
+ Target->isSubRegionOf(R);
+}
+
+static bool isWithin(const MemRegion *R, const MemRegion *Container,
+ ASTContext &Ctx) {
+ if (auto S = getMemorySpans(R, Container, Ctx))
+ return S->second.Begin <= S->first.Begin && S->first.End <= S->second.End;
+ R = stripCasts(R);
+ return R == stripCasts(Container) || R->isSubRegionOf(Container);
+}
+
+// Limits R to the placed object instead of the whole buffer it lives in.
+static const MemRegion *getPlacedRegion(const CXXNewExpr *NE,
+ const MemRegion *R, CheckerContext &C) {
+ ASTContext &Ctx = C.getASTContext();
+ QualType Ty = NE->getAllocatedType();
+ if (NE->isArray()) {
+ std::optional<const Expr *> Size = NE->getArraySize();
+ std::optional<llvm::APSInt> N =
+ Size && *Size ? (*Size)->getIntegerConstantExpr(Ctx) : std::nullopt;
+ if (!N)
+ return R;
+ Ty =
+ Ctx.getConstantArrayType(Ty, *N, nullptr, ArraySizeModifier::Normal, 0);
+ }
+ const auto *SR = dyn_cast<SubRegion>(R);
+ const auto *TR = dyn_cast<TypedValueRegion>(R);
+ if (!SR || (TR && Ctx.hasSameUnqualifiedType(TR->getValueType(), Ty)))
+ return R;
+ return C.getStoreManager().GetElementZeroRegion(SR, Ty);
+}
+
+// Calls that return their argument or its address without accessing it, e.g.
+// `std::move(X)`, `std::addressof(X)` or `&X` with an overloaded `operator&`.
+static bool isPassThroughCall(const CallExpr *CE) {
+ if (!CE || CE->getNumArgs() != 1)
+ return false;
+ if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE))
+ return OCE->getOperator() == OO_Amp;
+ const FunctionDecl *FD = CE->getDirectCallee();
+ switch (FD ? FD->getBuiltinID() : 0) {
+ case Builtin::BIaddressof:
+ case Builtin::BI__addressof:
+ case Builtin::BI__builtin_addressof:
+ case Builtin::BIas_const:
+ case Builtin::BIforward:
+ case Builtin::BIforward_like:
+ case Builtin::BImove:
+ case Builtin::BImove_if_noexcept:
+ return true;
+ default:
+ return false;
+ }
+}
+
+// Collects the variables that E accesses memory through, e.g. `O` for
+// `O->X[1]`, `O.A + 1` or `O.data()`, and both `A` and `B` for
+// `(C ? A : B).X`.
+static void collectBaseVars(const Expr *E,
+ SmallVectorImpl<const VarDecl *> &Vars,
+ bool &ViaThis) {
+ while (E) {
+ E = E->IgnoreParenCasts();
+ if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
+ if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
+ Vars.push_back(VD);
+ return;
+ }
+ if (isa<CXXThisExpr>(E)) {
+ ViaThis = true;
+ return;
+ }
+ if (const auto *CO = dyn_cast<AbstractConditionalOperator>(E)) {
+ collectBaseVars(CO->getTrueExpr(), Vars, ViaThis);
+ E = CO->getFalseExpr();
+ } else if (const auto *ME = dyn_cast<MemberExpr>(E))
+ E = ME->getBase();
+ else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
+ E = ASE->getBase();
+ else if (const auto *BO = dyn_cast<BinaryOperator>(E);
+ BO && BO->isAssignmentOp())
+ E = BO->getLHS();
+ else if (BO && BO->isAdditiveOp())
+ E = BO->getLHS()->getType()->isPointerType() ? BO->getLHS()
+ : BO->getRHS();
+ else if (const auto *UO = dyn_cast<UnaryOperator>(E);
+ UO &&
+ (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
+ UO->isIncrementDecrementOp()))
+ E = UO->getSubExpr();
+ else if (const auto *CE = dyn_cast<CallExpr>(E); isPassThroughCall(CE))
+ E = CE->getArg(0);
+ else if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(E))
+ E = MCE->getImplicitObjectArgument();
+ else
+ return;
+ }
+}
+
+static bool isEmptyRecord(const MemRegion *R) {
+ const auto *TR = dyn_cast<TypedValueRegion>(R);
+ const CXXRecordDecl *RD =
+ TR ? TR->getValueType()->getAsCXXRecordDecl() : nullptr;
+ return RD && RD->hasDefinition() && RD->isEmpty();
+}
+
+static bool isInInitializer(const CXXNewExpr *NE, const Stmt *S,
+ CheckerContext &C) {
+ const Expr *Init = NE->getInitializer();
+ const ParentMap &PM = C.getCurrentAnalysisDeclContext()->getParentMap();
+ for (const Stmt *P = S; P && P != NE; P = PM.getParent(P))
+ if (P == Init)
+ return true;
+ return false;
+}
+
+// Returns the target whose new-initializer S uses Source in.
+static const MemRegion *findInitializedTarget(const Stmt *S,
+ const MemRegion *Source,
+ CheckerContext &C) {
+ if (isEmptyRecord(Source))
+ return nullptr;
+ for (const auto &[Key, Target] : C.getState()->get<PlacementTargets>())
+ if (Key.second == C.getStackFrame() && isInInitializer(Key.first, S, C) &&
+ overlaps(Source, Target, C.getASTContext()))
+ return Target;
+ return nullptr;
+}
+
+// Captured variables and `this` in a lambda body belong to the frame of the
+// function that defines the lambda. Only pointers and `this` get here: other
+// captures of the old object are reported when the lambda is created.
+static const StackFrame *getOwningFrame(const VarDecl *VD,
+ const StackFrame *Frame) {
+ while (Frame) {
+ const auto *MD = dyn_cast_if_present<CXXMethodDecl>(Frame->getDecl());
+ if (!MD || !MD->getParent()->isLambda() ||
+ (VD && VD->getDeclContext() == MD))
+ return Frame;
+ const auto *Outer = dyn_cast<Decl>(MD->getParent()->getDeclContext());
+ do
+ Frame = Frame->getParent();
+ while (Frame && Frame->getDecl() != Outer);
+ }
+ return nullptr;
+}
+
+// Returns the target that E accesses through a variable that refers to it,
+// or through `this` of a method called on the old storage.
+static const MemRegion *findSourceTarget(const Expr *E, const MemRegion *Source,
+ CheckerContext &C) {
+ if (isEmptyRecord(Source))
+ return nullptr;
+ SmallVector<const VarDecl *, 2> Vars;
+ bool ViaThis = false;
+ collectBaseVars(E, Vars, ViaThis);
+ ProgramStateRef State = C.getState();
+ auto Matches = [&](const MemRegion *const *Target) {
+ return Target && overlaps(Source, *Target, C.getASTContext());
+ };
+ for (const VarDecl *VD : Vars) {
+ const StackFrame *Owner = getOwningFrame(VD, C.getStackFrame());
+ const MemRegion *Var =
+ Owner ? State->getLValue(VD, Owner).getAsRegion() : nullptr;
+ if (const MemRegion *const *T = Var ? State->get<SourceVars>(Var) : nullptr;
----------------
NagyDonat wrote:
Random stylistic comment: add `if (!Owner) continue;` and `if (!Var) continue;` instead of playing around with the ternary operators.
https://github.com/llvm/llvm-project/pull/233525
More information about the cfe-commits
mailing list