-
Notifications
You must be signed in to change notification settings - Fork 14.3k
Add bugprone-sprintf-argument-overlap #114244
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ccotter
wants to merge
23
commits into
llvm:main
Choose a base branch
from
ccotter:snprintf
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
fd914cc
Add bugprone-sprintf-overlap
ccotter 004719c
Apply suggestions from code review
ccotter d69c69a
Review feedback
ccotter 1984c94
Apply suggestions from code review
ccotter 75103a2
Remove custom matcher
ccotter ab472f0
Merge remote-tracking branch 'upstream/main' into snprintf
ccotter 84ded5f
Review feedback
ccotter cefd652
Apply suggestions from code review
ccotter e5012cd
Merge branch 'snprintf' of https://github.com/ccotter/llvm-project in…
ccotter 680b94e
format
ccotter bb6d7f7
Add example of incorrect behavior
ccotter 32f9d3f
Support more expressions with areStatementsIdentical
ccotter 357350e
Use argument number instead of argument text
ccotter 292752b
Rename tool
ccotter 3e1abf8
tidy up
ccotter c8f5764
Fix rename operation
ccotter a699e1d
Fix sort
ccotter b62b615
Fix arg index
ccotter 74c3a7b
format
ccotter 27ca8d4
fix docs
ccotter 21af986
Remove unused matcher
ccotter 0126bb6
Move logic into matchers
ccotter bbbd133
Fix sort
ccotter File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
106 changes: 106 additions & 0 deletions
106
clang-tools-extra/clang-tidy/bugprone/SprintfArgumentOverlapCheck.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
//===--- SprintfArgumentOverlapCheck.cpp - clang-tidy --------------------===// | ||
// | ||
// 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 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
#include "SprintfArgumentOverlapCheck.h" | ||
#include "../utils/ASTUtils.h" | ||
#include "clang/ASTMatchers/ASTMatchFinder.h" | ||
#include "clang/Lex/Lexer.h" | ||
|
||
using namespace clang::ast_matchers; | ||
|
||
namespace clang::tidy::bugprone { | ||
|
||
// Similar to forEachArgumentWithParam. forEachArgumentWithParam does not work | ||
// with variadic functions like sprintf, since there is no `decl()` to match | ||
// against in the parameter list `...`. | ||
AST_MATCHER_P(CallExpr, forEachArgument, ast_matchers::internal::Matcher<Expr>, | ||
ArgMatcher) { | ||
using namespace clang::ast_matchers::internal; | ||
BoundNodesTreeBuilder Result; | ||
int ParamIndex = 0; | ||
bool Matched = false; | ||
for (unsigned ArgIndex = 0; ArgIndex < Node.getNumArgs(); ++ArgIndex) { | ||
BoundNodesTreeBuilder ArgMatches(*Builder); | ||
if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder, | ||
&ArgMatches)) { | ||
BoundNodesTreeBuilder ParamMatches(ArgMatches); | ||
Result.addMatch(ArgMatches); | ||
Matched = true; | ||
} | ||
++ParamIndex; | ||
} | ||
*Builder = std::move(Result); | ||
return Matched; | ||
} | ||
|
||
AST_MATCHER_P(Stmt, identicalTo, std::string, ID) { | ||
return Builder->removeBindings( | ||
[this, &Node, | ||
&Finder](const ast_matchers::internal::BoundNodesMap &Nodes) { | ||
const DynTypedNode &BN = Nodes.getNode(ID); | ||
if (const auto *BoundStmt = BN.get<Stmt>()) | ||
return !utils::areStatementsIdentical(&Node, BoundStmt, | ||
Finder->getASTContext()); | ||
return true; | ||
}); | ||
} | ||
|
||
AST_MATCHER(Expr, hasSideEffects) { | ||
return Node.HasSideEffects(Finder->getASTContext()); | ||
} | ||
|
||
SprintfArgumentOverlapCheck::SprintfArgumentOverlapCheck( | ||
StringRef Name, ClangTidyContext *Context) | ||
: ClangTidyCheck(Name, Context), | ||
SprintfRegex(Options.get("SprintfFunction", "(::std)?::sn?printf")) {} | ||
|
||
void SprintfArgumentOverlapCheck::registerMatchers(MatchFinder *Finder) { | ||
Finder->addMatcher( | ||
callExpr( | ||
callee(functionDecl(matchesName(SprintfRegex)).bind("decl")), | ||
hasArgument(0, expr(unless(hasSideEffects())).bind("firstArgExpr")), | ||
forEachArgument(expr(unless(equalsBoundNode("firstArgExpr")), | ||
identicalTo("firstArgExpr")) | ||
.bind("otherArgExpr"))) | ||
.bind("call"), | ||
this); | ||
} | ||
|
||
void SprintfArgumentOverlapCheck::check( | ||
const MatchFinder::MatchResult &Result) { | ||
const auto *FirstArg = Result.Nodes.getNodeAs<Expr>("firstArgExpr"); | ||
const auto *OtherArg = Result.Nodes.getNodeAs<Expr>("otherArgExpr"); | ||
const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call"); | ||
const auto *FnDecl = Result.Nodes.getNodeAs<FunctionDecl>("decl"); | ||
|
||
if (!FirstArg || !OtherArg || !Call || !FnDecl) | ||
return; | ||
|
||
std::optional<unsigned> ArgIndex; | ||
for (unsigned I = 0; I != Call->getNumArgs(); ++I) { | ||
if (Call->getArg(I)->IgnoreUnlessSpelledInSource() == OtherArg) { | ||
ArgIndex = I; | ||
break; | ||
} | ||
} | ||
if (!ArgIndex) | ||
return; | ||
|
||
diag(OtherArg->getBeginLoc(), | ||
"the %ordinal0 argument in %1 overlaps the 1st argument, " | ||
"which is undefined behavior") | ||
<< (*ArgIndex + 1) << FnDecl << FirstArg->getSourceRange() | ||
<< OtherArg->getSourceRange(); | ||
} | ||
|
||
void SprintfArgumentOverlapCheck::storeOptions( | ||
ClangTidyOptions::OptionMap &Opts) { | ||
Options.store(Opts, "SprintfRegex", SprintfRegex); | ||
} | ||
|
||
} // namespace clang::tidy::bugprone |
40 changes: 40 additions & 0 deletions
40
clang-tools-extra/clang-tidy/bugprone/SprintfArgumentOverlapCheck.h
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
//===--- SprintfArgumentOverlapCheck.h - clang-tidy -------------*- 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 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_SPRINTFARGUMENTOVERLAPCHECK_H | ||
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_SPRINTFARGUMENTOVERLAPCHECK_H | ||
|
||
#include "../ClangTidyCheck.h" | ||
|
||
namespace clang::tidy::bugprone { | ||
|
||
/// Warns if any arguments to the ``sprintf`` family of functions overlap with | ||
/// the destination buffer (the first argument). | ||
/// | ||
/// For the user-facing documentation see: | ||
/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/sprintf-argument-overlap.html | ||
class SprintfArgumentOverlapCheck : public ClangTidyCheck { | ||
public: | ||
SprintfArgumentOverlapCheck(StringRef Name, ClangTidyContext *Context); | ||
void registerMatchers(ast_matchers::MatchFinder *Finder) override; | ||
void check(const ast_matchers::MatchFinder::MatchResult &Result) override; | ||
void storeOptions(ClangTidyOptions::OptionMap &Opts) override; | ||
std::optional<TraversalKind> getCheckTraversalKind() const override { | ||
return TK_IgnoreUnlessSpelledInSource; | ||
} | ||
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { | ||
return LangOpts.CPlusPlus || LangOpts.C99; | ||
} | ||
|
||
private: | ||
const std::string SprintfRegex; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Note: llvm::StringRef should be fine here |
||
}; | ||
|
||
} // namespace clang::tidy::bugprone | ||
|
||
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_SPRINTFARGUMENTOVERLAPCHECK_H |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
36 changes: 36 additions & 0 deletions
36
clang-tools-extra/docs/clang-tidy/checks/bugprone/sprintf-argument-overlap.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
.. title:: clang-tidy - bugprone-sprintf-argument-overlap | ||
|
||
bugprone-sprintf-argument-overlap | ||
================================= | ||
|
||
Warns if any arguments to the ``sprintf`` family of functions overlap with the | ||
destination buffer (the first argument). | ||
|
||
.. code-block:: c++ | ||
|
||
char buf[20] = {"hi"}; | ||
sprintf(buf, "%s%d", buf, 0); | ||
|
||
If copying takes place between objects that overlap, the behavior is undefined. | ||
This is stated in the `C23/N3220 standard | ||
<https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3096.pdf>`_ | ||
(sections 7.23.6.5 and 7.23.6.6), as well as the `POSIX.1-2024 standard | ||
<https://pubs.opengroup.org/onlinepubs/9799919799/>`_. | ||
|
||
In practice, passing the output buffer to an input argument can result in | ||
incorrect output. For example, Linux with glibc may produce the following. | ||
|
||
.. code-block:: c++ | ||
|
||
char buf[10]; | ||
sprintf(buf, "%s", "12"); | ||
sprintf(buf, "%s%s", "34", buf); | ||
printf("%s\n", buf); // prints 3434 | ||
|
||
Options | ||
------- | ||
|
||
.. option:: SprintfRegex | ||
|
||
A regex specifying the ``sprintf`` family of functions to match on. By default, | ||
this is `(::std)?::sn?printf`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
86 changes: 86 additions & 0 deletions
86
clang-tools-extra/test/clang-tidy/checkers/bugprone/sprintf-argument-overlap.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
// RUN: %check_clang_tidy %s bugprone-sprintf-argument-overlap %t | ||
|
||
using size_t = decltype(sizeof(int)); | ||
|
||
extern "C" int sprintf(char *s, const char *format, ...); | ||
extern "C" int snprintf(char *s, size_t n, const char *format, ...); | ||
|
||
namespace std { | ||
int snprintf(char *s, size_t n, const char *format, ...); | ||
} | ||
|
||
struct st_t { | ||
char buf[10]; | ||
char buf2[10]; | ||
}; | ||
|
||
struct st2_t { | ||
st_t inner; | ||
}; | ||
|
||
struct st3_t { | ||
st2_t inner; | ||
}; | ||
|
||
void first_arg_overlaps() { | ||
char buf[10]; | ||
sprintf(buf, "%s", buf); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:22: warning: the 3rd argument in 'sprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
snprintf(buf, sizeof(buf), "%s", buf); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:36: warning: the 4th argument in 'snprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
std::snprintf(buf, sizeof(buf), "%s", buf); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:41: warning: the 4th argument in 'snprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
sprintf(buf+1, "%s", (buf+1)); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:25: warning: the 3rd argument in 'sprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
sprintf(buf+1, "%s", buf+2); | ||
sprintf(buf+1, "%s", buf[1]); | ||
|
||
char* c = &buf[0]; | ||
sprintf(c, "%s", c); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: the 3rd argument in 'sprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
snprintf(c, sizeof(buf), "%s", c); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:34: warning: the 4th argument in 'snprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
|
||
snprintf(c, sizeof(buf), "%s%s", c, c); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:36: warning: the 4th argument in 'snprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
// CHECK-MESSAGES: :[[@LINE-2]]:39: warning: the 5th argument in 'snprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
|
||
char buf2[10]; | ||
sprintf(buf, "%s", buf2); | ||
sprintf(buf, "%s", buf2, buf); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:28: warning: the 4th argument in 'sprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
|
||
st_t st1, st2; | ||
sprintf(st1.buf, "%s", st1.buf); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:26: warning: the 3rd argument in 'sprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
sprintf(st1.buf, "%s", st1.buf2); | ||
sprintf(st1.buf, "%s", st2.buf); | ||
|
||
st3_t st3; | ||
sprintf(st3.inner.inner.buf, "%s", st3.inner.inner.buf); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:38: warning: the 3rd argument in 'sprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
sprintf((st3.inner.inner.buf), "%s", st3.inner.inner.buf); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:40: warning: the 3rd argument in 'sprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
|
||
st_t* stp; | ||
sprintf(stp->buf, "%s", stp->buf); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:27: warning: the 3rd argument in 'sprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
sprintf((stp->buf), "%s", stp->buf); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:29: warning: the 3rd argument in 'sprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
stp = &st1; | ||
sprintf(stp->buf, "%s", st1.buf); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would be nice to add comments for false negatives. |
||
|
||
char bufs[10][10]; | ||
sprintf(bufs[1], "%s", bufs[1]); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:26: warning: the 3rd argument in 'sprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
sprintf(bufs[0], "%s", bufs[1]); | ||
|
||
char bufss[10][10][10]; | ||
sprintf(bufss[0][1], "%s", bufss[0][1]); | ||
// CHECK-MESSAGES: :[[@LINE-1]]:30: warning: the 3rd argument in 'sprintf' overlaps the 1st argument, which is undefined behavior [bugprone-sprintf-argument-overlap] | ||
|
||
sprintf(bufss[0][0], "%s", bufss[0][1]); | ||
|
||
int i = 0; | ||
sprintf(bufss[0][++i], "%s", bufss[0][++i]); | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
there is isStatementIdenticalToBoundNode in utils/Matchers.h