11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/ASTMatchers/ASTMatchers.h"
14 #include "clang/Lex/Lexer.h"
15 #include "clang/Tooling/FixIt.h"
17 using namespace clang::ast_matchers;
23 void SuspiciousMemsetUsageCheck::registerMatchers(MatchFinder *
Finder) {
28 callee(functionDecl(hasName(
"::memset"))),
29 hasArgument(1, characterLiteral(equals(static_cast<unsigned>(
'0')))
30 .bind(
"char-zero-fill")),
32 eachOf(hasArgument(0, anyOf(hasType(pointsTo(isAnyCharacter())),
33 hasType(arrayType(hasElementType(
34 isAnyCharacter()))))),
35 isInTemplateInstantiation()))),
40 Finder->addMatcher(callExpr(callee(functionDecl(hasName(
"::memset"))),
41 hasArgument(1, integerLiteral().bind(
"num-fill")),
42 unless(isInTemplateInstantiation())),
47 callExpr(callee(functionDecl(hasName(
"::memset"))),
48 unless(hasArgument(1, anyOf(characterLiteral(equals(
49 static_cast<unsigned>(
'0'))),
51 unless(isInTemplateInstantiation()))
56 void SuspiciousMemsetUsageCheck::check(
const MatchFinder::MatchResult &Result) {
57 if (
const auto *CharZeroFill =
58 Result.Nodes.getNodeAs<CharacterLiteral>(
"char-zero-fill")) {
62 SourceRange CharRange = CharZeroFill->getSourceRange();
64 diag(CharZeroFill->getLocStart(),
"memset fill value is char '0', "
65 "potentially mistaken for int 0");
68 if (CharRange.getBegin().isMacroID())
70 Diag << FixItHint::CreateReplacement(
71 CharSourceRange::getTokenRange(CharRange),
"0");
74 else if (
const auto *NumFill =
75 Result.Nodes.getNodeAs<IntegerLiteral>(
"num-fill")) {
79 llvm::APSInt NumValue;
80 const auto UCharMax = (1 << Result.Context->getCharWidth()) - 1;
81 if (!NumFill->EvaluateAsInt(NumValue, *Result.Context) ||
82 (NumValue >= 0 && NumValue <= UCharMax))
85 diag(NumFill->getLocStart(),
"memset fill value is out of unsigned "
86 "character range, gets truncated");
89 else if (
const auto *Call = Result.Nodes.getNodeAs<CallExpr>(
"call")) {
93 const Expr *FillChar = Call->getArg(1);
94 const Expr *ByteCount = Call->getArg(2);
97 llvm::APSInt Value1, Value2;
98 if (ByteCount->isValueDependent() ||
99 !ByteCount->EvaluateAsInt(Value2, *Result.Context) || Value2 != 0)
105 if (!FillChar->isValueDependent() &&
106 FillChar->EvaluateAsInt(Value1, *Result.Context) &&
107 (Value1 == 0 || Value1.isNegative()))
113 auto D = diag(Call->getLocStart(),
114 "memset of size zero, potentially swapped arguments");
115 StringRef RHSString = tooling::fixit::getText(*ByteCount, *Result.Context);
116 StringRef LHSString = tooling::fixit::getText(*FillChar, *Result.Context);
117 if (LHSString.empty() || RHSString.empty())
120 D << tooling::fixit::createReplacement(*FillChar, RHSString)
121 << tooling::fixit::createReplacement(*ByteCount, LHSString);
std::unique_ptr< ast_matchers::MatchFinder > Finder