From e9afe761550fe876a08f2a9da3fa16e25ecdd3c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 23:14:01 +0000 Subject: [PATCH] feat(tidy): add fairmq-bugprone-use-after-send - Report uses of a MessagePtr after a Send() whose result is discarded. After the send the message is empty with zeromq, and still points to the sent buffer with shmem, so the same code acts differently per transport. - Walk the CFG from the send with ExprSequence, like bugprone-use-after-move. A loop back to the send counts as a use. - Assignment, reset(), Rebuild(), a new declaration in a loop and passing by non-const reference (e.g. to Receive()) give a new message. Co-Authored-By: Claude Opus 5.5 --- docs/src/content/docs/tools/fairmq-tidy.mdx | 15 ++ fairmq/tidy/CMakeLists.txt | 2 + fairmq/tidy/Module.cxx | 2 + fairmq/tidy/UseAfterSendCheck.cxx | 176 +++++++++++++++++++ fairmq/tidy/UseAfterSendCheck.h | 41 +++++ test/tidy/fairmq-bugprone-use-after-send.cxx | 73 ++++++++ 6 files changed, 309 insertions(+) create mode 100644 fairmq/tidy/UseAfterSendCheck.cxx create mode 100644 fairmq/tidy/UseAfterSendCheck.h create mode 100644 test/tidy/fairmq-bugprone-use-after-send.cxx diff --git a/docs/src/content/docs/tools/fairmq-tidy.mdx b/docs/src/content/docs/tools/fairmq-tidy.mdx index 14e418d5..ecf6e522 100644 --- a/docs/src/content/docs/tools/fairmq-tidy.mdx +++ b/docs/src/content/docs/tools/fairmq-tidy.mdx @@ -34,6 +34,7 @@ The `fairmq-*` checks are a clang-tidy module ([Module.cxx](/source/fairmq/tidy/ | Check | Finds | Fix | | --- | --- | --- | | `fairmq-bugprone-unchecked-transfer-result` | Calls of `Receive()` whose result is not used. With the option `CheckSend`, also calls of `Send()`. | No fix | +| `fairmq-bugprone-use-after-send` | Uses of a `MessagePtr` after a `Send()` whose result is not used | No fix | | `fairmq-modernize-channels-access` | Uses of the deprecated member `fair::mq::Device::fChannels` | `fChannels.at(name).at(index)` becomes `GetChannel(name, index)`. Other uses become `GetChannels()`. | | `fairmq-modernize-deprecated-functions` | Calls of deprecated functions: `Device::GetStateName()`, `Device::GetTransitionName()`, `Socket::GetConstant()`, `Socket::Close()` | The free function, for example `fair::mq::GetStateName()`. No fix for `Close()`. | | `fairmq-modernize-deprecated-headers` | `#include` lines of the deprecated headers, for example `` | The new header, for example `` | @@ -152,6 +153,20 @@ CheckOptions: fairmq-bugprone-unchecked-transfer-result.CheckSend: true ``` +### fairmq-bugprone-use-after-send + +After a successful `Send()`, the message is not yours anymore. With the zeromq transport, the message is empty. With the shmem transport, the message still points to the buffer that the receiver reads, so a write is a data race. The same code acts differently for each transport. + +```cpp +auto msg(NewMessage(16)); +Send(msg, "data"); +std::memset(msg->GetData(), 0, 16); // reported +``` + +The check follows the control flow of the function, like the upstream check `bugprone-use-after-move`. A loop that comes back to the `Send()` with the same message is also a use. These statements give the variable a new message, and the check stops at them: an assignment, `reset()`, `Rebuild()`, a declaration in the loop, and a call that takes the message by non-const reference, for example `Receive(msg, ...)`. + +The check looks only at a `Send()` whose result the code does not use. If the code checks the result, the send can have failed, and a use of the message can be correct. + ## Build fairmq-tidy Set the CMake option `BUILD_TIDY_TOOL` (default `OFF`) when you configure FairMQ: diff --git a/fairmq/tidy/CMakeLists.txt b/fairmq/tidy/CMakeLists.txt index 35b80208..329e6c62 100644 --- a/fairmq/tidy/CMakeLists.txt +++ b/fairmq/tidy/CMakeLists.txt @@ -51,6 +51,8 @@ add_library(fairmq-tidy-module OBJECT Transfer.h UncheckedTransferResultCheck.cxx UncheckedTransferResultCheck.h + UseAfterSendCheck.cxx + UseAfterSendCheck.h ) target_compile_features(fairmq-tidy-module PUBLIC cxx_std_17) target_include_directories(fairmq-tidy-module diff --git a/fairmq/tidy/Module.cxx b/fairmq/tidy/Module.cxx index 68069dec..4cdc9c32 100644 --- a/fairmq/tidy/Module.cxx +++ b/fairmq/tidy/Module.cxx @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -28,6 +29,7 @@ class Module : public clang::tidy::ClangTidyModule void addCheckFactories(clang::tidy::ClangTidyCheckFactories& factories) override { factories.registerCheck("fairmq-bugprone-unchecked-transfer-result"); + factories.registerCheck("fairmq-bugprone-use-after-send"); factories.registerCheck("fairmq-modernize-channels-access"); factories.registerCheck("fairmq-modernize-deprecated-functions"); factories.registerCheck("fairmq-modernize-deprecated-headers"); diff --git a/fairmq/tidy/UseAfterSendCheck.cxx b/fairmq/tidy/UseAfterSendCheck.cxx new file mode 100644 index 00000000..866aba4a --- /dev/null +++ b/fairmq/tidy/UseAfterSendCheck.cxx @@ -0,0 +1,176 @@ +/******************************************************************************** + * Copyright (C) 2026 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH * + * * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * + * copied verbatim in the file "LICENSE" * + ********************************************************************************/ + + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace fair::mq::tidy { + +using namespace clang; +using namespace clang::ast_matchers; +using clang::tidy::utils::ExprSequence; +using clang::tidy::utils::StmtToBlockMap; + +namespace { + +/// True if `type` is `std::unique_ptr`, i.e. `MessagePtr`. +bool isMessagePtr(QualType type) +{ + auto const* spec = dyn_cast_or_null( + type.getNonReferenceType()->getAsCXXRecordDecl()); + if (!spec || spec->getQualifiedNameAsString() != "std::unique_ptr" + || spec->getTemplateArgs().size() < 1) { + return false; + } + auto const* pointee = spec->getTemplateArgs()[0].getAsType()->getAsCXXRecordDecl(); + return pointee && pointee->getQualifiedNameAsString() == "fair::mq::Message"; +} + +struct Accesses +{ + std::vector uses; + std::vector reinits; +}; + +/// Collects the uses of `var` in `body` and the statements that give `var` a +/// new message. +Accesses collect(VarDecl const& var, Stmt const& body, ASTContext& ctx) +{ + auto const ref = declRefExpr(to(varDecl(equalsNode(&var)))).bind("ref"); + auto const reinit = stmt(anyOf( + // msg = NewMessage(); msg = std::move(other); + cxxOperatorCallExpr(hasOverloadedOperatorName("="), hasArgument(0, ref)), + // msg.reset(); msg.swap(other); + cxxMemberCallExpr(on(ref), callee(cxxMethodDecl(hasAnyName("reset", "swap")))), + // msg->Rebuild(...); + cxxMemberCallExpr(on(cxxOperatorCallExpr(hasOverloadedOperatorName("->"), hasArgument(0, ref))), + callee(cxxMethodDecl(hasName("Rebuild")))), + // Receive(msg, ...); fill(msg); + callExpr(forEachArgumentWithParam( + ignoringParenImpCasts(ref), + parmVarDecl(hasType(lValueReferenceType(pointee(unless(isConstQualified())))))), + unless(callee(functionDecl(hasAnyName("Send", "::std::move", "::std::forward"))))), + // a new variable in each iteration of a loop + declStmt(hasSingleDecl(equalsNode(&var))))); + + Accesses result; + llvm::SmallPtrSet reinitRefs; + for (auto const& match : ast_matchers::match(findAll(reinit.bind("reinit")), body, ctx)) { + result.reinits.push_back(match.getNodeAs("reinit")); + if (auto const* r = match.getNodeAs("ref")) { + reinitRefs.insert(r); + } + } + for (auto const& match : ast_matchers::match(findAll(ref), body, ctx)) { + auto const* r = match.getNodeAs("ref"); + if (!reinitRefs.count(r)) { + result.uses.push_back(r); + } + } + return result; +} + +} // namespace + +void UseAfterSendCheck::registerMatchers(MatchFinder* finder) +{ + finder->addMatcher( + cxxMemberCallExpr( + transferCall("Send"), + hasArgument(0, ignoringParenImpCasts(declRefExpr(to(varDecl(hasLocalStorage()).bind("var"))).bind("arg"))), + forCallable(functionDecl().bind("function")), + unless(isInTemplateInstantiation())) + .bind("send"), + this); +} + +void UseAfterSendCheck::check(MatchFinder::MatchResult const& result) +{ + auto& ctx = *result.Context; + auto const* send = result.Nodes.getNodeAs("send"); + auto const* arg = result.Nodes.getNodeAs("arg"); + auto const* var = result.Nodes.getNodeAs("var"); + auto const* body = result.Nodes.getNodeAs("function")->getBody(); + if (!body || !isMessagePtr(var->getType()) || !isDiscarded(*send, ctx)) { + return; + } + + CFG::BuildOptions options; + options.AddImplicitDtors = true; + options.AddTemporaryDtors = true; + options.setAllAlwaysAdd(); + std::unique_ptr const cfg = CFG::buildCFG(nullptr, const_cast(body), &ctx, options); + if (!cfg) { + return; + } + ExprSequence const sequence(cfg.get(), body, &ctx); + StmtToBlockMap const blocks(cfg.get(), &ctx); + auto const* start = blocks.blockContainingStmt(send); + if (!start) { + return; + } + auto const accesses = collect(*var, *body, ctx); + auto const& sm = *result.SourceManager; + + // Walk the CFG from the send. In the block of the send look only after + // the send, unless a loop leads back to it. + llvm::SmallPtrSet visited; + std::vector> work{{start, true}}; + while (!work.empty()) { + auto const [block, afterSend] = work.back(); + work.pop_back(); + + std::vector reinits; + for (auto const* r : accesses.reinits) { + if (blocks.blockContainingStmt(r) == block && (!afterSend || sequence.potentiallyAfter(r, send))) { + reinits.push_back(r); + } + } + DeclRefExpr const* use = nullptr; + for (auto const* u : accesses.uses) { + if (blocks.blockContainingStmt(u) != block || (afterSend && (u == arg || !sequence.potentiallyAfter(u, send)))) { + continue; + } + if (std::any_of(reinits.begin(), reinits.end(), [&](auto const* r) { return sequence.inSequence(r, u); })) { + continue; + } + if (!use || sm.isBeforeInTranslationUnit(u->getBeginLoc(), use->getBeginLoc())) { + use = u; + } + } + if (use) { + diag(use->getBeginLoc(), "'%0' is used after it was sent; a sent message is empty (zeromq) " + "or shared with the receiver (shmem)") + << var->getName(); + diag(send->getExprLoc(), "sent here", DiagnosticIDs::Note); + return; + } + if (!reinits.empty()) { + continue; + } + for (auto const& succ : block->succs()) { + if (succ && visited.insert(succ).second) { + work.emplace_back(succ, false); + } + } + } +} + +} // namespace fair::mq::tidy diff --git a/fairmq/tidy/UseAfterSendCheck.h b/fairmq/tidy/UseAfterSendCheck.h new file mode 100644 index 00000000..e13b3936 --- /dev/null +++ b/fairmq/tidy/UseAfterSendCheck.h @@ -0,0 +1,41 @@ +/******************************************************************************** + * Copyright (C) 2026 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH * + * * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * + * copied verbatim in the file "LICENSE" * + ********************************************************************************/ + + +#ifndef FAIR_MQ_TIDY_USEAFTERSENDCHECK_H +#define FAIR_MQ_TIDY_USEAFTERSENDCHECK_H + +#include + +namespace fair::mq::tidy { + +/// Finds uses of a `fair::mq::MessagePtr` after it was sent. After a +/// successful `Send()` the message is empty with the zeromq transport, and it +/// still points to the sent buffer with the shmem transport, i.e. a write +/// races with the receiver. The same code acts differently per transport. +/// +/// The check looks only at sends whose result is discarded. A send whose +/// result is checked can fail, and the code can then use the message again. +/// Assigning a new message, `reset()`, `Rebuild()` and passing the message +/// by non-const reference (e.g. to `Receive()`) start over. +class UseAfterSendCheck : public clang::tidy::ClangTidyCheck +{ + public: + using ClangTidyCheck::ClangTidyCheck; + + bool isLanguageVersionSupported(clang::LangOptions const& opts) const override + { + return opts.CPlusPlus17; + } + void registerMatchers(clang::ast_matchers::MatchFinder* finder) override; + void check(clang::ast_matchers::MatchFinder::MatchResult const& result) override; +}; + +} // namespace fair::mq::tidy + +#endif /* FAIR_MQ_TIDY_USEAFTERSENDCHECK_H */ diff --git a/test/tidy/fairmq-bugprone-use-after-send.cxx b/test/tidy/fairmq-bugprone-use-after-send.cxx new file mode 100644 index 00000000..4717236f --- /dev/null +++ b/test/tidy/fairmq-bugprone-use-after-send.cxx @@ -0,0 +1,73 @@ +#include + +#include + +struct Sampler : fair::mq::Device +{ + bool ConditionalRun() override + { + auto msg(NewMessage(16)); + Send(msg, "data"); + // CHECK-MESSAGES: :[[@LINE+1]]:21: warning: 'msg' is used after it was sent; a sent message is empty (zeromq) or shared with the receiver (shmem) [fairmq-bugprone-use-after-send] + std::memset(msg->GetData(), 0, 16); + return true; + } + + void Run() override + { + fair::mq::MessagePtr msg(NewMessage(16)); + while (!NewStatePending()) { + // CHECK-MESSAGES: :[[@LINE+1]]:18: warning: 'msg' is used after it was sent; a sent message is empty (zeromq) or shared with the receiver (shmem) [fairmq-bugprone-use-after-send] + Send(msg, "data"); + } + } + + void Branch(bool flag) + { + auto msg(NewMessage(16)); + GetChannel("data").Send(msg); + if (flag) { + // CHECK-MESSAGES: :[[@LINE+1]]:25: warning: 'msg' is used after it was sent; a sent message is empty (zeromq) or shared with the receiver (shmem) [fairmq-bugprone-use-after-send] + auto size = msg->GetSize(); + static_cast(size); + } + } + + // Not reported below. + void NewEachIteration() + { + while (!NewStatePending()) { + auto msg(NewMessage(16)); + Send(msg, "data"); + } + } + + void Reinit() + { + auto msg(NewMessage(16)); + Send(msg, "data"); + msg = NewMessage(8); + Send(msg, "data"); + msg->Rebuild(4); + Send(msg, "data"); + Receive(msg, "data"); + static_cast(msg->GetSize()); + Send(msg, "data"); + msg.reset(); + } + + void Checked() + { + auto msg(NewMessage(16)); + if (Send(msg, "data") < 0) { + static_cast(msg->GetSize()); + } + } + + void Parts() + { + fair::mq::Parts parts; + Send(parts, "data"); + static_cast(parts.Size()); + } +};