[clang] [analyzer] Add cplusplus.DestroyedAsWrongType checker (PR #237801)
via cfe-commits
cfe-commits at lists.llvm.org
Sat Nov 14 13:21:44 PST 2026
https://github.com/mark-zilber updated https://github.com/llvm/llvm-project/pull/237801
>From 07ebad282da420f78ccf679803cdc50b87505fe3 Mon Sep 17 00:00:00 2001
From: Mark Zilber <markusbusiness69 at gmail.com>
Date: Mon, 2 Nov 2026 01:50:42 +0200
Subject: [PATCH 1/4] [analyzer] Add cplusplus.DestroyedAsWrongType checker
Reports storage that placement new reuses for an object of a different
type and that is then destroyed or deleted as the original type
([basic.life]/11, [expr.delete]/3). Destructor calls and deletions made
inside the standard library, such as std::destroy_at, are reported at
the call site.
Tested on abseil-cpp, protobuf, EASTL, ETL, godot and parts of LLVM
(about 3900 translation units). The only reports are twelve in LLVM, all
caused by the move assignment of llvm::unique_function, which destroys
and recreates its UniqueFunctionBase base subobject.
Part of #233519
---
clang/docs/ReleaseNotes.md | 6 +
clang/docs/analyzer/checkers.md | 40 ++
.../clang/StaticAnalyzer/Checkers/Checkers.td | 5 +
.../StaticAnalyzer/Checkers/CMakeLists.txt | 1 +
.../Checkers/DestroyedAsWrongTypeChecker.cpp | 339 +++++++++++++++++
.../test/Analysis/destroyed-as-wrong-type.cpp | 358 ++++++++++++++++++
6 files changed, 749 insertions(+)
create mode 100644 clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp
create mode 100644 clang/test/Analysis/destroyed-as-wrong-type.cpp
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 9e5d92cae727cc..ba2b2bd311865a 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -1255,6 +1255,12 @@ features cannot lower the translation-unit ABI level;
% - Moved checkers
% - Diagnostic changes
+#### New checkers and features
+
+- Added the ``cplusplus.DestroyedAsWrongType`` checker, which reports storage
+ reused by placement new for an object of a different type that is then
+ destroyed or deleted as the original type.
+
#### Improvements
- The lock-order-reversal check in ``alpha.unix.PthreadLock`` is now disabled by default.
diff --git a/clang/docs/analyzer/checkers.md b/clang/docs/analyzer/checkers.md
index e2bbf52943bb87..b653fddcb37183 100644
--- a/clang/docs/analyzer/checkers.md
+++ b/clang/docs/analyzer/checkers.md
@@ -457,6 +457,46 @@ void foo() {
}
```
+(cplusplus-destroyedaswrongtype)=
+
+#### cplusplus.DestroyedAsWrongType (C++)
+
+Check for storage that is reused by placement new for an object of a different
+type and is then destroyed or deleted as the original type
+([basic.life]/11, [expr.delete]/3). Destructor calls and deletions inside the
+standard library, such as `std::destroy_at`, are reported at the call site.
+
+Deleting or destroying the object through a base class with a virtual
+destructor is allowed. Placement new into raw storage, such as a character
+buffer or memory from `::operator new`, into a union and into an object with a
+trivial destructor is not reported. Members and array elements destroyed by a
+destructor that is not inlined are checked when that destructor is called.
+
+```cpp
+class A {};
+class B {
+public:
+ ~B();
+};
+
+void test1() {
+ B b;
+ new (&b) A;
+} // warn: destructor of 'B' is called on storage that holds an object of
+ // type 'A'
+
+void test2() {
+ B *b = new B;
+ new (b) A;
+ delete b; // warn: deleting an object of type 'A' through a pointer to 'B'
+}
+```
+
+**Limitations**
+
+A function that is not inlined is assumed not to recreate the original object
+in the storage passed to it. If it does, the destruction is still reported.
+
(cplusplus-innerpointer)=
#### cplusplus.InnerPointer (C++)
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 9905649801e85b..14eed2d61ce38a 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -644,6 +644,11 @@ def ArrayDeleteChecker : Checker<"ArrayDelete">,
"destructed as their base class.">,
Documentation<HasDocumentation>;
+def DestroyedAsWrongTypeChecker : Checker<"DestroyedAsWrongType">,
+ HelpText<"Check for objects destroyed or deleted as a type that their "
+ "storage no longer holds after placement new">,
+ Documentation<HasDocumentation>;
+
def InnerPointerChecker : Checker<"InnerPointer">,
HelpText<"Check for inner pointers of C++ containers used after "
"re/deallocation">,
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index f136bd5434113b..c16e667de4c941 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -37,6 +37,7 @@ add_clang_library(clangStaticAnalyzerCheckers
DebugContainerModeling.cpp
DebugIteratorModeling.cpp
DereferenceChecker.cpp
+ DestroyedAsWrongTypeChecker.cpp
DirectIvarAssignment.cpp
DivZeroChecker.cpp
DynamicTypePropagation.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp
new file mode 100644
index 00000000000000..1cb117cfd37125
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp
@@ -0,0 +1,339 @@
+//===- DestroyedAsWrongTypeChecker.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 storage reused by placement new for an object
+// of a different type and then destroyed or deleted as the original type
+// (C++ [basic.life]p11, [expr.delete]p3).
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/AST/ExprCXX.h"
+#include "clang/Analysis/CFG.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"
+#include <optional>
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+struct WrongDestruction {
+ QualType Placed;
+ const CXXRecordDecl *DtorClass;
+ const CXXDeleteExpr *Delete;
+
+ bool operator==(const WrongDestruction &X) const {
+ return Placed == X.Placed && DtorClass == X.DtorClass && Delete == X.Delete;
+ }
+ void Profile(llvm::FoldingSetNodeID &ID) const {
+ ID.Add(Placed);
+ ID.AddPointer(DtorClass);
+ ID.AddPointer(Delete);
+ }
+};
+} // namespace
+
+REGISTER_MAP_WITH_PROGRAMSTATE(PlacedObjectTypes, const MemRegion *, QualType)
+REGISTER_SET_WITH_PROGRAMSTATE(NewAllocatedObjects, const MemRegion *)
+REGISTER_MAP_WITH_PROGRAMSTATE(PendingDestructions, const MemRegion *,
+ WrongDestruction)
+
+namespace {
+class DestroyedAsWrongTypeChecker
+ : public Checker<check::PostStmt<CXXNewExpr>, check::PreCall,
+ check::PostCall, check::DeadSymbols> {
+ const BugType BT{this, "Object destroyed as a type it no longer has",
+ categories::MemoryError};
+
+ void reportBug(const MemRegion *R, const WrongDestruction &W,
+ CheckerContext &C) const;
+ void reportOrDefer(const MemRegion *R, const WrongDestruction &W,
+ CheckerContext &C) const;
+
+public:
+ void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
+ void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
+ void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
+ void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
+};
+} // namespace
+
+// An array is keyed by its first element, the object its destructor gets.
+static const MemRegion *getStorageRegion(SVal V, CheckerContext &C) {
+ const MemRegion *R = V.getAsRegion();
+ if (!R)
+ return nullptr;
+ R = R->StripCasts();
+ ASTContext &Ctx = C.getASTContext();
+ while (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
+ const ArrayType *AT = Ctx.getAsArrayType(TR->getValueType());
+ if (!AT)
+ break;
+ R = C.getStoreManager().getRegionManager().getElementRegion(
+ AT->getElementType(), C.getSValBuilder().makeZeroArrayIndex(), TR, Ctx);
+ }
+ return R;
+}
+
+// Storage obtained as raw memory has no original object to be replaced.
+static bool holdsOriginalObject(ProgramStateRef State, const MemRegion *R) {
+ if (State->contains<NewAllocatedObjects>(R))
+ return true;
+ const auto *TR = dyn_cast<TypedValueRegion>(R);
+ if (!TR)
+ return false;
+ // Placement new into a union starts the lifetime of one of its members.
+ const CXXRecordDecl *RD = TR->getValueType()->getAsCXXRecordDecl();
+ return RD && !RD->isUnion() && RD->hasNonTrivialDestructor();
+}
+
+static bool isSameRecord(QualType T, const CXXRecordDecl *RD) {
+ const CXXRecordDecl *TD = T->getAsCXXRecordDecl();
+ return TD && TD->getCanonicalDecl() == RD->getCanonicalDecl();
+}
+
+static QualType getStorageType(const MemRegion *R) {
+ if (const auto *TR = dyn_cast<TypedValueRegion>(R))
+ return TR->getValueType();
+ if (const auto *SR = dyn_cast<SymbolicRegion>(R))
+ return SR->getPointeeStaticType();
+ return {};
+}
+
+// A field and a byte offset from its parent are different regions.
+static bool isSameLocation(const MemRegion *A, const MemRegion *B) {
+ RegionOffset OA = A->getAsOffset();
+ RegionOffset OB = B->getAsOffset();
+ return OA.isValid() && OB.isValid() && !OA.hasSymbolicOffset() &&
+ !OB.hasSymbolicOffset() && OA.getRegion() == OB.getRegion() &&
+ OA.getOffset() == OB.getOffset();
+}
+
+static ProgramStateRef forgetPlacedTypes(ProgramStateRef State,
+ const MemRegion *R) {
+ for (const MemRegion *Key :
+ llvm::make_first_range(State->get<PlacedObjectTypes>()))
+ if (Key == R || Key->isSubRegionOf(R) || isSameLocation(Key, R))
+ State = State->remove<PlacedObjectTypes>(Key);
+ return State;
+}
+
+static SmallVector<const MemRegion *, 1>
+getPlacementStorages(const CXXNewExpr *NE, CheckerContext &C) {
+ SmallVector<const MemRegion *, 1> Storages;
+ for (const Expr *Arg : NE->placement_arguments())
+ if (Arg->getType()->isPointerType())
+ if (const MemRegion *R = getStorageRegion(C.getSVal(Arg), C))
+ Storages.push_back(R);
+ return Storages;
+}
+
+static bool isInStdFrame(CheckerContext &C) {
+ return AnalysisDeclContext::isInStdNamespace(C.getStackFrame()->getDecl());
+}
+
+void DestroyedAsWrongTypeChecker::reportBug(const MemRegion *R,
+ const WrongDestruction &W,
+ CheckerContext &C) const {
+ ExplodedNode *N = C.generateErrorNode();
+ if (!N)
+ return;
+ const PrintingPolicy &PP = C.getASTContext().getPrintingPolicy();
+ std::string Placed = W.Placed.getAsString(PP);
+ std::string Msg =
+ W.Delete
+ ? "Deleting an object of type '" + Placed +
+ "' through a pointer to '" +
+ W.Delete->getDestroyedType().getUnqualifiedType().getAsString(
+ PP) +
+ "'"
+ : "Destructor of '" + W.DtorClass->getQualifiedNameAsString() +
+ "' is called on storage that holds an object of type '" +
+ Placed + "'";
+ auto Report = std::make_unique<PathSensitiveBugReport>(BT, Msg, N);
+ Report->markInteresting(R);
+ C.emitReport(std::move(Report));
+}
+
+void DestroyedAsWrongTypeChecker::checkPostStmt(const CXXNewExpr *NE,
+ CheckerContext &C) const {
+ const FunctionDecl *OperatorNew = NE->getOperatorNew();
+ if (!OperatorNew)
+ return;
+
+ const MemRegion *Result = getStorageRegion(C.getSVal(NE), C);
+ if (!Result)
+ return;
+
+ ProgramStateRef State = C.getState();
+ SmallVector<const MemRegion *, 1> Storages = getPlacementStorages(NE, C);
+ if (OperatorNew->isReservedGlobalPlacementOperator() && Storages.empty())
+ return;
+ // The result may be typed as the new object, so use the storage argument.
+ const MemRegion *R = nullptr;
+ for (const MemRegion *Storage : Storages)
+ if (OperatorNew->isReservedGlobalPlacementOperator() || Storage == Result ||
+ isSameLocation(Storage, Result))
+ R = Storage;
+ if (!R) {
+ // An operator new that is not inlined may have placed the object there.
+ for (const MemRegion *Storage : Storages)
+ State = forgetPlacedTypes(State, Storage);
+ C.addTransition(State->add<NewAllocatedObjects>(Result));
+ return;
+ }
+
+ if (NE->isArray()) {
+ const auto *ER = dyn_cast<ElementRegion>(R);
+ C.addTransition(forgetPlacedTypes(State, ER ? ER->getSuperRegion() : R));
+ return;
+ }
+ State = forgetPlacedTypes(State, R);
+ if (!holdsOriginalObject(State, R)) {
+ C.addTransition(State);
+ return;
+ }
+
+ QualType Placed = NE->getAllocatedType().getUnqualifiedType();
+ std::string Note = "Object of type '" +
+ Placed.getAsString(C.getASTContext().getPrintingPolicy()) +
+ "' is created here by placement new";
+ const NoteTag *Tag =
+ C.getNoteTag([this, R, Note](PathSensitiveBugReport &BR) -> std::string {
+ if (&BR.getBugType() != &BT || !BR.isInteresting(R))
+ return "";
+ return Note;
+ });
+ C.addTransition(State->set<PlacedObjectTypes>(R, Placed), Tag);
+}
+
+// Destroying through a base class with a virtual destructor is well-defined.
+static bool isVirtualBaseDestruction(QualType Placed,
+ const CXXRecordDecl *Static) {
+ const CXXRecordDecl *PlacedRD = Placed->getAsCXXRecordDecl();
+ if (!PlacedRD || !PlacedRD->isDerivedFrom(Static))
+ return false;
+ const CXXDestructorDecl *Dtor = Static->getDestructor();
+ return Dtor && Dtor->isVirtual();
+}
+
+void DestroyedAsWrongTypeChecker::reportOrDefer(const MemRegion *R,
+ const WrongDestruction &W,
+ CheckerContext &C) const {
+ // Reports inside the standard library are suppressed; report at the caller.
+ if (isInStdFrame(C)) {
+ C.addTransition(C.getState()->set<PendingDestructions>(R, W));
+ return;
+ }
+ reportBug(R, W, C);
+}
+
+static const MemRegion *getDestroyedRegion(const CallEvent &Call,
+ CheckerContext &C) {
+ const auto *Instance = dyn_cast<CXXInstanceCall>(&Call);
+ return Instance ? getStorageRegion(Instance->getCXXThisVal(), C) : nullptr;
+}
+
+static std::optional<WrongDestruction>
+findWrongDestruction(const CallEvent &Call, const CXXDestructorDecl *Dtor,
+ const MemRegion *R, ProgramStateRef State) {
+ const QualType *Placed = State->get<PlacedObjectTypes>(R);
+ const CXXRecordDecl *DtorClass = Dtor->getParent();
+ if (!Placed || isSameRecord(*Placed, DtorClass))
+ return std::nullopt;
+
+ const auto *Implicit = dyn_cast<CXXDestructorCall>(&Call);
+ std::optional<CFGDeleteDtor> Delete =
+ Implicit ? Implicit->getCFGElementRef()->getAs<CFGDeleteDtor>()
+ : std::nullopt;
+ // Implicit destructors of automatic objects and members are not virtual.
+ bool CallIsVirtual = !Implicit || Delete;
+ if (CallIsVirtual && isVirtualBaseDestruction(*Placed, DtorClass))
+ return std::nullopt;
+ return WrongDestruction{*Placed, DtorClass,
+ Delete ? Delete->getDeleteExpr() : nullptr};
+}
+
+// A destructor without a body destroys members, and the analyzer then destroys
+// only the last element of an array, out of the checker's sight.
+static std::optional<std::pair<const MemRegion *, WrongDestruction>>
+findHiddenWrongDestruction(const CallEvent &Call, const MemRegion *R,
+ ProgramStateRef State) {
+ const MemRegion *Scope = R;
+ if (const auto *ER = dyn_cast<ElementRegion>(R);
+ ER && isa<CXXDestructorCall>(Call))
+ Scope = ER->getSuperRegion();
+ for (const auto &[Key, Placed] : State->get<PlacedObjectTypes>()) {
+ QualType StorageType = getStorageType(Key);
+ const CXXRecordDecl *RD =
+ StorageType.isNull() ? nullptr : StorageType->getAsCXXRecordDecl();
+ if (RD && Key != R && Key->isSubRegionOf(Scope) &&
+ !isSameRecord(Placed, RD))
+ return std::make_pair(Key, WrongDestruction{Placed, RD, nullptr});
+ }
+ return std::nullopt;
+}
+
+void DestroyedAsWrongTypeChecker::checkPreCall(const CallEvent &Call,
+ CheckerContext &C) const {
+ const auto *Dtor = dyn_cast_if_present<CXXDestructorDecl>(Call.getDecl());
+ if (!Dtor)
+ return;
+
+ const auto *Implicit = dyn_cast<CXXDestructorCall>(&Call);
+ if (Implicit && Implicit->isBaseDestructor())
+ return;
+
+ const MemRegion *R = getDestroyedRegion(Call, C);
+ if (!R)
+ return;
+ ProgramStateRef State = C.getState();
+ if (std::optional<WrongDestruction> W =
+ findWrongDestruction(Call, Dtor, R, State)) {
+ reportOrDefer(R, *W, C);
+ return;
+ }
+ if (Call.getRuntimeDefinition().getDecl())
+ return;
+ if (auto Hidden = findHiddenWrongDestruction(Call, R, State))
+ reportOrDefer(Hidden->first, Hidden->second, C);
+}
+
+void DestroyedAsWrongTypeChecker::checkPostCall(const CallEvent &Call,
+ CheckerContext &C) const {
+ PendingDestructionsTy Pending = C.getState()->get<PendingDestructions>();
+ if (Pending.isEmpty() || isInStdFrame(C))
+ return;
+ const auto &[R, W] = *Pending.begin();
+ reportBug(R, W, C);
+}
+
+void DestroyedAsWrongTypeChecker::checkDeadSymbols(SymbolReaper &SR,
+ CheckerContext &C) const {
+ ProgramStateRef State = C.getState();
+ for (const MemRegion *R :
+ llvm::make_first_range(State->get<PlacedObjectTypes>()))
+ if (!SR.isLiveRegion(R))
+ State = State->remove<PlacedObjectTypes>(R);
+ for (const MemRegion *R : State->get<NewAllocatedObjects>())
+ if (!SR.isLiveRegion(R))
+ State = State->remove<NewAllocatedObjects>(R);
+ C.addTransition(State);
+}
+
+void ento::registerDestroyedAsWrongTypeChecker(CheckerManager &Mgr) {
+ Mgr.registerChecker<DestroyedAsWrongTypeChecker>();
+}
+
+bool ento::shouldRegisterDestroyedAsWrongTypeChecker(const CheckerManager &) {
+ return true;
+}
diff --git a/clang/test/Analysis/destroyed-as-wrong-type.cpp b/clang/test/Analysis/destroyed-as-wrong-type.cpp
new file mode 100644
index 00000000000000..0b7a22c25392b0
--- /dev/null
+++ b/clang/test/Analysis/destroyed-as-wrong-type.cpp
@@ -0,0 +1,358 @@
+// RUN: %clang_analyze_cc1 -std=c++11 %s \
+// RUN: -analyzer-checker=core,cplusplus.DestroyedAsWrongType \
+// RUN: -analyzer-output=text -verify -triple x86_64-unknown-linux-gnu
+
+#include "Inputs/system-header-simulator-cxx.h"
+
+struct A {};
+
+struct B {
+ ~B();
+};
+
+void consume(void *);
+
+void replace_local() {
+ B b;
+ new (&b) A; // expected-note{{Object of type 'A' is created here by placement new}}
+} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+
+void replace_heap() {
+ B *b = new B;
+ new (b) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ delete b; // expected-warning{{Deleting an object of type 'A' through a pointer to 'B'}} expected-note{{Deleting an object of type 'A' through a pointer to 'B'}}
+}
+
+struct Base {
+ ~Base();
+};
+struct Derived : Base {};
+
+void delete_through_base_without_virtual_dtor() {
+ Base *p = new Base;
+ new (p) Derived; // expected-note{{Object of type 'Derived' is created here by placement new}}
+ delete p; // expected-warning{{Deleting an object of type 'Derived' through a pointer to 'Base'}} expected-note{{Deleting an object of type 'Derived' through a pointer to 'Base'}}
+}
+
+struct Holder { // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ B Member;
+};
+
+void replace_member() {
+ Holder h;
+ new (&h.Member) A; // expected-note{{Object of type 'A' is created here by placement new}}
+} // expected-note{{Calling implicit destructor for 'Holder'}}
+
+void destroy_then_replace() {
+ B b;
+ b.~B();
+ new (&b) A; // expected-note{{Object of type 'A' is created here by placement new}}
+} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+
+void explicit_destructor_on_replaced_storage() {
+ B b;
+ new (&b) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ b.~B(); // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+}
+
+void restore_after_destroying_placed_object() {
+ B b;
+ b.~B();
+ new (&b) A;
+ reinterpret_cast<A *>(&b)->~A();
+ new (&b) B;
+} // no-warning
+
+void reconstruct_original_type() {
+ B b;
+ b.~B();
+ new (&b) B;
+} // no-warning
+
+void reconstruct_on_heap() {
+ B *b = new B;
+ b->~B();
+ new (b) B;
+ delete b; // no-warning
+}
+
+struct VBase {
+ virtual ~VBase();
+};
+struct VDerived : VBase {};
+
+void delete_through_base_with_virtual_dtor() {
+ VBase *p = new VBase;
+ p->~VBase();
+ new (p) VDerived;
+ delete p; // no-warning
+}
+
+void explicit_virtual_destructor_through_base() {
+ VBase *p = new VBase;
+ p->~VBase();
+ new (p) VDerived;
+ p->~VBase(); // no-warning
+}
+
+void storage_passed_to_opaque_function() {
+ B b;
+ new (&b) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ consume(&b);
+} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+
+struct WithDtor {
+ ~WithDtor();
+};
+struct DerivedFromWithDtor : WithDtor {};
+
+void raw_memory_destroyed_through_base() {
+ void *Raw = ::operator new(sizeof(DerivedFromWithDtor));
+ WithDtor *P = new (Raw) DerivedFromWithDtor;
+ P->~WithDtor();
+ ::operator delete(Raw);
+} // no-warning
+
+void raw_local_buffer() {
+ alignas(B) unsigned char Buf[sizeof(B)];
+ B *P = new (Buf) B;
+ P->~B();
+} // no-warning
+
+union OneOf {
+ B First;
+ A Second;
+ OneOf() { new (this) B; }
+ ~OneOf();
+};
+
+void union_member_created_through_union_address() {
+ OneOf U;
+ U.~OneOf();
+ new (&U) OneOf;
+} // no-warning
+
+struct Reassignable {
+ Reassignable();
+ Reassignable(const Reassignable &);
+ ~Reassignable();
+ Reassignable &operator=(const Reassignable &Other) {
+ this->~Reassignable();
+ new (this) Reassignable(Other); // expected-note{{Object of type 'Reassignable' is created here by placement new}}
+ return *this;
+ }
+};
+struct WrapsReassignable : Reassignable {};
+
+void recreate_base_subobject(const WrapsReassignable &Other) {
+ WrapsReassignable W;
+ W = Other; // expected-note{{Calling implicit copy assignment operator for 'WrapsReassignable'}} expected-note{{Calling copy assignment operator for 'Reassignable'}} expected-note{{Returning from copy assignment operator for 'Reassignable'}} expected-note{{Returning from copy assignment operator for 'WrapsReassignable'}}
+} // expected-warning{{Destructor of 'WrapsReassignable' is called on storage that holds an object of type 'Reassignable'}} expected-note{{Destructor of 'WrapsReassignable' is called on storage that holds an object of type 'Reassignable'}}
+
+struct Trivial {
+ int X;
+};
+
+void trivially_destructible_storage() {
+ Trivial t;
+ new (&t) A;
+} // no-warning
+
+struct WithPlacementNew {
+ ~WithPlacementNew();
+ static void *operator new(size_t, void *P) { return P; }
+};
+
+void restore_through_class_placement_new() {
+ WithPlacementNew W;
+ W.~WithPlacementNew();
+ ::new (&W) A;
+ new (&W) WithPlacementNew;
+} // no-warning
+
+struct WithOpaquePlacementNew {
+ ~WithOpaquePlacementNew();
+ static void *operator new(size_t, void *P);
+};
+
+void restore_through_opaque_class_placement_new() {
+ WithOpaquePlacementNew W;
+ W.~WithOpaquePlacementNew();
+ ::new (&W) A;
+ new (&W) WithOpaquePlacementNew;
+} // no-warning
+
+struct OffsetHolder {
+ int X;
+ B Member;
+};
+
+void restore_member_through_byte_offset() {
+ OffsetHolder H;
+ H.Member.~B();
+ ::new (&H.Member) A;
+ ::new (reinterpret_cast<char *>(&H) + __builtin_offsetof(OffsetHolder, Member)) B;
+} // no-warning
+
+struct PlacementTag {};
+struct WithTaggedPlacementNew {
+ ~WithTaggedPlacementNew();
+ static void *operator new(size_t, PlacementTag, void *P) { return P; }
+};
+
+void restore_through_tagged_placement_new() {
+ WithTaggedPlacementNew W;
+ W.~WithTaggedPlacementNew();
+ ::new (&W) A;
+ new (PlacementTag{}, &W) WithTaggedPlacementNew;
+} // no-warning
+
+struct PlacedWithClassNew {
+ static void *operator new(size_t, void *P) { return P; }
+};
+
+void replace_through_class_placement_new() {
+ B b;
+ new (&b) PlacedWithClassNew; // expected-note{{Object of type 'PlacedWithClassNew' is created here by placement new}}
+} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'PlacedWithClassNew'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'PlacedWithClassNew'}}
+
+struct EscapingHolder { // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ B Member;
+};
+
+void member_passed_to_opaque_function_with_parent() {
+ EscapingHolder H;
+ new (&H.Member) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ consume(&H);
+} // expected-note{{Calling implicit destructor for 'EscapingHolder'}}
+
+struct MutatedHolder { // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ B Member;
+ void mutate();
+};
+
+void member_of_object_with_opaque_method() {
+ MutatedHolder H;
+ new (&H.Member) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ H.mutate();
+} // expected-note{{Calling implicit destructor for 'MutatedHolder'}}
+
+struct HeapHolder { // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ B Member;
+};
+
+void heap_member_passed_to_opaque_function_with_parent() {
+ HeapHolder *H = new HeapHolder;
+ new (&H->Member) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ consume(H);
+ delete H; // expected-note{{Calling implicit destructor for 'HeapHolder'}}
+}
+
+struct OpaqueDtorHolder {
+ B Member;
+ ~OpaqueDtorHolder();
+};
+
+void member_destroyed_by_opaque_destructor() {
+ OpaqueDtorHolder H;
+ new (&H.Member) A; // expected-note{{Object of type 'A' is created here by placement new}}
+} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+
+void member_restored_before_opaque_destructor() {
+ OpaqueDtorHolder H;
+ H.Member.~B();
+ new (&H.Member) A;
+ reinterpret_cast<A *>(&H.Member)->~A();
+ new (&H.Member) B;
+} // no-warning
+
+void array_element() {
+ B Arr[2];
+ new (&Arr[1]) A; // expected-note{{Object of type 'A' is created here by placement new}}
+} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+
+void first_array_element() {
+ B Arr[2];
+ new (&Arr[0]) A; // expected-note{{Object of type 'A' is created here by placement new}}
+} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+
+void array_element_restored() {
+ B Arr[2];
+ Arr[1].~B();
+ new (&Arr[1]) A;
+ reinterpret_cast<A *>(&Arr[1])->~A();
+ new (&Arr[1]) B;
+} // no-warning
+
+void heap_array_element() {
+ B *Arr = new B[2];
+ new (&Arr[1]) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ delete[] Arr; // expected-warning{{Deleting an object of type 'A' through a pointer to 'B'}} expected-note{{Deleting an object of type 'A' through a pointer to 'B'}}
+}
+
+void heap_first_array_element() {
+ B *Arr = new B[2];
+ new (&Arr[0]) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ delete[] Arr; // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+}
+
+struct CastBase {
+ ~CastBase();
+};
+struct CastDerived : CastBase {};
+
+void recreate_base_through_reinterpret_cast() {
+ CastDerived D;
+ reinterpret_cast<CastBase *>(&D)->~CastBase();
+ new (reinterpret_cast<CastBase *>(&D)) CastBase; // expected-note{{Object of type 'CastBase' is created here by placement new}}
+} // expected-warning{{Destructor of 'CastDerived' is called on storage that holds an object of type 'CastBase'}} expected-note{{Destructor of 'CastDerived' is called on storage that holds an object of type 'CastBase'}}
+
+void restore_through_array_placement_new() {
+ B b;
+ b.~B();
+ new (&b) A;
+ new (&b) B[1];
+} // no-warning
+
+void heap_destroy_then_replace() {
+ B *P = new B;
+ P->~B();
+ new (P) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ delete P; // expected-warning{{Deleting an object of type 'A' through a pointer to 'B'}} expected-note{{Deleting an object of type 'A' through a pointer to 'B'}}
+}
+
+void heap_recreate_base_through_reinterpret_cast() {
+ CastDerived *P = new CastDerived;
+ P->~CastDerived();
+ new (reinterpret_cast<CastBase *>(P)) CastBase; // expected-note{{Object of type 'CastBase' is created here by placement new}}
+ delete P; // expected-warning{{Deleting an object of type 'CastBase' through a pointer to 'CastDerived'}} expected-note{{Deleting an object of type 'CastBase' through a pointer to 'CastDerived'}}
+}
+
+template <class T> void placeInto(void *P) {
+ ::new (P) T; // expected-note{{Object of type 'A' is created here by placement new}}
+}
+
+void replace_from_template() {
+ B b;
+ placeInto<A>(&b); // expected-note{{Calling 'placeInto<A>'}} expected-note{{Returning from 'placeInto<A>'}}
+} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+
+namespace std {
+template <class T> void destroy_at(T *P) { P->~T(); }
+template <class T> struct default_delete {
+ void operator()(T *P) const { delete P; }
+};
+} // namespace std
+
+void destroy_at_on_replaced_storage() {
+ B b;
+ new (&b) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ std::destroy_at(&b); // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ new (&b) B;
+}
+
+void delete_in_std_deleter() {
+ B *P = new B;
+ new (P) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ std::default_delete<B>()(P); // expected-warning{{Deleting an object of type 'A' through a pointer to 'B'}} expected-note{{Deleting an object of type 'A' through a pointer to 'B'}}
+}
>From 1f158ac3ac00a6779ab03a2b00075f1d60bc4841 Mon Sep 17 00:00:00 2001
From: Mark Zilber <markusbusiness69 at gmail.com>
Date: Wed, 4 Nov 2026 20:59:54 +0200
Subject: [PATCH 2/4] Address code review comments
---
clang/docs/analyzer/checkers.md | 16 +-
.../Core/PathSensitive/MemRegion.h | 10 +-
.../Checkers/DestroyedAsWrongTypeChecker.cpp | 125 +++++---
.../test/Analysis/destroyed-as-wrong-type.cpp | 290 ++++++++++++++----
4 files changed, 332 insertions(+), 109 deletions(-)
diff --git a/clang/docs/analyzer/checkers.md b/clang/docs/analyzer/checkers.md
index b653fddcb37183..5ac67ea16cf227 100644
--- a/clang/docs/analyzer/checkers.md
+++ b/clang/docs/analyzer/checkers.md
@@ -466,11 +466,14 @@ type and is then destroyed or deleted as the original type
([basic.life]/11, [expr.delete]/3). Destructor calls and deletions inside the
standard library, such as `std::destroy_at`, are reported at the call site.
-Deleting or destroying the object through a base class with a virtual
-destructor is allowed. Placement new into raw storage, such as a character
-buffer or memory from `::operator new`, into a union and into an object with a
-trivial destructor is not reported. Members and array elements destroyed by a
-destructor that is not inlined are checked when that destructor is called.
+Deleting a single object through a base class with a virtual destructor, a
+destroying `operator delete` and an explicit destructor call of a base class
+are allowed. Placement new into raw storage, such as a character buffer or
+memory from `::operator new`, into a union and into an object with a trivial
+destructor is not reported. Members and array elements destroyed by a
+destructor that is not inlined are checked when that destructor is called. A
+report inside the standard library names the function that made the call, for
+example `by 'std::destroy_at'`.
```cpp
class A {};
@@ -482,8 +485,7 @@ public:
void test1() {
B b;
new (&b) A;
-} // warn: destructor of 'B' is called on storage that holds an object of
- // type 'A'
+} // warn: destructor of 'B' is called on an object of type 'A'
void test2() {
B *b = new B;
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
index c3d6d552d5e562..fc0a34299f99cf 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
@@ -66,7 +66,7 @@ class RegionOffset {
const MemRegion *R = nullptr;
/// The bit offset within the base region. Can be negative.
- int64_t Offset;
+ int64_t Offset = 0;
public:
// We're using a const instead of an enumeration due to the size required;
@@ -87,6 +87,14 @@ class RegionOffset {
}
bool isValid() const { return R; }
+
+ /// Symbolic offsets with the same base region compare equal even if they
+ /// describe different locations.
+ bool operator==(const RegionOffset &Other) const {
+ return R == Other.R && Offset == Other.Offset;
+ }
+
+ bool operator!=(const RegionOffset &Other) const { return !(*this == Other); }
};
//===----------------------------------------------------------------------===//
diff --git a/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp
index 1cb117cfd37125..eac467151e3715 100644
--- a/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp
@@ -20,6 +20,7 @@
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "llvm/Support/FormatVariadic.h"
#include <optional>
using namespace clang;
@@ -39,11 +40,32 @@ struct WrongDestruction {
ID.AddPointer(DtorClass);
ID.AddPointer(Delete);
}
+
+ std::string getReportMessage(const PrintingPolicy &PP,
+ const NamedDecl *StdCaller) const {
+ std::string Caller;
+ if (StdCaller)
+ Caller =
+ llvm::formatv(" by '{0}'", StdCaller->getQualifiedNameAsString());
+ if (Delete)
+ return llvm::formatv(
+ "Deleting an object of type '{0}' through a pointer to '{1}'{2}",
+ Placed.getAsString(PP),
+ Delete->getDestroyedType().getUnqualifiedType().getAsString(PP),
+ Caller);
+ return llvm::formatv("Destructor of '{0}' is called{1} on storage that "
+ "holds an object of type '{2}'",
+ DtorClass->getQualifiedNameAsString(), Caller,
+ Placed.getAsString(PP));
+ }
};
} // namespace
+// Storage reused by placement new -> type of the new object.
REGISTER_MAP_WITH_PROGRAMSTATE(PlacedObjectTypes, const MemRegion *, QualType)
+// Memory from a non-placement new, which holds an original object.
REGISTER_SET_WITH_PROGRAMSTATE(NewAllocatedObjects, const MemRegion *)
+// Found inside std; reported on return to user code.
REGISTER_MAP_WITH_PROGRAMSTATE(PendingDestructions, const MemRegion *,
WrongDestruction)
@@ -55,7 +77,7 @@ class DestroyedAsWrongTypeChecker
categories::MemoryError};
void reportBug(const MemRegion *R, const WrongDestruction &W,
- CheckerContext &C) const;
+ CheckerContext &C, const NamedDecl *StdCaller = nullptr) const;
void reportOrDefer(const MemRegion *R, const WrongDestruction &W,
CheckerContext &C) const;
@@ -78,8 +100,7 @@ static const MemRegion *getStorageRegion(SVal V, CheckerContext &C) {
const ArrayType *AT = Ctx.getAsArrayType(TR->getValueType());
if (!AT)
break;
- R = C.getStoreManager().getRegionManager().getElementRegion(
- AT->getElementType(), C.getSValBuilder().makeZeroArrayIndex(), TR, Ctx);
+ R = C.getStoreManager().GetElementZeroRegion(TR, AT->getElementType());
}
return R;
}
@@ -111,18 +132,18 @@ static QualType getStorageType(const MemRegion *R) {
// A field and a byte offset from its parent are different regions.
static bool isSameLocation(const MemRegion *A, const MemRegion *B) {
+ if (A == B)
+ return true;
RegionOffset OA = A->getAsOffset();
RegionOffset OB = B->getAsOffset();
- return OA.isValid() && OB.isValid() && !OA.hasSymbolicOffset() &&
- !OB.hasSymbolicOffset() && OA.getRegion() == OB.getRegion() &&
- OA.getOffset() == OB.getOffset();
+ return OA.isValid() && !OA.hasSymbolicOffset() && OA == OB;
}
static ProgramStateRef forgetPlacedTypes(ProgramStateRef State,
const MemRegion *R) {
for (const MemRegion *Key :
llvm::make_first_range(State->get<PlacedObjectTypes>()))
- if (Key == R || Key->isSubRegionOf(R) || isSameLocation(Key, R))
+ if (Key->isSubRegionOf(R) || isSameLocation(Key, R))
State = State->remove<PlacedObjectTypes>(Key);
return State;
}
@@ -138,27 +159,19 @@ getPlacementStorages(const CXXNewExpr *NE, CheckerContext &C) {
}
static bool isInStdFrame(CheckerContext &C) {
- return AnalysisDeclContext::isInStdNamespace(C.getStackFrame()->getDecl());
+ const Decl *D = C.getStackFrame()->getDecl();
+ return D && AnalysisDeclContext::isInStdNamespace(D);
}
void DestroyedAsWrongTypeChecker::reportBug(const MemRegion *R,
const WrongDestruction &W,
- CheckerContext &C) const {
- ExplodedNode *N = C.generateErrorNode();
+ CheckerContext &C,
+ const NamedDecl *StdCaller) const {
+ ExplodedNode *N = C.addSink();
if (!N)
return;
- const PrintingPolicy &PP = C.getASTContext().getPrintingPolicy();
- std::string Placed = W.Placed.getAsString(PP);
std::string Msg =
- W.Delete
- ? "Deleting an object of type '" + Placed +
- "' through a pointer to '" +
- W.Delete->getDestroyedType().getUnqualifiedType().getAsString(
- PP) +
- "'"
- : "Destructor of '" + W.DtorClass->getQualifiedNameAsString() +
- "' is called on storage that holds an object of type '" +
- Placed + "'";
+ W.getReportMessage(C.getASTContext().getPrintingPolicy(), StdCaller);
auto Report = std::make_unique<PathSensitiveBugReport>(BT, Msg, N);
Report->markInteresting(R);
C.emitReport(std::move(Report));
@@ -181,7 +194,7 @@ void DestroyedAsWrongTypeChecker::checkPostStmt(const CXXNewExpr *NE,
// The result may be typed as the new object, so use the storage argument.
const MemRegion *R = nullptr;
for (const MemRegion *Storage : Storages)
- if (OperatorNew->isReservedGlobalPlacementOperator() || Storage == Result ||
+ if (OperatorNew->isReservedGlobalPlacementOperator() ||
isSameLocation(Storage, Result))
R = Storage;
if (!R) {
@@ -216,13 +229,13 @@ void DestroyedAsWrongTypeChecker::checkPostStmt(const CXXNewExpr *NE,
C.addTransition(State->set<PlacedObjectTypes>(R, Placed), Tag);
}
-// Destroying through a base class with a virtual destructor is well-defined.
-static bool isVirtualBaseDestruction(QualType Placed,
- const CXXRecordDecl *Static) {
+static bool isDerivedFrom(QualType Placed, const CXXRecordDecl *Base) {
const CXXRecordDecl *PlacedRD = Placed->getAsCXXRecordDecl();
- if (!PlacedRD || !PlacedRD->isDerivedFrom(Static))
- return false;
- const CXXDestructorDecl *Dtor = Static->getDestructor();
+ return PlacedRD && PlacedRD->isDerivedFrom(Base);
+}
+
+static bool hasVirtualDestructor(const CXXRecordDecl *RD) {
+ const CXXDestructorDecl *Dtor = RD->getDestructor();
return Dtor && Dtor->isVirtual();
}
@@ -252,30 +265,37 @@ findWrongDestruction(const CallEvent &Call, const CXXDestructorDecl *Dtor,
return std::nullopt;
const auto *Implicit = dyn_cast<CXXDestructorCall>(&Call);
+ // An explicit destructor call may name a base class ([class.dtor]p16).
+ if (!Implicit)
+ return isDerivedFrom(*Placed, DtorClass)
+ ? std::nullopt
+ : std::optional(WrongDestruction{*Placed, DtorClass, nullptr});
+
std::optional<CFGDeleteDtor> Delete =
- Implicit ? Implicit->getCFGElementRef()->getAs<CFGDeleteDtor>()
- : std::nullopt;
- // Implicit destructors of automatic objects and members are not virtual.
- bool CallIsVirtual = !Implicit || Delete;
- if (CallIsVirtual && isVirtualBaseDestruction(*Placed, DtorClass))
+ Implicit->getCFGElementRef()->getAs<CFGDeleteDtor>();
+ if (!Delete)
+ return WrongDestruction{*Placed, DtorClass, nullptr};
+ const CXXDeleteExpr *DE = Delete->getDeleteExpr();
+ // [expr.delete]p3 does not cover a destroying operator delete, and allows a
+ // base class with a virtual destructor only for a single object.
+ const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
+ if (OperatorDelete && OperatorDelete->isDestroyingOperatorDelete())
return std::nullopt;
- return WrongDestruction{*Placed, DtorClass,
- Delete ? Delete->getDeleteExpr() : nullptr};
+ if (!DE->isArrayForm() && isDerivedFrom(*Placed, DtorClass) &&
+ hasVirtualDestructor(DtorClass))
+ return std::nullopt;
+ return WrongDestruction{*Placed, DtorClass, DE};
}
-// A destructor without a body destroys members, and the analyzer then destroys
-// only the last element of an array, out of the checker's sight.
+// Finds a wrong destruction of storage within Scope other than R itself.
static std::optional<std::pair<const MemRegion *, WrongDestruction>>
-findHiddenWrongDestruction(const CallEvent &Call, const MemRegion *R,
+findHiddenWrongDestruction(const MemRegion *R, const MemRegion *Scope,
ProgramStateRef State) {
- const MemRegion *Scope = R;
- if (const auto *ER = dyn_cast<ElementRegion>(R);
- ER && isa<CXXDestructorCall>(Call))
- Scope = ER->getSuperRegion();
for (const auto &[Key, Placed] : State->get<PlacedObjectTypes>()) {
QualType StorageType = getStorageType(Key);
- const CXXRecordDecl *RD =
- StorageType.isNull() ? nullptr : StorageType->getAsCXXRecordDecl();
+ if (StorageType.isNull())
+ continue;
+ const CXXRecordDecl *RD = StorageType->getAsCXXRecordDecl();
if (RD && Key != R && Key->isSubRegionOf(Scope) &&
!isSameRecord(Placed, RD))
return std::make_pair(Key, WrongDestruction{Placed, RD, nullptr});
@@ -302,9 +322,15 @@ void DestroyedAsWrongTypeChecker::checkPreCall(const CallEvent &Call,
reportOrDefer(R, *W, C);
return;
}
- if (Call.getRuntimeDefinition().getDecl())
+ // The analyzer may destroy an array with a single call on its last element,
+ // and does not show the destruction of members by a destructor without a
+ // body, so check these here.
+ const MemRegion *Scope = R;
+ if (const auto *ER = dyn_cast<ElementRegion>(R); ER && Implicit)
+ Scope = ER->getSuperRegion();
+ else if (Call.getRuntimeDefinition().getDecl())
return;
- if (auto Hidden = findHiddenWrongDestruction(Call, R, State))
+ if (auto Hidden = findHiddenWrongDestruction(R, Scope, State))
reportOrDefer(Hidden->first, Hidden->second, C);
}
@@ -314,7 +340,7 @@ void DestroyedAsWrongTypeChecker::checkPostCall(const CallEvent &Call,
if (Pending.isEmpty() || isInStdFrame(C))
return;
const auto &[R, W] = *Pending.begin();
- reportBug(R, W, C);
+ reportBug(R, W, C, dyn_cast_if_present<NamedDecl>(Call.getDecl()));
}
void DestroyedAsWrongTypeChecker::checkDeadSymbols(SymbolReaper &SR,
@@ -334,6 +360,7 @@ void ento::registerDestroyedAsWrongTypeChecker(CheckerManager &Mgr) {
Mgr.registerChecker<DestroyedAsWrongTypeChecker>();
}
-bool ento::shouldRegisterDestroyedAsWrongTypeChecker(const CheckerManager &) {
- return true;
+bool ento::shouldRegisterDestroyedAsWrongTypeChecker(
+ const CheckerManager &Mgr) {
+ return Mgr.getLangOpts().CPlusPlus;
}
diff --git a/clang/test/Analysis/destroyed-as-wrong-type.cpp b/clang/test/Analysis/destroyed-as-wrong-type.cpp
index 0b7a22c25392b0..9f8e4454058d15 100644
--- a/clang/test/Analysis/destroyed-as-wrong-type.cpp
+++ b/clang/test/Analysis/destroyed-as-wrong-type.cpp
@@ -1,6 +1,9 @@
// RUN: %clang_analyze_cc1 -std=c++11 %s \
// RUN: -analyzer-checker=core,cplusplus.DestroyedAsWrongType \
// RUN: -analyzer-output=text -verify -triple x86_64-unknown-linux-gnu
+// RUN: %clang_analyze_cc1 -std=c++20 %s \
+// RUN: -analyzer-checker=core,cplusplus.DestroyedAsWrongType \
+// RUN: -analyzer-output=text -verify -triple x86_64-unknown-linux-gnu
#include "Inputs/system-header-simulator-cxx.h"
@@ -14,13 +17,19 @@ void consume(void *);
void replace_local() {
B b;
- new (&b) A; // expected-note{{Object of type 'A' is created here by placement new}}
-} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ new (&b) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+}
+// expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+// expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
void replace_heap() {
B *b = new B;
- new (b) A; // expected-note{{Object of type 'A' is created here by placement new}}
- delete b; // expected-warning{{Deleting an object of type 'A' through a pointer to 'B'}} expected-note{{Deleting an object of type 'A' through a pointer to 'B'}}
+ new (b) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+ delete b;
+ // expected-warning at -1 {{Deleting an object of type 'A' through a pointer to 'B'}}
+ // expected-note at -2 {{Deleting an object of type 'A' through a pointer to 'B'}}
}
struct Base {
@@ -30,29 +39,42 @@ struct Derived : Base {};
void delete_through_base_without_virtual_dtor() {
Base *p = new Base;
- new (p) Derived; // expected-note{{Object of type 'Derived' is created here by placement new}}
- delete p; // expected-warning{{Deleting an object of type 'Derived' through a pointer to 'Base'}} expected-note{{Deleting an object of type 'Derived' through a pointer to 'Base'}}
+ new (p) Derived;
+ // expected-note at -1 {{Object of type 'Derived' is created here by placement new}}
+ delete p;
+ // expected-warning at -1 {{Deleting an object of type 'Derived' through a pointer to 'Base'}}
+ // expected-note at -2 {{Deleting an object of type 'Derived' through a pointer to 'Base'}}
}
-struct Holder { // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+struct Holder {
+ // expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ // expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
B Member;
};
void replace_member() {
Holder h;
- new (&h.Member) A; // expected-note{{Object of type 'A' is created here by placement new}}
-} // expected-note{{Calling implicit destructor for 'Holder'}}
+ new (&h.Member) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+}
+// expected-note at -1 {{Calling implicit destructor for 'Holder'}}
void destroy_then_replace() {
B b;
b.~B();
- new (&b) A; // expected-note{{Object of type 'A' is created here by placement new}}
-} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ new (&b) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+}
+// expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+// expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
void explicit_destructor_on_replaced_storage() {
B b;
- new (&b) A; // expected-note{{Object of type 'A' is created here by placement new}}
- b.~B(); // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ new (&b) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+ b.~B();
+ // expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ // expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
}
void restore_after_destroying_placed_object() {
@@ -88,6 +110,16 @@ void delete_through_base_with_virtual_dtor() {
delete p; // no-warning
}
+void array_delete_through_base_with_virtual_dtor() {
+ VBase *p = new VBase[1];
+ p->~VBase();
+ new (p) VDerived;
+ // expected-note at -1 {{Object of type 'VDerived' is created here by placement new}}
+ delete[] p;
+ // expected-warning at -1 {{Deleting an object of type 'VDerived' through a pointer to 'VBase'}}
+ // expected-note at -2 {{Deleting an object of type 'VDerived' through a pointer to 'VBase'}}
+}
+
void explicit_virtual_destructor_through_base() {
VBase *p = new VBase;
p->~VBase();
@@ -95,11 +127,38 @@ void explicit_virtual_destructor_through_base() {
p->~VBase(); // no-warning
}
+struct BaseWithData {
+ int X;
+ ~BaseWithData();
+};
+struct DerivedFromBaseWithData : BaseWithData {};
+
+void explicit_base_destructor_on_derived_object() {
+ BaseWithData b;
+ b.~BaseWithData();
+ auto *D = new (&b) DerivedFromBaseWithData;
+ static_cast<BaseWithData *>(D)->~BaseWithData();
+ new (&b) BaseWithData;
+} // no-warning
+
+void explicit_base_destructor_without_restoring() {
+ BaseWithData b;
+ b.~BaseWithData();
+ auto *D = new (&b) DerivedFromBaseWithData;
+ // expected-note at -1 {{Object of type 'DerivedFromBaseWithData' is created here by placement new}}
+ static_cast<BaseWithData *>(D)->~BaseWithData();
+}
+// expected-warning at -1 {{Destructor of 'BaseWithData' is called on storage that holds an object of type 'DerivedFromBaseWithData'}}
+// expected-note at -2 {{Destructor of 'BaseWithData' is called on storage that holds an object of type 'DerivedFromBaseWithData'}}
+
void storage_passed_to_opaque_function() {
B b;
- new (&b) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ new (&b) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
consume(&b);
-} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+}
+// expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+// expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
struct WithDtor {
~WithDtor();
@@ -138,7 +197,8 @@ struct Reassignable {
~Reassignable();
Reassignable &operator=(const Reassignable &Other) {
this->~Reassignable();
- new (this) Reassignable(Other); // expected-note{{Object of type 'Reassignable' is created here by placement new}}
+ new (this) Reassignable(Other);
+ // expected-note at -1 {{Object of type 'Reassignable' is created here by placement new}}
return *this;
}
};
@@ -146,8 +206,14 @@ struct WrapsReassignable : Reassignable {};
void recreate_base_subobject(const WrapsReassignable &Other) {
WrapsReassignable W;
- W = Other; // expected-note{{Calling implicit copy assignment operator for 'WrapsReassignable'}} expected-note{{Calling copy assignment operator for 'Reassignable'}} expected-note{{Returning from copy assignment operator for 'Reassignable'}} expected-note{{Returning from copy assignment operator for 'WrapsReassignable'}}
-} // expected-warning{{Destructor of 'WrapsReassignable' is called on storage that holds an object of type 'Reassignable'}} expected-note{{Destructor of 'WrapsReassignable' is called on storage that holds an object of type 'Reassignable'}}
+ W = Other;
+ // expected-note at -1 {{Calling implicit copy assignment operator for 'WrapsReassignable'}}
+ // expected-note at -2 {{Calling copy assignment operator for 'Reassignable'}}
+ // expected-note at -3 {{Returning from copy assignment operator for 'Reassignable'}}
+ // expected-note at -4 {{Returning from copy assignment operator for 'WrapsReassignable'}}
+}
+// expected-warning at -1 {{Destructor of 'WrapsReassignable' is called on storage that holds an object of type 'Reassignable'}}
+// expected-note at -2 {{Destructor of 'WrapsReassignable' is called on storage that holds an object of type 'Reassignable'}}
struct Trivial {
int X;
@@ -213,39 +279,54 @@ struct PlacedWithClassNew {
void replace_through_class_placement_new() {
B b;
- new (&b) PlacedWithClassNew; // expected-note{{Object of type 'PlacedWithClassNew' is created here by placement new}}
-} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'PlacedWithClassNew'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'PlacedWithClassNew'}}
+ new (&b) PlacedWithClassNew;
+ // expected-note at -1 {{Object of type 'PlacedWithClassNew' is created here by placement new}}
+}
+// expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'PlacedWithClassNew'}}
+// expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'PlacedWithClassNew'}}
-struct EscapingHolder { // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+struct EscapingHolder {
+ // expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ // expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
B Member;
};
void member_passed_to_opaque_function_with_parent() {
EscapingHolder H;
- new (&H.Member) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ new (&H.Member) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
consume(&H);
-} // expected-note{{Calling implicit destructor for 'EscapingHolder'}}
+}
+// expected-note at -1 {{Calling implicit destructor for 'EscapingHolder'}}
-struct MutatedHolder { // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+struct MutatedHolder {
+ // expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ // expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
B Member;
void mutate();
};
void member_of_object_with_opaque_method() {
MutatedHolder H;
- new (&H.Member) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ new (&H.Member) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
H.mutate();
-} // expected-note{{Calling implicit destructor for 'MutatedHolder'}}
+}
+// expected-note at -1 {{Calling implicit destructor for 'MutatedHolder'}}
-struct HeapHolder { // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+struct HeapHolder {
+ // expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ // expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
B Member;
};
void heap_member_passed_to_opaque_function_with_parent() {
HeapHolder *H = new HeapHolder;
- new (&H->Member) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ new (&H->Member) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
consume(H);
- delete H; // expected-note{{Calling implicit destructor for 'HeapHolder'}}
+ delete H;
+ // expected-note at -1 {{Calling implicit destructor for 'HeapHolder'}}
}
struct OpaqueDtorHolder {
@@ -255,8 +336,11 @@ struct OpaqueDtorHolder {
void member_destroyed_by_opaque_destructor() {
OpaqueDtorHolder H;
- new (&H.Member) A; // expected-note{{Object of type 'A' is created here by placement new}}
-} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ new (&H.Member) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+}
+// expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+// expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
void member_restored_before_opaque_destructor() {
OpaqueDtorHolder H;
@@ -268,13 +352,19 @@ void member_restored_before_opaque_destructor() {
void array_element() {
B Arr[2];
- new (&Arr[1]) A; // expected-note{{Object of type 'A' is created here by placement new}}
-} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ new (&Arr[1]) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+}
+// expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+// expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
void first_array_element() {
B Arr[2];
- new (&Arr[0]) A; // expected-note{{Object of type 'A' is created here by placement new}}
-} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ new (&Arr[0]) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+}
+// expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+// expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
void array_element_restored() {
B Arr[2];
@@ -284,16 +374,51 @@ void array_element_restored() {
new (&Arr[1]) B;
} // no-warning
+struct InlineDtor {
+ int X;
+ ~InlineDtor() {}
+};
+
+void multidimensional_array_element() {
+ B M[2][3];
+ new (&M[1][1]) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+}
+// expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+// expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+
+void multidimensional_array_element_with_inline_destructor() {
+ InlineDtor M[2][3];
+ new (&M[1][1]) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+}
+// expected-warning at -1 {{Destructor of 'InlineDtor' is called on storage that holds an object of type 'A'}}
+// expected-note at -2 {{Destructor of 'InlineDtor' is called on storage that holds an object of type 'A'}}
+
+void multidimensional_array_element_restored() {
+ B M[2][3];
+ M[1][1].~B();
+ new (&M[1][1]) A;
+ reinterpret_cast<A *>(&M[1][1])->~A();
+ new (&M[1][1]) B;
+} // no-warning
+
void heap_array_element() {
B *Arr = new B[2];
- new (&Arr[1]) A; // expected-note{{Object of type 'A' is created here by placement new}}
- delete[] Arr; // expected-warning{{Deleting an object of type 'A' through a pointer to 'B'}} expected-note{{Deleting an object of type 'A' through a pointer to 'B'}}
+ new (&Arr[1]) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+ delete[] Arr;
+ // expected-warning at -1 {{Deleting an object of type 'A' through a pointer to 'B'}}
+ // expected-note at -2 {{Deleting an object of type 'A' through a pointer to 'B'}}
}
void heap_first_array_element() {
B *Arr = new B[2];
- new (&Arr[0]) A; // expected-note{{Object of type 'A' is created here by placement new}}
- delete[] Arr; // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ new (&Arr[0]) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+ delete[] Arr;
+ // expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ // expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
}
struct CastBase {
@@ -304,8 +429,11 @@ struct CastDerived : CastBase {};
void recreate_base_through_reinterpret_cast() {
CastDerived D;
reinterpret_cast<CastBase *>(&D)->~CastBase();
- new (reinterpret_cast<CastBase *>(&D)) CastBase; // expected-note{{Object of type 'CastBase' is created here by placement new}}
-} // expected-warning{{Destructor of 'CastDerived' is called on storage that holds an object of type 'CastBase'}} expected-note{{Destructor of 'CastDerived' is called on storage that holds an object of type 'CastBase'}}
+ new (reinterpret_cast<CastBase *>(&D)) CastBase;
+ // expected-note at -1 {{Object of type 'CastBase' is created here by placement new}}
+}
+// expected-warning at -1 {{Destructor of 'CastDerived' is called on storage that holds an object of type 'CastBase'}}
+// expected-note at -2 {{Destructor of 'CastDerived' is called on storage that holds an object of type 'CastBase'}}
void restore_through_array_placement_new() {
B b;
@@ -317,42 +445,100 @@ void restore_through_array_placement_new() {
void heap_destroy_then_replace() {
B *P = new B;
P->~B();
- new (P) A; // expected-note{{Object of type 'A' is created here by placement new}}
- delete P; // expected-warning{{Deleting an object of type 'A' through a pointer to 'B'}} expected-note{{Deleting an object of type 'A' through a pointer to 'B'}}
+ new (P) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+ delete P;
+ // expected-warning at -1 {{Deleting an object of type 'A' through a pointer to 'B'}}
+ // expected-note at -2 {{Deleting an object of type 'A' through a pointer to 'B'}}
}
void heap_recreate_base_through_reinterpret_cast() {
CastDerived *P = new CastDerived;
P->~CastDerived();
- new (reinterpret_cast<CastBase *>(P)) CastBase; // expected-note{{Object of type 'CastBase' is created here by placement new}}
- delete P; // expected-warning{{Deleting an object of type 'CastBase' through a pointer to 'CastDerived'}} expected-note{{Deleting an object of type 'CastBase' through a pointer to 'CastDerived'}}
+ new (reinterpret_cast<CastBase *>(P)) CastBase;
+ // expected-note at -1 {{Object of type 'CastBase' is created here by placement new}}
+ delete P;
+ // expected-warning at -1 {{Deleting an object of type 'CastBase' through a pointer to 'CastDerived'}}
+ // expected-note at -2 {{Deleting an object of type 'CastBase' through a pointer to 'CastDerived'}}
}
template <class T> void placeInto(void *P) {
- ::new (P) T; // expected-note{{Object of type 'A' is created here by placement new}}
+ ::new (P) T;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
}
void replace_from_template() {
B b;
- placeInto<A>(&b); // expected-note{{Calling 'placeInto<A>'}} expected-note{{Returning from 'placeInto<A>'}}
-} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ placeInto<A>(&b);
+ // expected-note at -1 {{Calling 'placeInto<A>'}}
+ // expected-note at -2 {{Returning from 'placeInto<A>'}}
+}
+// expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+// expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
namespace std {
template <class T> void destroy_at(T *P) { P->~T(); }
template <class T> struct default_delete {
void operator()(T *P) const { delete P; }
};
+template <class T> struct holder {
+ T Value;
+};
} // namespace std
void destroy_at_on_replaced_storage() {
B b;
- new (&b) A; // expected-note{{Object of type 'A' is created here by placement new}}
- std::destroy_at(&b); // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ new (&b) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+ std::destroy_at(&b);
+ // expected-warning at -1 {{Destructor of 'B' is called by 'std::destroy_at' on storage that holds an object of type 'A'}}
+ // expected-note at -2 {{Destructor of 'B' is called by 'std::destroy_at' on storage that holds an object of type 'A'}}
+ new (&b) B;
+}
+
+void destroy_at_through_function_pointer() {
+ B b;
+ new (&b) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+ void (*Destroy)(B *) = std::destroy_at<B>;
+ Destroy(&b);
+ // expected-warning at -1 {{Destructor of 'B' is called by 'std::destroy_at' on storage that holds an object of type 'A'}}
+ // expected-note at -2 {{Destructor of 'B' is called by 'std::destroy_at' on storage that holds an object of type 'A'}}
new (&b) B;
}
void delete_in_std_deleter() {
B *P = new B;
- new (P) A; // expected-note{{Object of type 'A' is created here by placement new}}
- std::default_delete<B>()(P); // expected-warning{{Deleting an object of type 'A' through a pointer to 'B'}} expected-note{{Deleting an object of type 'A' through a pointer to 'B'}}
+ new (P) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+ std::default_delete<B>()(P);
+ // expected-warning at -1 {{Deleting an object of type 'A' through a pointer to 'B' by 'std::default_delete<B>::operator()'}}
+ // expected-note at -2 {{Deleting an object of type 'A' through a pointer to 'B' by 'std::default_delete<B>::operator()'}}
+}
+
+void member_of_std_object() {
+ std::holder<B> H;
+ new (&H.Value) A;
+ // expected-note at -1 {{Object of type 'A' is created here by placement new}}
+}
+// expected-warning at -1 {{Destructor of 'B' is called by 'std::holder<B>::~holder' on storage that holds an object of type 'A'}}
+// expected-note at -2 {{Destructor of 'B' is called by 'std::holder<B>::~holder' on storage that holds an object of type 'A'}}
+
+#if __cplusplus >= 202002L
+namespace std {
+struct destroying_delete_t {
+ explicit destroying_delete_t() = default;
+};
+} // namespace std
+
+struct WithDestroyingDelete {
+ ~WithDestroyingDelete();
+ void operator delete(WithDestroyingDelete *P, std::destroying_delete_t);
+};
+
+void destroying_operator_delete() {
+ WithDestroyingDelete *P = new WithDestroyingDelete;
+ new (P) A;
+ delete P; // no-warning
}
+#endif
>From 65bdba06a6aef4f9390d268f07dda6ca5db64bea Mon Sep 17 00:00:00 2001
From: Mark Zilber <markusbusiness69 at gmail.com>
Date: Tue, 10 Nov 2026 00:24:50 +0200
Subject: [PATCH 3/4] Address review comments
---
.../Checkers/DestroyedAsWrongTypeChecker.cpp | 28 +++++++++----------
1 file changed, 14 insertions(+), 14 deletions(-)
diff --git a/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp
index eac467151e3715..067e9f9aae4853 100644
--- a/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp
@@ -45,8 +45,7 @@ struct WrongDestruction {
const NamedDecl *StdCaller) const {
std::string Caller;
if (StdCaller)
- Caller =
- llvm::formatv(" by '{0}'", StdCaller->getQualifiedNameAsString());
+ Caller = " by '" + StdCaller->getQualifiedNameAsString() + "'";
if (Delete)
return llvm::formatv(
"Deleting an object of type '{0}' through a pointer to '{1}'{2}",
@@ -64,7 +63,7 @@ struct WrongDestruction {
// Storage reused by placement new -> type of the new object.
REGISTER_MAP_WITH_PROGRAMSTATE(PlacedObjectTypes, const MemRegion *, QualType)
// Memory from a non-placement new, which holds an original object.
-REGISTER_SET_WITH_PROGRAMSTATE(NewAllocatedObjects, const MemRegion *)
+REGISTER_SET_WITH_PROGRAMSTATE(ObjectsAllocatedByNew, const MemRegion *)
// Found inside std; reported on return to user code.
REGISTER_MAP_WITH_PROGRAMSTATE(PendingDestructions, const MemRegion *,
WrongDestruction)
@@ -107,7 +106,7 @@ static const MemRegion *getStorageRegion(SVal V, CheckerContext &C) {
// Storage obtained as raw memory has no original object to be replaced.
static bool holdsOriginalObject(ProgramStateRef State, const MemRegion *R) {
- if (State->contains<NewAllocatedObjects>(R))
+ if (State->contains<ObjectsAllocatedByNew>(R))
return true;
const auto *TR = dyn_cast<TypedValueRegion>(R);
if (!TR)
@@ -130,7 +129,8 @@ static QualType getStorageType(const MemRegion *R) {
return {};
}
-// A field and a byte offset from its parent are different regions.
+// A field and a byte offset from its parent are different regions, but we want
+// to recognize that they refer to the same location.
static bool isSameLocation(const MemRegion *A, const MemRegion *B) {
if (A == B)
return true;
@@ -159,8 +159,7 @@ getPlacementStorages(const CXXNewExpr *NE, CheckerContext &C) {
}
static bool isInStdFrame(CheckerContext &C) {
- const Decl *D = C.getStackFrame()->getDecl();
- return D && AnalysisDeclContext::isInStdNamespace(D);
+ return AnalysisDeclContext::isInStdNamespace(C.getStackFrame()->getDecl());
}
void DestroyedAsWrongTypeChecker::reportBug(const MemRegion *R,
@@ -201,7 +200,7 @@ void DestroyedAsWrongTypeChecker::checkPostStmt(const CXXNewExpr *NE,
// An operator new that is not inlined may have placed the object there.
for (const MemRegion *Storage : Storages)
State = forgetPlacedTypes(State, Storage);
- C.addTransition(State->add<NewAllocatedObjects>(Result));
+ C.addTransition(State->add<ObjectsAllocatedByNew>(Result));
return;
}
@@ -266,10 +265,11 @@ findWrongDestruction(const CallEvent &Call, const CXXDestructorDecl *Dtor,
const auto *Implicit = dyn_cast<CXXDestructorCall>(&Call);
// An explicit destructor call may name a base class ([class.dtor]p16).
- if (!Implicit)
- return isDerivedFrom(*Placed, DtorClass)
- ? std::nullopt
- : std::optional(WrongDestruction{*Placed, DtorClass, nullptr});
+ if (!Implicit) {
+ if (isDerivedFrom(*Placed, DtorClass))
+ return std::nullopt;
+ return WrongDestruction{*Placed, DtorClass, nullptr};
+ }
std::optional<CFGDeleteDtor> Delete =
Implicit->getCFGElementRef()->getAs<CFGDeleteDtor>();
@@ -350,9 +350,9 @@ void DestroyedAsWrongTypeChecker::checkDeadSymbols(SymbolReaper &SR,
llvm::make_first_range(State->get<PlacedObjectTypes>()))
if (!SR.isLiveRegion(R))
State = State->remove<PlacedObjectTypes>(R);
- for (const MemRegion *R : State->get<NewAllocatedObjects>())
+ for (const MemRegion *R : State->get<ObjectsAllocatedByNew>())
if (!SR.isLiveRegion(R))
- State = State->remove<NewAllocatedObjects>(R);
+ State = State->remove<ObjectsAllocatedByNew>(R);
C.addTransition(State);
}
>From eb2405ee64ee99d69f8dda7bf647df7535a4a36c Mon Sep 17 00:00:00 2001
From: Mark Zilber <markusbusiness69 at gmail.com>
Date: Sat, 14 Nov 2026 22:20:47 +0200
Subject: [PATCH 4/4] fix bugs in BugReporterVisitor and
DynamicTypePropagation, rewrite checker with DynamicTypePropagation
---
.../clang/StaticAnalyzer/Checkers/Checkers.td | 1 +
.../Core/PathSensitive/DynamicType.h | 19 ++
.../Checkers/DestroyedAsWrongTypeChecker.cpp | 196 ++++++++----------
.../Checkers/DynamicTypePropagation.cpp | 47 ++++-
clang/lib/StaticAnalyzer/Core/DynamicType.cpp | 56 +++++
.../test/Analysis/destroyed-as-wrong-type.cpp | 26 +++
clang/test/Analysis/new-dynamic-types.cpp | 76 ++++++-
7 files changed, 305 insertions(+), 116 deletions(-)
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 14eed2d61ce38a..183461945d08de 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -647,6 +647,7 @@ def ArrayDeleteChecker : Checker<"ArrayDelete">,
def DestroyedAsWrongTypeChecker : Checker<"DestroyedAsWrongType">,
HelpText<"Check for objects destroyed or deleted as a type that their "
"storage no longer holds after placement new">,
+ Dependencies<[DynamicTypePropagation]>,
Documentation<HasDocumentation>;
def InnerPointerChecker : Checker<"InnerPointer">,
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h
index 52d1526b1acf44..c7e2d4ae11d475 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h
@@ -24,6 +24,9 @@
#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
namespace clang {
+class CXXNewExpr;
+class StackFrame;
+
namespace ento {
/// Get dynamic type information for the region \p MR.
@@ -69,6 +72,22 @@ ProgramStateRef setDynamicTypeAndCastInfo(ProgramStateRef State,
QualType CastToTy,
bool IsCastSucceeds);
+/// Remove dynamic type and cast information of the objects in the storage of
+/// \p MR, including its subregions and regions at the same location.
+ProgramStateRef removeDynamicTypeInfoWithin(ProgramStateRef State,
+ const MemRegion *MR);
+
+/// Get the regions within \p MR, including \p MR itself, that have dynamic
+/// type information.
+SmallVector<std::pair<const MemRegion *, DynamicTypeInfo>, 4>
+getDynamicTypeInfoWithin(ProgramStateRef State, const MemRegion *MR);
+
+/// Get the storage in which the placement new expression \p NE created its
+/// object, or null if it is not known.
+const MemRegion *getPlacementNewStorage(ProgramStateRef State,
+ const CXXNewExpr *NE,
+ const StackFrame *SF);
+
/// Removes the dead type informations from \p State.
ProgramStateRef removeDeadTypes(ProgramStateRef State, SymbolReaper &SR);
diff --git a/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp
index 067e9f9aae4853..325679862eccd5 100644
--- a/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/DestroyedAsWrongTypeChecker.cpp
@@ -20,6 +20,7 @@
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h"
#include "llvm/Support/FormatVariadic.h"
#include <optional>
@@ -60,10 +61,10 @@ struct WrongDestruction {
};
} // namespace
-// Storage reused by placement new -> type of the new object.
-REGISTER_MAP_WITH_PROGRAMSTATE(PlacedObjectTypes, const MemRegion *, QualType)
// Memory from a non-placement new, which holds an original object.
REGISTER_SET_WITH_PROGRAMSTATE(ObjectsAllocatedByNew, const MemRegion *)
+// Storage of an original object reused by placement new.
+REGISTER_SET_WITH_PROGRAMSTATE(ReusedStorages, const MemRegion *)
// Found inside std; reported on return to user code.
REGISTER_MAP_WITH_PROGRAMSTATE(PendingDestructions, const MemRegion *,
WrongDestruction)
@@ -88,20 +89,14 @@ class DestroyedAsWrongTypeChecker
};
} // namespace
-// An array is keyed by its first element, the object its destructor gets.
-static const MemRegion *getStorageRegion(SVal V, CheckerContext &C) {
- const MemRegion *R = V.getAsRegion();
- if (!R)
- return nullptr;
- R = R->StripCasts();
- ASTContext &Ctx = C.getASTContext();
- while (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
- const ArrayType *AT = Ctx.getAsArrayType(TR->getValueType());
- if (!AT)
- break;
- R = C.getStoreManager().GetElementZeroRegion(TR, AT->getElementType());
- }
- return R;
+// The type of the object known to occupy the storage, if it is exact.
+static std::optional<QualType> getPlacedType(const DynamicTypeInfo &DTI) {
+ if (!DTI.isValid() || DTI.canBeASubClass())
+ return std::nullopt;
+ QualType T = DTI.getType();
+ if (T->isPointerType() || T->isReferenceType())
+ T = T->getPointeeType();
+ return T.getUnqualifiedType();
}
// Storage obtained as raw memory has no original object to be replaced.
@@ -111,8 +106,10 @@ static bool holdsOriginalObject(ProgramStateRef State, const MemRegion *R) {
const auto *TR = dyn_cast<TypedValueRegion>(R);
if (!TR)
return false;
+ ASTContext &Ctx = State->getStateManager().getContext();
// Placement new into a union starts the lifetime of one of its members.
- const CXXRecordDecl *RD = TR->getValueType()->getAsCXXRecordDecl();
+ const CXXRecordDecl *RD =
+ Ctx.getBaseElementType(TR->getValueType())->getAsCXXRecordDecl();
return RD && !RD->isUnion() && RD->hasNonTrivialDestructor();
}
@@ -121,41 +118,16 @@ static bool isSameRecord(QualType T, const CXXRecordDecl *RD) {
return TD && TD->getCanonicalDecl() == RD->getCanonicalDecl();
}
-static QualType getStorageType(const MemRegion *R) {
+static const CXXRecordDecl *getStorageRecord(const MemRegion *R,
+ ASTContext &Ctx) {
+ QualType T;
if (const auto *TR = dyn_cast<TypedValueRegion>(R))
- return TR->getValueType();
- if (const auto *SR = dyn_cast<SymbolicRegion>(R))
- return SR->getPointeeStaticType();
- return {};
-}
-
-// A field and a byte offset from its parent are different regions, but we want
-// to recognize that they refer to the same location.
-static bool isSameLocation(const MemRegion *A, const MemRegion *B) {
- if (A == B)
- return true;
- RegionOffset OA = A->getAsOffset();
- RegionOffset OB = B->getAsOffset();
- return OA.isValid() && !OA.hasSymbolicOffset() && OA == OB;
-}
-
-static ProgramStateRef forgetPlacedTypes(ProgramStateRef State,
- const MemRegion *R) {
- for (const MemRegion *Key :
- llvm::make_first_range(State->get<PlacedObjectTypes>()))
- if (Key->isSubRegionOf(R) || isSameLocation(Key, R))
- State = State->remove<PlacedObjectTypes>(Key);
- return State;
-}
-
-static SmallVector<const MemRegion *, 1>
-getPlacementStorages(const CXXNewExpr *NE, CheckerContext &C) {
- SmallVector<const MemRegion *, 1> Storages;
- for (const Expr *Arg : NE->placement_arguments())
- if (Arg->getType()->isPointerType())
- if (const MemRegion *R = getStorageRegion(C.getSVal(Arg), C))
- Storages.push_back(R);
- return Storages;
+ T = TR->getValueType();
+ else if (const auto *SR = dyn_cast<SymbolicRegion>(R))
+ T = SR->getPointeeStaticType();
+ if (T.isNull())
+ return nullptr;
+ return Ctx.getBaseElementType(T)->getAsCXXRecordDecl();
}
static bool isInStdFrame(CheckerContext &C) {
@@ -178,42 +150,15 @@ void DestroyedAsWrongTypeChecker::reportBug(const MemRegion *R,
void DestroyedAsWrongTypeChecker::checkPostStmt(const CXXNewExpr *NE,
CheckerContext &C) const {
- const FunctionDecl *OperatorNew = NE->getOperatorNew();
- if (!OperatorNew)
- return;
-
- const MemRegion *Result = getStorageRegion(C.getSVal(NE), C);
- if (!Result)
- return;
-
ProgramStateRef State = C.getState();
- SmallVector<const MemRegion *, 1> Storages = getPlacementStorages(NE, C);
- if (OperatorNew->isReservedGlobalPlacementOperator() && Storages.empty())
- return;
- // The result may be typed as the new object, so use the storage argument.
- const MemRegion *R = nullptr;
- for (const MemRegion *Storage : Storages)
- if (OperatorNew->isReservedGlobalPlacementOperator() ||
- isSameLocation(Storage, Result))
- R = Storage;
+ const MemRegion *R = getPlacementNewStorage(State, NE, C.getStackFrame());
if (!R) {
- // An operator new that is not inlined may have placed the object there.
- for (const MemRegion *Storage : Storages)
- State = forgetPlacedTypes(State, Storage);
- C.addTransition(State->add<ObjectsAllocatedByNew>(Result));
- return;
- }
-
- if (NE->isArray()) {
- const auto *ER = dyn_cast<ElementRegion>(R);
- C.addTransition(forgetPlacedTypes(State, ER ? ER->getSuperRegion() : R));
+ if (const MemRegion *Result = C.getSVal(NE).getAsRegion())
+ C.addTransition(State->add<ObjectsAllocatedByNew>(Result->StripCasts()));
return;
}
- State = forgetPlacedTypes(State, R);
- if (!holdsOriginalObject(State, R)) {
- C.addTransition(State);
+ if (NE->isArray() || !holdsOriginalObject(State, R))
return;
- }
QualType Placed = NE->getAllocatedType().getUnqualifiedType();
std::string Note = "Object of type '" +
@@ -225,7 +170,7 @@ void DestroyedAsWrongTypeChecker::checkPostStmt(const CXXNewExpr *NE,
return "";
return Note;
});
- C.addTransition(State->set<PlacedObjectTypes>(R, Placed), Tag);
+ C.addTransition(State->add<ReusedStorages>(R), Tag);
}
static bool isDerivedFrom(QualType Placed, const CXXRecordDecl *Base) {
@@ -249,18 +194,37 @@ void DestroyedAsWrongTypeChecker::reportOrDefer(const MemRegion *R,
reportBug(R, W, C);
}
-static const MemRegion *getDestroyedRegion(const CallEvent &Call,
- CheckerContext &C) {
+static const MemRegion *getDestroyedRegion(const CallEvent &Call) {
const auto *Instance = dyn_cast<CXXInstanceCall>(&Call);
- return Instance ? getStorageRegion(Instance->getCXXThisVal(), C) : nullptr;
+ if (!Instance)
+ return nullptr;
+ const MemRegion *R = Instance->getCXXThisVal().getAsRegion();
+ if (!R)
+ return nullptr;
+ return R->StripCasts();
+}
+
+// The array of which R is an element, or R itself if it is an array.
+static const MemRegion *getEnclosingArray(const MemRegion *R, ASTContext &Ctx) {
+ if (const auto *ER = dyn_cast<ElementRegion>(R))
+ return ER->getSuperRegion();
+ const auto *TR = dyn_cast<TypedValueRegion>(R);
+ if (!TR || !Ctx.getAsArrayType(TR->getValueType()))
+ return nullptr;
+ return R;
}
static std::optional<WrongDestruction>
findWrongDestruction(const CallEvent &Call, const CXXDestructorDecl *Dtor,
const MemRegion *R, ProgramStateRef State) {
- const QualType *Placed = State->get<PlacedObjectTypes>(R);
+ const DynamicTypeInfo *DTI = getRawDynamicTypeInfo(State, R);
+ if (!DTI)
+ return std::nullopt;
+ std::optional<QualType> Placed = getPlacedType(*DTI);
const CXXRecordDecl *DtorClass = Dtor->getParent();
- if (!Placed || isSameRecord(*Placed, DtorClass))
+ // An object placed at the address of a union may be its member.
+ if (!Placed || DtorClass->isUnion() || isSameRecord(*Placed, DtorClass) ||
+ !State->contains<ReusedStorages>(R))
return std::nullopt;
const auto *Implicit = dyn_cast<CXXDestructorCall>(&Call);
@@ -287,18 +251,31 @@ findWrongDestruction(const CallEvent &Call, const CXXDestructorDecl *Dtor,
return WrongDestruction{*Placed, DtorClass, DE};
}
+// Members of a union are not destroyed with it.
+static bool isInUnion(const MemRegion *R, const MemRegion *Scope) {
+ while (R != Scope) {
+ const auto *SR = dyn_cast<SubRegion>(R);
+ if (!SR)
+ return false;
+ R = SR->getSuperRegion();
+ const auto *TR = dyn_cast<TypedValueRegion>(R);
+ if (TR && TR->getValueType()->isUnionType())
+ return true;
+ }
+ return false;
+}
+
// Finds a wrong destruction of storage within Scope other than R itself.
static std::optional<std::pair<const MemRegion *, WrongDestruction>>
findHiddenWrongDestruction(const MemRegion *R, const MemRegion *Scope,
- ProgramStateRef State) {
- for (const auto &[Key, Placed] : State->get<PlacedObjectTypes>()) {
- QualType StorageType = getStorageType(Key);
- if (StorageType.isNull())
- continue;
- const CXXRecordDecl *RD = StorageType->getAsCXXRecordDecl();
- if (RD && Key != R && Key->isSubRegionOf(Scope) &&
- !isSameRecord(Placed, RD))
- return std::make_pair(Key, WrongDestruction{Placed, RD, nullptr});
+ ProgramStateRef State, ASTContext &Ctx) {
+ for (const auto &[Key, DTI] : getDynamicTypeInfoWithin(State, Scope)) {
+ std::optional<QualType> Placed = getPlacedType(DTI);
+ const CXXRecordDecl *RD = getStorageRecord(Key, Ctx);
+ if (Placed && RD && !RD->isUnion() && Key != R &&
+ !isSameRecord(*Placed, RD) && State->contains<ReusedStorages>(Key) &&
+ !isInUnion(Key, Scope))
+ return std::make_pair(Key, WrongDestruction{*Placed, RD, nullptr});
}
return std::nullopt;
}
@@ -313,7 +290,7 @@ void DestroyedAsWrongTypeChecker::checkPreCall(const CallEvent &Call,
if (Implicit && Implicit->isBaseDestructor())
return;
- const MemRegion *R = getDestroyedRegion(Call, C);
+ const MemRegion *R = getDestroyedRegion(Call);
if (!R)
return;
ProgramStateRef State = C.getState();
@@ -325,12 +302,16 @@ void DestroyedAsWrongTypeChecker::checkPreCall(const CallEvent &Call,
// The analyzer may destroy an array with a single call on its last element,
// and does not show the destruction of members by a destructor without a
// body, so check these here.
- const MemRegion *Scope = R;
- if (const auto *ER = dyn_cast<ElementRegion>(R); ER && Implicit)
- Scope = ER->getSuperRegion();
- else if (Call.getRuntimeDefinition().getDecl())
- return;
- if (auto Hidden = findHiddenWrongDestruction(R, Scope, State))
+ const MemRegion *Scope = nullptr;
+ if (Implicit)
+ Scope = getEnclosingArray(R, C.getASTContext());
+ if (!Scope) {
+ if (Call.getRuntimeDefinition().getDecl())
+ return;
+ Scope = R;
+ }
+ if (auto Hidden =
+ findHiddenWrongDestruction(R, Scope, State, C.getASTContext()))
reportOrDefer(Hidden->first, Hidden->second, C);
}
@@ -346,13 +327,12 @@ void DestroyedAsWrongTypeChecker::checkPostCall(const CallEvent &Call,
void DestroyedAsWrongTypeChecker::checkDeadSymbols(SymbolReaper &SR,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
- for (const MemRegion *R :
- llvm::make_first_range(State->get<PlacedObjectTypes>()))
- if (!SR.isLiveRegion(R))
- State = State->remove<PlacedObjectTypes>(R);
for (const MemRegion *R : State->get<ObjectsAllocatedByNew>())
if (!SR.isLiveRegion(R))
State = State->remove<ObjectsAllocatedByNew>(R);
+ for (const MemRegion *R : State->get<ReusedStorages>())
+ if (!SR.isLiveRegion(R))
+ State = State->remove<ReusedStorages>(R);
C.addTransition(State);
}
diff --git a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
index 6eb57698102124..daf38f9da4b6f2 100644
--- a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
@@ -278,6 +278,12 @@ void DynamicTypePropagation::checkPreCall(const CallEvent &Call,
return;
}
+ if (const auto *Ctor = dyn_cast<CXXInheritedConstructorCall>(&Call)) {
+ if (const MemRegion *Target = Ctor->getCXXThisVal().getAsRegion())
+ recordFixedType(Target, Ctor->getDecl(), C);
+ return;
+ }
+
if (const CXXDestructorCall *Dtor = dyn_cast<CXXDestructorCall>(&Call)) {
// C++11 [class.cdtor]p4 (see above)
if (!Dtor->isBaseDestructor())
@@ -386,6 +392,26 @@ void DynamicTypePropagation::checkPostCall(const CallEvent &Call,
return;
}
}
+
+ if (const auto *Ctor = dyn_cast<CXXInheritedConstructorCall>(&Call)) {
+ const MemRegion *Target = Ctor->getCXXThisVal().getAsRegion();
+ const auto *Outer =
+ dyn_cast_if_present<CXXConstructorDecl>(C.getStackFrame()->getDecl());
+ if (Target && Outer)
+ recordFixedType(Target, Outer, C);
+ return;
+ }
+
+ if (const CXXDestructorCall *Dtor = dyn_cast<CXXDestructorCall>(&Call)) {
+ // After a base destructor, use the subclass's type again.
+ if (!Dtor->isBaseDestructor())
+ return;
+ const MemRegion *Target = Dtor->getCXXThisVal().getAsRegion();
+ const auto *Outer =
+ dyn_cast_if_present<CXXDestructorDecl>(C.getStackFrame()->getDecl());
+ if (Target && Outer)
+ recordFixedType(Target, Outer, C);
+ }
}
/// TODO: Handle explicit casts.
@@ -411,15 +437,26 @@ ExplodedNode *DynamicTypePropagation::dynamicTypePropagationOnCasts(
void DynamicTypePropagation::checkPostStmt(const CXXNewExpr *NewE,
CheckerContext &C) const {
- if (NewE->isArray())
- return;
+ ProgramStateRef State = C.getState();
+ const MemRegion *MR = getPlacementNewStorage(State, NewE, C.getStackFrame());
+ if (MR) {
+ State = removeDynamicTypeInfoWithin(State, MR);
+ } else {
+ // An operator new that is not inlined may have placed the object there.
+ for (const Expr *Arg : NewE->placement_arguments())
+ if (Arg->getType()->isVoidPointerType())
+ if (const MemRegion *Storage = C.getSVal(Arg).getAsRegion())
+ State = removeDynamicTypeInfoWithin(State, Storage);
+ MR = C.getSVal(NewE).getAsRegion();
+ }
// We only track dynamic type info for regions.
- const MemRegion *MR = C.getSVal(NewE).getAsRegion();
- if (!MR)
+ if (NewE->isArray() || !MR) {
+ C.addTransition(State);
return;
+ }
- C.addTransition(setDynamicTypeInfo(C.getState(), MR, NewE->getType(),
+ C.addTransition(setDynamicTypeInfo(State, MR, NewE->getType(),
/*CanBeSubClassed=*/false));
}
diff --git a/clang/lib/StaticAnalyzer/Core/DynamicType.cpp b/clang/lib/StaticAnalyzer/Core/DynamicType.cpp
index fb6dfd92646066..d20ea3c005f019 100644
--- a/clang/lib/StaticAnalyzer/Core/DynamicType.cpp
+++ b/clang/lib/StaticAnalyzer/Core/DynamicType.cpp
@@ -13,6 +13,7 @@
//===----------------------------------------------------------------------===//
#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h"
+#include "clang/AST/ExprCXX.h"
#include "clang/Basic/JsonSupport.h"
#include "clang/Basic/LLVM.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
@@ -154,6 +155,61 @@ ProgramStateRef setClassObjectDynamicTypeInfo(ProgramStateRef State,
DynamicTypeInfo(NewTy, CanBeSubClassed));
}
+// A field and a byte offset from its parent are different regions, but we want
+// to recognize that they refer to the same location.
+static bool isSameLocation(const MemRegion *A, const MemRegion *B) {
+ if (A == B)
+ return true;
+ RegionOffset OA = A->getAsOffset();
+ RegionOffset OB = B->getAsOffset();
+ return OA.isValid() && !OA.hasSymbolicOffset() && OA == OB;
+}
+
+ProgramStateRef removeDynamicTypeInfoWithin(ProgramStateRef State,
+ const MemRegion *MR) {
+ MR = MR->StripCasts();
+ auto IsWithin = [MR](const MemRegion *Key) {
+ return Key->isSubRegionOf(MR) || isSameLocation(Key, MR);
+ };
+ for (const MemRegion *Key :
+ llvm::make_first_range(State->get<DynamicTypeMap>()))
+ if (IsWithin(Key))
+ State = State->remove<DynamicTypeMap>(Key);
+ for (const MemRegion *Key :
+ llvm::make_first_range(State->get<DynamicCastMap>()))
+ if (IsWithin(Key))
+ State = State->remove<DynamicCastMap>(Key);
+ return State;
+}
+
+SmallVector<std::pair<const MemRegion *, DynamicTypeInfo>, 4>
+getDynamicTypeInfoWithin(ProgramStateRef State, const MemRegion *MR) {
+ SmallVector<std::pair<const MemRegion *, DynamicTypeInfo>, 4> Result;
+ for (const auto &[Key, DTI] : State->get<DynamicTypeMap>())
+ if (Key == MR || Key->isSubRegionOf(MR))
+ Result.emplace_back(Key, DTI);
+ return Result;
+}
+
+const MemRegion *getPlacementNewStorage(ProgramStateRef State,
+ const CXXNewExpr *NE,
+ const StackFrame *SF) {
+ const FunctionDecl *OperatorNew = NE->getOperatorNew();
+ const MemRegion *Result = State->getSVal(NE, SF).getAsRegion();
+ if (!OperatorNew || !Result)
+ return nullptr;
+ // The result may be typed as the new object, so use the storage argument.
+ for (const Expr *Arg : NE->placement_arguments()) {
+ if (!Arg->getType()->isPointerType())
+ continue;
+ const MemRegion *Storage = State->getSVal(Arg, SF).getAsRegion();
+ if (Storage && (OperatorNew->isReservedGlobalPlacementOperator() ||
+ isSameLocation(Storage, Result)))
+ return Storage->StripCasts();
+ }
+ return nullptr;
+}
+
static bool isLive(SymbolReaper &SR, const MemRegion *MR) {
return SR.isLiveRegion(MR);
}
diff --git a/clang/test/Analysis/destroyed-as-wrong-type.cpp b/clang/test/Analysis/destroyed-as-wrong-type.cpp
index 9f8e4454058d15..bd2d519ff57789 100644
--- a/clang/test/Analysis/destroyed-as-wrong-type.cpp
+++ b/clang/test/Analysis/destroyed-as-wrong-type.cpp
@@ -46,6 +46,11 @@ void delete_through_base_without_virtual_dtor() {
// expected-note at -2 {{Deleting an object of type 'Derived' through a pointer to 'Base'}}
}
+void new_derived_deleted_through_base_without_virtual_dtor() {
+ Base *p = new Derived;
+ delete p; // no-warning
+}
+
struct Holder {
// expected-warning at -1 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
// expected-note at -2 {{Destructor of 'B' is called on storage that holds an object of type 'A'}}
@@ -178,6 +183,27 @@ void raw_local_buffer() {
P->~B();
} // no-warning
+void raw_local_buffer_destroyed_as_other_type() {
+ alignas(B) unsigned char Buf[sizeof(B)];
+ new (Buf) A;
+ reinterpret_cast<B *>(Buf)->~B();
+} // no-warning
+
+struct CtorBase {
+ CtorBase() {}
+};
+struct WithCtor : CtorBase {
+ WithCtor(int) {}
+ ~WithCtor();
+};
+struct InheritsCtor : WithCtor {
+ using WithCtor::WithCtor;
+};
+
+void inherited_constructor() {
+ InheritsCtor I(0);
+} // no-warning
+
union OneOf {
B First;
A Second;
diff --git a/clang/test/Analysis/new-dynamic-types.cpp b/clang/test/Analysis/new-dynamic-types.cpp
index e0a460e3928e3e..224ab14eb26ade 100644
--- a/clang/test/Analysis/new-dynamic-types.cpp
+++ b/clang/test/Analysis/new-dynamic-types.cpp
@@ -1,10 +1,12 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core -std=c++11 -verify %s
-
-// expected-no-diagnostics
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -std=c++11 -verify %s
typedef __typeof(sizeof(int)) size_t;
void *operator new(size_t size, void *ptr);
+void *operator new[](size_t size, void *ptr);
+void *operator new(size_t, void *, int);
+
+void clang_analyzer_eval(bool);
struct B {
virtual void foo();
@@ -26,3 +28,71 @@ void test_non_ub() {
new (c) D;
((B *)c)->foo(); // no-crash
}
+
+struct V {
+ virtual int id() { return 1; }
+ ~V() {}
+};
+struct W : V {
+ int id() override { return 2; }
+ ~W() {}
+};
+
+void array_element() {
+ V A[2];
+ V *P = &A[1];
+ new (&A[1]) W;
+ clang_analyzer_eval(P->id() == 2); // expected-warning{{TRUE}}
+}
+
+struct TwoMembers {
+ V First;
+ V Second;
+};
+
+void restore_through_byte_offset() {
+ TwoMembers S;
+ new (&S.Second) W;
+ new (reinterpret_cast<char *>(&S) + sizeof(V)) V;
+ clang_analyzer_eval(S.Second.id() == 1); // expected-warning{{TRUE}}
+}
+
+void restore_through_opaque_operator_new() {
+ V v;
+ new (&v) W;
+ new (&v, 1) V;
+ clang_analyzer_eval(v.id() == 1); // expected-warning{{TRUE}}
+}
+
+void restore_through_array_placement_new() {
+ V v;
+ new (&v) W;
+ new (&v) V[1];
+ clang_analyzer_eval(v.id() == 1); // expected-warning{{TRUE}}
+}
+
+void after_base_destructor() {
+ W w;
+ w.~W();
+ V *P = &w;
+ clang_analyzer_eval(P->id() == 2); // expected-warning{{TRUE}}
+ new (&w) W;
+}
+
+struct E {
+ E() {}
+};
+struct WithBase : E {
+ WithBase(int) {}
+ virtual int id() { return 1; }
+};
+struct Inheriting : WithBase {
+ using WithBase::WithBase;
+ int id() override { return 2; }
+};
+
+void after_inherited_constructor() {
+ Inheriting I(0);
+ WithBase *P = &I;
+ clang_analyzer_eval(P->id() == 2); // expected-warning{{TRUE}}
+}
More information about the cfe-commits
mailing list