10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Frontend/CompilerInstance.h"
13#include "clang/Lex/Lexer.h"
14#include "clang/Lex/PPCallbacks.h"
15#include "clang/Lex/Preprocessor.h"
36enum class LengthHandleKind { Increase, Decrease };
39static Preprocessor *
PP;
48 if (
const auto *DestVAT =
50 return DestVAT->getSizeExpr();
52 if (
const auto *DestVD = Result.Nodes.getNodeAs<VarDecl>(
DestVarDeclName))
53 if (
const TypeLoc DestTL = DestVD->getTypeSourceInfo()->getTypeLoc())
54 if (
const auto DestCTL = DestTL.getAs<ConstantArrayTypeLoc>())
55 return DestCTL.getSizeExpr();
63 const MatchFinder::MatchResult &Result) {
67 E = E->IgnoreImpCasts();
69 if (
const auto *LengthDRE = dyn_cast<DeclRefExpr>(E))
70 if (
const auto *LengthVD = dyn_cast<VarDecl>(LengthDRE->getDecl()))
71 if (!isa<ParmVarDecl>(LengthVD))
72 if (
const Expr *LengthInit = LengthVD->getInit();
73 LengthInit && !LengthInit->isValueDependent()) {
74 Expr::EvalResult Length;
75 if (LengthInit->EvaluateAsInt(Length, *Result.Context))
76 return Length.Val.getInt().getZExtValue();
79 if (
const auto *LengthIL = dyn_cast<IntegerLiteral>(E))
80 return LengthIL->getValue().getZExtValue();
82 if (
const auto *StrDRE = dyn_cast<DeclRefExpr>(E))
83 if (
const auto *StrVD = dyn_cast<VarDecl>(StrDRE->getDecl()))
84 if (
const Expr *StrInit = StrVD->getInit())
85 if (
const auto *StrSL =
86 dyn_cast<StringLiteral>(StrInit->IgnoreImpCasts()))
87 return StrSL->getLength();
89 if (
const auto *SrcSL = dyn_cast<StringLiteral>(E))
90 return SrcSL->getLength();
99 return getLength(DestCapacityExpr, Result);
105static const CallExpr *
getStrlenExpr(
const MatchFinder::MatchResult &Result) {
106 if (
const auto *StrlenExpr =
108 if (
const Decl *D = StrlenExpr->getCalleeDecl())
109 if (
const FunctionDecl *FD = D->getAsFunction())
110 if (
const IdentifierInfo *II = FD->getIdentifier())
111 if (II->isStr(
"strlen") || II->isStr(
"wcslen"))
123 if (
const int Length =
127 if (
const int Length =
133 if (
const Expr *Arg = StrlenCE->getArg(0)->IgnoreImpCasts())
134 if (
const int ArgLength =
getLength(Arg, Result))
142 const MatchFinder::MatchResult &Result) {
146 return Lexer::getSourceText(
147 CharSourceRange::getTokenRange(E->getSourceRange()),
148 *Result.SourceManager, Result.Context->getLangOpts(),
nullptr);
153 const MatchFinder::MatchResult &Result) {
154 return Lexer::getLocForEndOfToken(E->getEndLoc(), 0, *Result.SourceManager,
155 Result.Context->getLangOpts());
165static bool isInjectUL(
const MatchFinder::MatchResult &Result) {
177 const StringRef DestCapacityExprStr =
179 const StringRef LengthExprStr =
182 return !DestCapacityExprStr.empty() && !LengthExprStr.empty() &&
183 DestCapacityExprStr.contains(LengthExprStr);
188 if (
const auto *DestDRE = Result.Nodes.getNodeAs<DeclRefExpr>(
DestExprName))
189 if (
const auto *SrcDRE = Result.Nodes.getNodeAs<DeclRefExpr>(
SrcExprName))
190 return DestDRE->getDecl()->getCanonicalDecl() ==
191 SrcDRE->getDecl()->getCanonicalDecl();
198 const auto *DestExpr =
199 Result.Nodes.getNodeAs<CXXMemberCallExpr>(
DestExprName);
200 const auto *SrcExpr = Result.Nodes.getNodeAs<CXXMemberCallExpr>(
SrcExprName);
201 const auto *LengthExpr =
204 StringRef DestStr =
"", SrcStr =
"", LengthStr =
"";
206 if (
const CXXMethodDecl *DestMD = DestExpr->getMethodDecl())
207 DestStr = DestMD->getName();
210 if (
const CXXMethodDecl *SrcMD = SrcExpr->getMethodDecl())
211 SrcStr = SrcMD->getName();
214 if (
const CXXMethodDecl *LengthMD = LengthExpr->getMethodDecl())
215 LengthStr = LengthMD->getName();
217 return (LengthStr ==
"length" || LengthStr ==
"size") &&
218 (SrcStr ==
"data" || DestStr ==
"data");
230 const int SrcLength =
233 if (GivenLength != 0 && SrcLength != 0 && GivenLength == SrcLength)
236 if (
const auto *LengthExpr = Result.Nodes.getNodeAs<Expr>(
LengthExprName))
237 if (isa<BinaryOperator>(LengthExpr->IgnoreParenImpCasts()))
242 if (
const auto *ArgDRE =
243 dyn_cast<DeclRefExpr>(StrlenCE->getArg(0)->IgnoreImpCasts()))
244 if (
const auto *SrcVD = Result.Nodes.getNodeAs<VarDecl>(
SrcVarDeclName))
245 return dyn_cast<VarDecl>(ArgDRE->getDecl()) == SrcVD;
265 const int DestCapacity =
getLength(DestCapacityExpr, Result);
268 if (GivenLength != 0 && DestCapacity != 0)
273 const StringRef DestCapacityExprStr =
exprToStr(DestCapacityExpr, Result);
274 if (DestCapacityExprStr.contains(
"+1") || DestCapacityExprStr.contains(
"+ 1"))
294 LengthHandleKind LengthHandle,
295 const MatchFinder::MatchResult &Result,
296 DiagnosticBuilder &Diag) {
297 LengthExpr = LengthExpr->IgnoreParenImpCasts();
300 const StringRef LengthExprStr =
exprToStr(LengthExpr, Result);
301 const bool IsMacroDefinition = llvm::any_of(
PP->macros(), [=](
const auto &M) {
302 return M.first->getName() == LengthExprStr;
306 if (!IsMacroDefinition) {
307 if (
const auto *LengthIL = dyn_cast<IntegerLiteral>(LengthExpr)) {
308 const uint64_t NewLength =
309 LengthIL->getValue().getZExtValue() +
310 (LengthHandle == LengthHandleKind::Increase ? 1 : -1);
312 const auto NewLengthFix = FixItHint::CreateReplacement(
313 LengthIL->getSourceRange(),
314 (Twine(NewLength) + (
isInjectUL(Result) ?
"UL" :
"")).str());
315 Diag << NewLengthFix;
321 const auto *BO = dyn_cast<BinaryOperator>(LengthExpr);
322 if (BO && BO->getOpcode() == BO_Add &&
323 LengthHandle == LengthHandleKind::Decrease) {
324 const Expr *LhsExpr = BO->getLHS()->IgnoreImpCasts();
325 const Expr *RhsExpr = BO->getRHS()->IgnoreImpCasts();
327 if (
const auto *LhsIL = dyn_cast<IntegerLiteral>(LhsExpr)) {
328 if (LhsIL->getValue().getZExtValue() == 1) {
329 Diag << FixItHint::CreateRemoval(
330 {LhsIL->getBeginLoc(),
331 RhsExpr->getBeginLoc().getLocWithOffset(-1)});
336 if (
const auto *RhsIL = dyn_cast<IntegerLiteral>(RhsExpr)) {
337 if (RhsIL->getValue().getZExtValue() == 1) {
338 Diag << FixItHint::CreateRemoval(
339 {LhsExpr->getEndLoc().getLocWithOffset(1), RhsIL->getEndLoc()});
346 const bool NeedInnerParen = BO && BO->getOpcode() != BO_Add;
349 Diag << FixItHint::CreateInsertion(LengthExpr->getBeginLoc(),
"(");
351 SmallString<8> Injection;
354 Injection += LengthHandle == LengthHandleKind::Increase ?
" + 1" :
" - 1";
358 Diag << FixItHint::CreateInsertion(
exprLocEnd(LengthExpr, Result), Injection);
362 const MatchFinder::MatchResult &Result,
363 DiagnosticBuilder &Diag) {
364 const auto *LengthExpr = Result.Nodes.getNodeAs<Expr>(
LengthExprName);
369 const MatchFinder::MatchResult &Result,
370 DiagnosticBuilder &Diag) {
371 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
378 DiagnosticBuilder &Diag) {
379 const auto *Dest = Result.Nodes.getNodeAs<Expr>(
DestExprName);
383 const std::string TempTyStr = Dest->getType().getAsString();
384 const StringRef TyStr = TempTyStr;
385 if (TyStr.starts_with(
"char") || TyStr.starts_with(
"wchar_t"))
388 Diag << FixItHint::CreateInsertion(Dest->getBeginLoc(),
"(char *)");
395 DiagnosticBuilder &Diag) {
404static void removeArg(
int ArgPos,
const MatchFinder::MatchResult &Result,
405 DiagnosticBuilder &Diag) {
410 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
411 const Expr *ArgToRemove = FunctionExpr->getArg(ArgPos);
412 const Expr *LHSArg = FunctionExpr->getArg(ArgPos - 1);
413 const auto RemoveArgFix = FixItHint::CreateRemoval(
415 exprLocEnd(ArgToRemove, Result).getLocWithOffset(-1)));
416 Diag << RemoveArgFix;
420 const MatchFinder::MatchResult &Result,
421 DiagnosticBuilder &Diag) {
422 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
423 const int FuncNameLength =
424 FunctionExpr->getDirectCallee()->getIdentifier()->getLength();
425 const SourceRange FuncNameRange(
426 FunctionExpr->getBeginLoc(),
427 FunctionExpr->getBeginLoc().getLocWithOffset(FuncNameLength - 1));
429 const auto FuncNameFix =
430 FixItHint::CreateReplacement(FuncNameRange, NewFuncName);
435 const MatchFinder::MatchResult &Result,
436 DiagnosticBuilder &Diag) {
437 SmallString<10> NewFuncName;
438 NewFuncName = (Name[0] !=
'w') ?
"str" :
"wcs";
439 NewFuncName += IsCopy ?
"cpy" :
"ncpy";
440 NewFuncName += IsSafe ?
"_s" :
"";
445 const MatchFinder::MatchResult &Result,
446 DiagnosticBuilder &Diag) {
447 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
448 SmallString<64> NewSecondArg;
451 NewSecondArg = Twine(IsOverflows ? DestLength + 1 : DestLength).str();
455 (IsOverflows ? (!
isInjectUL(Result) ?
" + 1" :
" + 1UL") :
""))
459 NewSecondArg +=
", ";
460 const auto InsertNewArgFix = FixItHint::CreateInsertion(
461 FunctionExpr->getArg(1)->getBeginLoc(), NewSecondArg);
462 Diag << InsertNewArgFix;
466 const MatchFinder::MatchResult &Result,
467 DiagnosticBuilder &Diag) {
468 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
469 const int FuncLocStartColumn = Result.SourceManager->getPresumedColumnNumber(
470 FunctionExpr->getBeginLoc());
471 const SourceRange SpaceRange(
472 FunctionExpr->getBeginLoc().getLocWithOffset(-FuncLocStartColumn + 1),
473 FunctionExpr->getBeginLoc());
474 const StringRef SpaceBeforeStmtStr = Lexer::getSourceText(
475 CharSourceRange::getCharRange(SpaceRange), *Result.SourceManager,
476 Result.Context->getLangOpts(),
nullptr);
478 SmallString<128> NewAddNullTermExprStr;
479 NewAddNullTermExprStr =
480 (Twine(
'\n') + SpaceBeforeStmtStr +
483 "] = " + ((Name[0] !=
'w') ? R
"('\0';)" : R"(L'\0';)"))
486 const auto AddNullTerminatorExprFix = FixItHint::CreateInsertion(
487 exprLocEnd(FunctionExpr, Result).getLocWithOffset(1),
488 NewAddNullTermExprStr);
489 Diag << AddNullTerminatorExprFix;
499 WantToUseSafeFunctions(Options.get(
"WantToUseSafeFunctions", true)) {}
503 Options.store(Opts,
"WantToUseSafeFunctions", WantToUseSafeFunctions);
507 const SourceManager &SM, Preprocessor *Pp, Preprocessor *ModuleExpanderPP) {
512AST_MATCHER_P(Expr, hasDefinition, ast_matchers::internal::Matcher<Expr>,
514 const Expr *SimpleNode = &Node;
515 SimpleNode = SimpleNode->IgnoreParenImpCasts();
517 if (InnerMatcher.matches(*SimpleNode, Finder, Builder))
520 auto DREHasInit = ignoringImpCasts(
521 declRefExpr(to(varDecl(hasInitializer(ignoringImpCasts(InnerMatcher))))));
523 if (DREHasInit.matches(*SimpleNode, Finder, Builder))
526 const char *
const VarDeclName =
"variable-declaration";
527 auto DREHasDefinition = ignoringImpCasts(declRefExpr(
528 to(varDecl().bind(VarDeclName)),
529 hasAncestor(compoundStmt(hasDescendant(binaryOperator(
530 hasLHS(declRefExpr(to(varDecl(equalsBoundNode(VarDeclName))))),
531 hasRHS(ignoringImpCasts(InnerMatcher))))))));
533 if (DREHasDefinition.matches(*SimpleNode, Finder, Builder))
542 binaryOperator(hasOperatorName(
"+"),
543 hasEitherOperand(ignoringParenImpCasts(integerLiteral())));
546 binaryOperator(hasOperatorName(
"-"),
547 hasEitherOperand(ignoringParenImpCasts(integerLiteral())));
549 auto HasIncOp = anyOf(ignoringImpCasts(IncOp), hasDescendant(IncOp));
550 auto HasDecOp = anyOf(ignoringImpCasts(DecOp), hasDescendant(DecOp));
552 auto Container = ignoringImpCasts(cxxMemberCallExpr(hasDescendant(declRefExpr(
553 hasType(hasUnqualifiedDesugaredType(recordType(hasDeclaration(recordDecl(
554 hasAnyName(
"::std::vector",
"::std::list",
"::std::deque"))))))))));
556 auto StringTy = type(hasUnqualifiedDesugaredType(recordType(
557 hasDeclaration(cxxRecordDecl(hasName(
"::std::basic_string"))))));
560 anyOf(hasType(StringTy), hasType(qualType(pointsTo(StringTy))));
562 auto CharTyArray = hasType(qualType(hasCanonicalType(
565 auto CharTyPointer = hasType(
566 qualType(hasCanonicalType(pointerType(pointee(isAnyCharacter())))));
568 auto AnyOfCharTy = anyOf(CharTyArray, CharTyPointer);
576 callExpr(callee(functionDecl(hasAnyName(
"::strlen",
"::wcslen"))))
581 cxxMemberCallExpr(on(expr(AnyOfStringTy).bind(
"Foo")),
582 has(memberExpr(member(hasAnyName(
"size",
"length")))))
586 auto SizeOfCharExpr = unaryExprOrTypeTraitExpr(has(expr(AnyOfCharTy)));
589 ignoringImpCasts(anyOf(Strlen, SizeOrLength, hasDescendant(Strlen),
590 hasDescendant(SizeOrLength)));
594 ignoringImpCasts(declRefExpr(to(varDecl(hasInitializer(WrongLength)))));
596 auto AnyOfCallOrDREWithoutInc = anyOf(DREWithoutInc, WrongLength);
599 auto CallExprReturnWithoutInc = ignoringImpCasts(callExpr(callee(functionDecl(
600 hasBody(has(returnStmt(hasReturnValue(AnyOfCallOrDREWithoutInc))))))));
603 auto DREHasReturnWithoutInc = ignoringImpCasts(
604 declRefExpr(to(varDecl(hasInitializer(CallExprReturnWithoutInc)))));
606 auto AnyOfWrongLengthInit =
607 anyOf(WrongLength, AnyOfCallOrDREWithoutInc, CallExprReturnWithoutInc,
608 DREHasReturnWithoutInc);
616 auto SizeExpr = anyOf(SizeOfCharExpr, integerLiteral(equals(1)));
618 auto MallocLengthExpr = allOf(
620 hasAnyName(
"::alloca",
"::calloc",
"malloc",
"realloc"))),
624 auto DestMalloc = anyOf(callExpr(MallocLengthExpr),
625 hasDescendant(callExpr(MallocLengthExpr)));
628 auto DestCXXNewExpr = ignoringImpCasts(
631 auto AnyOfDestInit = anyOf(DestMalloc, DestCXXNewExpr);
634 auto DestArrayTyDecl = declRefExpr(
639 auto DestUnknownDecl =
644 auto AnyOfDestDecl = ignoringImpCasts(
645 anyOf(allOf(hasDefinition(anyOf(AnyOfDestInit, DestArrayTyDecl,
646 hasDescendant(DestArrayTyDecl))),
648 anyOf(DestUnknownDecl, hasDescendant(DestUnknownDecl))));
650 auto NullTerminatorExpr = binaryOperator(
651 hasLHS(anyOf(hasDescendant(declRefExpr(to(varDecl(
653 hasDescendant(declRefExpr(
655 hasRHS(ignoringImpCasts(
656 anyOf(characterLiteral(equals(0U)), integerLiteral(equals(0))))));
660 anyOf(hasAncestor(cxxMemberCallExpr().bind(
SrcExprName)),
664 ignoringImpCasts(anyOf(stringLiteral().bind(
SrcExprName),
666 SrcDecl, hasDescendant(SrcDecl)));
673 CallContext(StringRef Name, std::optional<unsigned> DestinationPos,
674 std::optional<unsigned> SourcePos,
unsigned LengthPos,
676 : Name(Name), DestinationPos(DestinationPos), SourcePos(SourcePos),
677 LengthPos(LengthPos), WithIncrease(WithIncrease) {}
680 std::optional<unsigned> DestinationPos;
681 std::optional<unsigned> SourcePos;
686 auto MatchDestination = [=](CallContext CC) {
687 return hasArgument(*CC.DestinationPos,
689 unless(hasAncestor(compoundStmt(
690 hasDescendant(NullTerminatorExpr)))),
694 auto MatchSource = [=](CallContext CC) {
695 return hasArgument(*CC.SourcePos, AnyOfSrcDecl);
698 auto MatchGivenLength = [=](CallContext CC) {
703 allOf(unless(hasDefinition(SizeOfCharExpr)),
704 allOf(CC.WithIncrease
705 ? ignoringImpCasts(hasDefinition(HasIncOp))
707 allOf(unless(hasDefinition(HasIncOp)),
708 hasDefinition(optionally(
709 binaryOperator().bind(
711 AnyOfWrongLengthInit))),
715 auto MatchCall = [=](CallContext CC) {
716 const std::string CharHandlerFuncName =
"::" + CC.Name.str();
719 const std::string WcharHandlerFuncName =
720 "::" + (CC.Name.starts_with(
"mem") ?
"w" + CC.Name.str()
721 :
"wcs" + CC.Name.substr(3).str());
723 return allOf(callee(functionDecl(
724 hasAnyName(CharHandlerFuncName, WcharHandlerFuncName))),
725 MatchGivenLength(CC));
728 auto Match = [=](CallContext CC) {
729 if (CC.DestinationPos && CC.SourcePos)
730 return allOf(MatchCall(CC), MatchDestination(CC), MatchSource(CC));
732 if (CC.DestinationPos && !CC.SourcePos)
733 return allOf(MatchCall(CC), MatchDestination(CC),
734 hasArgument(*CC.DestinationPos, anything()));
736 if (!CC.DestinationPos && CC.SourcePos)
737 return allOf(MatchCall(CC), MatchSource(CC),
738 hasArgument(*CC.SourcePos, anything()));
740 llvm_unreachable(
"Unhandled match");
744 auto Memcpy = Match({
"memcpy", 0, 1, 2,
false});
747 auto MemcpyS = Match({
"memcpy_s", 0, 2, 3,
false});
750 auto Memchr = Match({
"memchr", std::nullopt, 0, 2,
false});
753 auto Memmove = Match({
"memmove", 0, 1, 2,
false});
756 auto MemmoveS = Match({
"memmove_s", 0, 2, 3,
false});
759 auto StrncmpRHS = Match({
"strncmp", std::nullopt, 1, 2,
true});
760 auto StrncmpLHS = Match({
"strncmp", std::nullopt, 0, 2,
true});
763 auto Strxfrm = Match({
"strxfrm", 0, 1, 2,
false});
766 auto StrerrorS = Match({
"strerror_s", 0, std::nullopt, 1,
false});
768 auto AnyOfMatchers = anyOf(Memcpy, MemcpyS, Memmove, MemmoveS, StrncmpRHS,
769 StrncmpLHS, Strxfrm, StrerrorS);
776 unless(hasAncestor(castExpr(unless(implicitCastExpr())))))
780 castExpr(allOf(unless(implicitCastExpr()),
787 const MatchFinder::MatchResult &Result) {
788 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
789 if (FunctionExpr->getBeginLoc().isMacroID())
792 if (WantToUseSafeFunctions &&
PP->isMacroDefined(
"__STDC_LIB_EXT1__")) {
793 std::optional<bool> AreSafeFunctionsWanted;
794 for (
const auto &M :
PP->macros()) {
795 if (M.first->getName() !=
"__STDC_WANT_LIB_EXT1__")
797 const auto *MI =
PP->getMacroInfo(M.first);
801 const auto &T = MI->tokens().back();
802 if (T.isLiteral() && T.getLiteralData()) {
803 const StringRef ValueStr(T.getLiteralData(), T.getLength());
804 llvm::APInt IntValue;
805 ValueStr.getAsInteger(10, IntValue);
806 AreSafeFunctionsWanted = IntValue.getZExtValue();
811 if (AreSafeFunctionsWanted)
812 UseSafeFunctions = *AreSafeFunctionsWanted;
815 const StringRef Name = FunctionExpr->getDirectCallee()->getName();
816 if (Name.starts_with(
"mem") || Name.starts_with(
"wmem"))
817 memoryHandlerFunctionFix(Name, Result);
818 else if (Name ==
"strerror_s")
819 strerrorSFix(Result);
820 else if (Name.ends_with(
"ncmp"))
821 ncmpFix(Name, Result);
822 else if (Name.ends_with(
"xfrm"))
823 xfrmFix(Name, Result);
826void NotNullTerminatedResultCheck::memoryHandlerFunctionFix(
827 StringRef Name,
const MatchFinder::MatchResult &Result) {
831 if (Name.ends_with(
"chr")) {
832 memchrFix(Name, Result);
836 if ((Name.contains(
"cpy") || Name.contains(
"move")) &&
842 "the result from calling '%0' is not null-terminated")
845 if (Name.ends_with(
"cpy")) {
846 memcpyFix(Name, Result, Diag);
847 }
else if (Name.ends_with(
"cpy_s")) {
848 memcpySFix(Name, Result, Diag);
849 }
else if (Name.ends_with(
"move")) {
850 memmoveFix(Name, Result, Diag);
851 }
else if (Name.ends_with(
"move_s")) {
857void NotNullTerminatedResultCheck::memcpyFix(
858 StringRef Name,
const MatchFinder::MatchResult &Result,
859 DiagnosticBuilder &Diag) {
866 const bool IsSafe = UseSafeFunctions && IsOverflows &&
isKnownDest(Result) &&
869 const bool IsDestLengthNotRequired =
870 IsSafe && getLangOpts().CPlusPlus &&
875 if (IsSafe && !IsDestLengthNotRequired)
881 if (!IsCopy && !IsSafe)
885void NotNullTerminatedResultCheck::memcpySFix(
886 StringRef Name,
const MatchFinder::MatchResult &Result,
887 DiagnosticBuilder &Diag) {
891 const bool RemoveDestLength =
892 getLangOpts().CPlusPlus &&
895 const bool IsSafe = IsOverflows;
899 if (!IsSafe || (IsSafe && RemoveDestLength))
907 if (!IsCopy && !IsSafe)
911void NotNullTerminatedResultCheck::memchrFix(
912 StringRef Name,
const MatchFinder::MatchResult &Result) {
913 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
914 if (
const auto *GivenCL = dyn_cast<CharacterLiteral>(FunctionExpr->getArg(1)))
915 if (GivenCL->getValue() != 0)
918 auto Diag = diag(FunctionExpr->getArg(2)->IgnoreParenCasts()->getBeginLoc(),
919 "the length is too short to include the null terminator");
921 if (
const auto *CastExpr = Result.Nodes.getNodeAs<Expr>(
CastExprName)) {
922 const auto CastRemoveFix = FixItHint::CreateRemoval(
923 SourceRange(CastExpr->getBeginLoc(),
924 FunctionExpr->getBeginLoc().getLocWithOffset(-1)));
925 Diag << CastRemoveFix;
928 const StringRef NewFuncName = (Name[0] !=
'w') ?
"strchr" :
"wcschr";
933void NotNullTerminatedResultCheck::memmoveFix(
934 StringRef Name,
const MatchFinder::MatchResult &Result,
935 DiagnosticBuilder &Diag)
const {
939 renameFunc((Name[0] !=
'w') ?
"memmove_s" :
"wmemmove_s", Result, Diag);
946void NotNullTerminatedResultCheck::strerrorSFix(
947 const MatchFinder::MatchResult &Result) {
950 "the result from calling 'strerror_s' is not null-terminated and "
951 "missing the last character of the error message");
957void NotNullTerminatedResultCheck::ncmpFix(
958 StringRef Name,
const MatchFinder::MatchResult &Result) {
959 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
960 const Expr *FirstArgExpr = FunctionExpr->getArg(0)->IgnoreImpCasts();
961 const Expr *SecondArgExpr = FunctionExpr->getArg(1)->IgnoreImpCasts();
962 bool IsLengthTooLong =
false;
965 const Expr *LengthExprArg = StrlenExpr->getArg(0);
966 const StringRef FirstExprStr =
exprToStr(FirstArgExpr, Result).trim();
967 const StringRef SecondExprStr =
exprToStr(SecondArgExpr, Result).trim();
968 const StringRef LengthArgStr =
exprToStr(LengthExprArg, Result).trim();
970 LengthArgStr == FirstExprStr || LengthArgStr == SecondExprStr;
972 const int SrcLength =
975 if (SrcLength != 0 && GivenLength != 0)
976 IsLengthTooLong = GivenLength > SrcLength;
982 auto Diag = diag(FunctionExpr->getArg(2)->IgnoreParenCasts()->getBeginLoc(),
983 "comparison length is too long and might lead to a "
989void NotNullTerminatedResultCheck::xfrmFix(
990 StringRef Name,
const MatchFinder::MatchResult &Result) {
996 "the result from calling '%0' is not null-terminated")
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
NotNullTerminatedResultCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
static bool isStringDataAndLength(const MatchFinder::MatchResult &Result)
static bool isCorrectGivenLength(const MatchFinder::MatchResult &Result)
static const CallExpr * getStrlenExpr(const MatchFinder::MatchResult &Result)
static void renameFunc(StringRef NewFuncName, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag)
constexpr StringRef UnknownLengthName
static bool isKnownDest(const MatchFinder::MatchResult &Result)
static bool isDestAndSrcEquals(const MatchFinder::MatchResult &Result)
static bool isDestExprFix(const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag)
constexpr StringRef SrcVarDeclName
constexpr StringRef DestExprName
static SourceLocation exprLocEnd(const Expr *E, const MatchFinder::MatchResult &Result)
static int getGivenLength(const MatchFinder::MatchResult &Result)
constexpr StringRef DestMallocExprName
static bool isDestBasedOnGivenLength(const MatchFinder::MatchResult &Result)
static const Expr * getDestCapacityExpr(const MatchFinder::MatchResult &Result)
constexpr StringRef LengthExprName
static bool isGivenLengthEqualToSrcLength(const MatchFinder::MatchResult &Result)
constexpr StringRef DestArrayTyName
constexpr StringRef FunctionExprName
constexpr StringRef SrcExprName
static int getDestCapacity(const MatchFinder::MatchResult &Result)
static bool isDestCapacityOverflows(const MatchFinder::MatchResult &Result)
static bool isInjectUL(const MatchFinder::MatchResult &Result)
static bool isFixedGivenLengthAndUnknownSrc(const MatchFinder::MatchResult &Result)
static void lengthExprHandle(const Expr *LengthExpr, LengthHandleKind LengthHandle, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag)
static void lengthArgHandle(LengthHandleKind LengthHandle, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag)
static void lengthArgPosHandle(unsigned ArgPos, LengthHandleKind LengthHandle, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag)
static bool isDestCapacityFix(const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag)
static StringRef exprToStr(const Expr *E, const MatchFinder::MatchResult &Result)
static void insertNullTerminatorExpr(StringRef Name, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag)
static void removeArg(int ArgPos, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag)
static unsigned getLength(const Expr *E, const MatchFinder::MatchResult &Result)
constexpr StringRef CastExprName
static void insertDestCapacityArg(bool IsOverflows, StringRef Name, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag)
static void renameMemcpy(StringRef Name, bool IsCopy, bool IsSafe, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag)
constexpr StringRef WrongLengthExprName
constexpr StringRef DestVarDeclName
constexpr StringRef UnknownDestName
llvm::StringMap< ClangTidyValue > OptionMap