mirror of
https://github.com/FairRootGroup/FairMQ.git
synced 2026-11-25 21:21:37 +00:00
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 <noreply@anthropic.com>
This commit is contained in:
@@ -34,6 +34,7 @@ The `fairmq-*` checks are a clang-tidy module ([Module.cxx](/source/fairmq/tidy/
|
|||||||
| Check | Finds | Fix |
|
| 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-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-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-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 `<FairMQDevice.h>` | The new header, for example `<fairmq/Device.h>` |
|
| `fairmq-modernize-deprecated-headers` | `#include` lines of the deprecated headers, for example `<FairMQDevice.h>` | The new header, for example `<fairmq/Device.h>` |
|
||||||
@@ -152,6 +153,20 @@ CheckOptions:
|
|||||||
fairmq-bugprone-unchecked-transfer-result.CheckSend: true
|
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
|
## Build fairmq-tidy
|
||||||
|
|
||||||
Set the CMake option `BUILD_TIDY_TOOL` (default `OFF`) when you configure FairMQ:
|
Set the CMake option `BUILD_TIDY_TOOL` (default `OFF`) when you configure FairMQ:
|
||||||
|
|||||||
@@ -51,6 +51,8 @@ add_library(fairmq-tidy-module OBJECT
|
|||||||
Transfer.h
|
Transfer.h
|
||||||
UncheckedTransferResultCheck.cxx
|
UncheckedTransferResultCheck.cxx
|
||||||
UncheckedTransferResultCheck.h
|
UncheckedTransferResultCheck.h
|
||||||
|
UseAfterSendCheck.cxx
|
||||||
|
UseAfterSendCheck.h
|
||||||
)
|
)
|
||||||
target_compile_features(fairmq-tidy-module PUBLIC cxx_std_17)
|
target_compile_features(fairmq-tidy-module PUBLIC cxx_std_17)
|
||||||
target_include_directories(fairmq-tidy-module
|
target_include_directories(fairmq-tidy-module
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
#include <fairmq/tidy/ProgOptionsAccessorsCheck.h>
|
#include <fairmq/tidy/ProgOptionsAccessorsCheck.h>
|
||||||
#include <fairmq/tidy/RunDeviceCheck.h>
|
#include <fairmq/tidy/RunDeviceCheck.h>
|
||||||
#include <fairmq/tidy/UncheckedTransferResultCheck.h>
|
#include <fairmq/tidy/UncheckedTransferResultCheck.h>
|
||||||
|
#include <fairmq/tidy/UseAfterSendCheck.h>
|
||||||
|
|
||||||
#include <clang-tidy/ClangTidyModule.h>
|
#include <clang-tidy/ClangTidyModule.h>
|
||||||
#include <clang-tidy/ClangTidyModuleRegistry.h>
|
#include <clang-tidy/ClangTidyModuleRegistry.h>
|
||||||
@@ -28,6 +29,7 @@ class Module : public clang::tidy::ClangTidyModule
|
|||||||
void addCheckFactories(clang::tidy::ClangTidyCheckFactories& factories) override
|
void addCheckFactories(clang::tidy::ClangTidyCheckFactories& factories) override
|
||||||
{
|
{
|
||||||
factories.registerCheck<UncheckedTransferResultCheck>("fairmq-bugprone-unchecked-transfer-result");
|
factories.registerCheck<UncheckedTransferResultCheck>("fairmq-bugprone-unchecked-transfer-result");
|
||||||
|
factories.registerCheck<UseAfterSendCheck>("fairmq-bugprone-use-after-send");
|
||||||
factories.registerCheck<ChannelsAccessCheck>("fairmq-modernize-channels-access");
|
factories.registerCheck<ChannelsAccessCheck>("fairmq-modernize-channels-access");
|
||||||
factories.registerCheck<DeprecatedFunctionsCheck>("fairmq-modernize-deprecated-functions");
|
factories.registerCheck<DeprecatedFunctionsCheck>("fairmq-modernize-deprecated-functions");
|
||||||
factories.registerCheck<DeprecatedHeadersCheck>("fairmq-modernize-deprecated-headers");
|
factories.registerCheck<DeprecatedHeadersCheck>("fairmq-modernize-deprecated-headers");
|
||||||
|
|||||||
176
fairmq/tidy/UseAfterSendCheck.cxx
Normal file
176
fairmq/tidy/UseAfterSendCheck.cxx
Normal file
@@ -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 <fairmq/tidy/Transfer.h>
|
||||||
|
#include <fairmq/tidy/UseAfterSendCheck.h>
|
||||||
|
|
||||||
|
#include <clang-tidy/utils/ExprSequence.h>
|
||||||
|
#include <clang/AST/DeclTemplate.h>
|
||||||
|
#include <clang/ASTMatchers/ASTMatchFinder.h>
|
||||||
|
#include <clang/ASTMatchers/ASTMatchers.h>
|
||||||
|
#include <clang/Analysis/CFG.h>
|
||||||
|
#include <llvm/ADT/SmallPtrSet.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <memory>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
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<fair::mq::Message>`, i.e. `MessagePtr`.
|
||||||
|
bool isMessagePtr(QualType type)
|
||||||
|
{
|
||||||
|
auto const* spec = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
|
||||||
|
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<DeclRefExpr const*> uses;
|
||||||
|
std::vector<Stmt const*> 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<DeclRefExpr const*, 8> reinitRefs;
|
||||||
|
for (auto const& match : ast_matchers::match(findAll(reinit.bind("reinit")), body, ctx)) {
|
||||||
|
result.reinits.push_back(match.getNodeAs<Stmt>("reinit"));
|
||||||
|
if (auto const* r = match.getNodeAs<DeclRefExpr>("ref")) {
|
||||||
|
reinitRefs.insert(r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (auto const& match : ast_matchers::match(findAll(ref), body, ctx)) {
|
||||||
|
auto const* r = match.getNodeAs<DeclRefExpr>("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<CXXMemberCallExpr>("send");
|
||||||
|
auto const* arg = result.Nodes.getNodeAs<DeclRefExpr>("arg");
|
||||||
|
auto const* var = result.Nodes.getNodeAs<VarDecl>("var");
|
||||||
|
auto const* body = result.Nodes.getNodeAs<FunctionDecl>("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<CFG> const cfg = CFG::buildCFG(nullptr, const_cast<Stmt*>(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<CFGBlock const*, 16> visited;
|
||||||
|
std::vector<std::pair<CFGBlock const*, bool>> work{{start, true}};
|
||||||
|
while (!work.empty()) {
|
||||||
|
auto const [block, afterSend] = work.back();
|
||||||
|
work.pop_back();
|
||||||
|
|
||||||
|
std::vector<Stmt const*> 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
|
||||||
41
fairmq/tidy/UseAfterSendCheck.h
Normal file
41
fairmq/tidy/UseAfterSendCheck.h
Normal file
@@ -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 <clang-tidy/ClangTidyCheck.h>
|
||||||
|
|
||||||
|
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 */
|
||||||
73
test/tidy/fairmq-bugprone-use-after-send.cxx
Normal file
73
test/tidy/fairmq-bugprone-use-after-send.cxx
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
#include <fairmq/Device.h>
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
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<void>(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<void>(msg->GetSize());
|
||||||
|
Send(msg, "data");
|
||||||
|
msg.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Checked()
|
||||||
|
{
|
||||||
|
auto msg(NewMessage(16));
|
||||||
|
if (Send(msg, "data") < 0) {
|
||||||
|
static_cast<void>(msg->GetSize());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Parts()
|
||||||
|
{
|
||||||
|
fair::mq::Parts parts;
|
||||||
|
Send(parts, "data");
|
||||||
|
static_cast<void>(parts.Size());
|
||||||
|
}
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user