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"
38static 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) {
68 E =
E->IgnoreImpCasts();
70 if (
const auto *LengthDRE = dyn_cast<DeclRefExpr>(
E))
71 if (
const auto *LengthVD = dyn_cast<VarDecl>(LengthDRE->getDecl()))
72 if (!isa<ParmVarDecl>(LengthVD))
73 if (
const Expr *LengthInit = LengthVD->getInit())
74 if (LengthInit->EvaluateAsInt(
Length, *Result.Context))
75 return Length.Val.getInt().getZExtValue();
77 if (
const auto *LengthIL = dyn_cast<IntegerLiteral>(
E))
78 return LengthIL->getValue().getZExtValue();
80 if (
const auto *StrDRE = dyn_cast<DeclRefExpr>(
E))
81 if (
const auto *StrVD = dyn_cast<VarDecl>(StrDRE->getDecl()))
82 if (
const Expr *StrInit = StrVD->getInit())
83 if (
const auto *StrSL =
84 dyn_cast<StringLiteral>(StrInit->IgnoreImpCasts()))
85 return StrSL->getLength();
87 if (
const auto *SrcSL = dyn_cast<StringLiteral>(
E))
88 return SrcSL->getLength();
97 return getLength(DestCapacityExpr, Result);
103static const CallExpr *
getStrlenExpr(
const MatchFinder::MatchResult &Result) {
104 if (
const auto *StrlenExpr =
106 if (
const Decl *D = StrlenExpr->getCalleeDecl())
107 if (
const FunctionDecl *FD = D->getAsFunction())
108 if (
const IdentifierInfo *II = FD->getIdentifier())
109 if (II->isStr(
"strlen") || II->isStr(
"wcslen"))
131 if (
const Expr *Arg = StrlenCE->getArg(0)->IgnoreImpCasts())
132 if (
int ArgLength =
getLength(Arg, Result))
140 const MatchFinder::MatchResult &Result) {
144 return Lexer::getSourceText(
145 CharSourceRange::getTokenRange(
E->getSourceRange()),
146 *Result.SourceManager, Result.Context->getLangOpts(),
nullptr);
151 const MatchFinder::MatchResult &Result) {
152 return Lexer::getLocForEndOfToken(
E->getEndLoc(), 0, *Result.SourceManager,
153 Result.Context->getLangOpts());
163static bool isInjectUL(
const MatchFinder::MatchResult &Result) {
175 StringRef DestCapacityExprStr =
177 StringRef LengthExprStr =
180 return !DestCapacityExprStr.empty() && !LengthExprStr.empty() &&
181 DestCapacityExprStr.contains(LengthExprStr);
186 if (
const auto *DestDRE = Result.Nodes.getNodeAs<DeclRefExpr>(
DestExprName))
187 if (
const auto *SrcDRE = Result.Nodes.getNodeAs<DeclRefExpr>(
SrcExprName))
188 return DestDRE->getDecl()->getCanonicalDecl() ==
189 SrcDRE->getDecl()->getCanonicalDecl();
196 const auto *DestExpr =
197 Result.Nodes.getNodeAs<CXXMemberCallExpr>(
DestExprName);
198 const auto *SrcExpr = Result.Nodes.getNodeAs<CXXMemberCallExpr>(
SrcExprName);
199 const auto *LengthExpr =
202 StringRef DestStr =
"", SrcStr =
"", LengthStr =
"";
204 if (
const CXXMethodDecl *DestMD = DestExpr->getMethodDecl())
205 DestStr = DestMD->getName();
208 if (
const CXXMethodDecl *SrcMD = SrcExpr->getMethodDecl())
209 SrcStr = SrcMD->getName();
212 if (
const CXXMethodDecl *LengthMD = LengthExpr->getMethodDecl())
213 LengthStr = LengthMD->getName();
215 return (LengthStr ==
"length" || LengthStr ==
"size") &&
216 (SrcStr ==
"data" || DestStr ==
"data");
230 if (GivenLength != 0 && SrcLength != 0 && GivenLength == SrcLength)
233 if (
const auto *LengthExpr = Result.Nodes.getNodeAs<Expr>(
LengthExprName))
234 if (isa<BinaryOperator>(LengthExpr->IgnoreParenImpCasts()))
239 if (
const auto *ArgDRE =
240 dyn_cast<DeclRefExpr>(StrlenCE->getArg(0)->IgnoreImpCasts()))
241 if (
const auto *SrcVD = Result.Nodes.getNodeAs<VarDecl>(
SrcVarDeclName))
242 return dyn_cast<VarDecl>(ArgDRE->getDecl()) == SrcVD;
262 int DestCapacity =
getLength(DestCapacityExpr, Result);
265 if (GivenLength != 0 && DestCapacity != 0)
270 StringRef DestCapacityExprStr =
exprToStr(DestCapacityExpr, Result);
271 if (DestCapacityExprStr.contains(
"+1") || DestCapacityExprStr.contains(
"+ 1"))
292 const MatchFinder::MatchResult &Result,
293 DiagnosticBuilder &Diag) {
294 LengthExpr = LengthExpr->IgnoreParenImpCasts();
297 bool IsMacroDefinition =
false;
298 StringRef LengthExprStr =
exprToStr(LengthExpr, Result);
299 Preprocessor::macro_iterator It =
PP->macro_begin();
300 while (It !=
PP->macro_end() && !IsMacroDefinition) {
301 if (It->first->getName() == LengthExprStr)
302 IsMacroDefinition =
true;
308 if (!IsMacroDefinition) {
309 if (
const auto *LengthIL = dyn_cast<IntegerLiteral>(LengthExpr)) {
310 size_t NewLength = LengthIL->getValue().getZExtValue() +
315 const auto NewLengthFix = FixItHint::CreateReplacement(
316 LengthIL->getSourceRange(),
317 (Twine(NewLength) + (
isInjectUL(Result) ?
"UL" :
"")).str());
318 Diag << NewLengthFix;
324 const auto *BO = dyn_cast<BinaryOperator>(LengthExpr);
325 if (BO && BO->getOpcode() == BO_Add &&
327 const Expr *LhsExpr = BO->getLHS()->IgnoreImpCasts();
328 const Expr *RhsExpr = BO->getRHS()->IgnoreImpCasts();
330 if (
const auto *LhsIL = dyn_cast<IntegerLiteral>(LhsExpr)) {
331 if (LhsIL->getValue().getZExtValue() == 1) {
332 Diag << FixItHint::CreateRemoval(
333 {LhsIL->getBeginLoc(),
334 RhsExpr->getBeginLoc().getLocWithOffset(-1)});
339 if (
const auto *RhsIL = dyn_cast<IntegerLiteral>(RhsExpr)) {
340 if (RhsIL->getValue().getZExtValue() == 1) {
341 Diag << FixItHint::CreateRemoval(
342 {LhsExpr->getEndLoc().getLocWithOffset(1), RhsIL->getEndLoc()});
349 bool NeedInnerParen = BO && BO->getOpcode() != BO_Add;
352 Diag << FixItHint::CreateInsertion(LengthExpr->getBeginLoc(),
"(");
354 SmallString<8> Injection;
361 Diag << FixItHint::CreateInsertion(
exprLocEnd(LengthExpr, Result), Injection);
365 const MatchFinder::MatchResult &Result,
366 DiagnosticBuilder &Diag) {
367 const auto *LengthExpr = Result.Nodes.getNodeAs<Expr>(
LengthExprName);
372 const MatchFinder::MatchResult &Result,
373 DiagnosticBuilder &Diag) {
374 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
381 DiagnosticBuilder &Diag) {
382 const auto *Dest = Result.Nodes.getNodeAs<Expr>(
DestExprName);
386 std::string TempTyStr = Dest->getType().getAsString();
387 StringRef TyStr = TempTyStr;
388 if (TyStr.starts_with(
"char") || TyStr.starts_with(
"wchar_t"))
391 Diag << FixItHint::CreateInsertion(Dest->getBeginLoc(),
"(char *)");
398 DiagnosticBuilder &Diag) {
407static void removeArg(
int ArgPos,
const MatchFinder::MatchResult &Result,
408 DiagnosticBuilder &Diag) {
413 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
414 const Expr *ArgToRemove = FunctionExpr->getArg(ArgPos);
415 const Expr *LHSArg = FunctionExpr->getArg(ArgPos - 1);
416 const auto RemoveArgFix = FixItHint::CreateRemoval(
418 exprLocEnd(ArgToRemove, Result).getLocWithOffset(-1)));
419 Diag << RemoveArgFix;
423 const MatchFinder::MatchResult &Result,
424 DiagnosticBuilder &Diag) {
425 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
427 FunctionExpr->getDirectCallee()->getIdentifier()->getLength();
428 SourceRange FuncNameRange(
429 FunctionExpr->getBeginLoc(),
430 FunctionExpr->getBeginLoc().getLocWithOffset(FuncNameLength - 1));
432 const auto FuncNameFix =
433 FixItHint::CreateReplacement(FuncNameRange, NewFuncName);
438 const MatchFinder::MatchResult &Result,
439 DiagnosticBuilder &Diag) {
440 SmallString<10> NewFuncName;
441 NewFuncName = (
Name[0] !=
'w') ?
"str" :
"wcs";
442 NewFuncName += IsCopy ?
"cpy" :
"ncpy";
443 NewFuncName += IsSafe ?
"_s" :
"";
448 const MatchFinder::MatchResult &Result,
449 DiagnosticBuilder &Diag) {
450 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
451 SmallString<64> NewSecondArg;
454 NewSecondArg = Twine(IsOverflows ? DestLength + 1 : DestLength).str();
458 (IsOverflows ? (!
isInjectUL(Result) ?
" + 1" :
" + 1UL") :
""))
462 NewSecondArg +=
", ";
463 const auto InsertNewArgFix = FixItHint::CreateInsertion(
464 FunctionExpr->getArg(1)->getBeginLoc(), NewSecondArg);
465 Diag << InsertNewArgFix;
469 const MatchFinder::MatchResult &Result,
470 DiagnosticBuilder &Diag) {
471 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
472 int FuncLocStartColumn = Result.SourceManager->getPresumedColumnNumber(
473 FunctionExpr->getBeginLoc());
474 SourceRange SpaceRange(
475 FunctionExpr->getBeginLoc().getLocWithOffset(-FuncLocStartColumn + 1),
476 FunctionExpr->getBeginLoc());
477 StringRef SpaceBeforeStmtStr = Lexer::getSourceText(
478 CharSourceRange::getCharRange(SpaceRange), *Result.SourceManager,
479 Result.Context->getLangOpts(),
nullptr);
481 SmallString<128> NewAddNullTermExprStr;
482 NewAddNullTermExprStr =
483 (Twine(
'\n') + SpaceBeforeStmtStr +
486 "] = " + ((
Name[0] !=
'w') ? R
"('\0';)" : R"(L'\0';)"))
489 const auto AddNullTerminatorExprFix = FixItHint::CreateInsertion(
490 exprLocEnd(FunctionExpr, Result).getLocWithOffset(1),
491 NewAddNullTermExprStr);
492 Diag << AddNullTerminatorExprFix;
502 WantToUseSafeFunctions(Options.get(
"WantToUseSafeFunctions", true)) {}
506 Options.
store(Opts,
"WantToUseSafeFunctions", WantToUseSafeFunctions);
510 const SourceManager &SM, Preprocessor *Pp, Preprocessor *ModuleExpanderPP) {
515AST_MATCHER_P(Expr, hasDefinition, ast_matchers::internal::Matcher<Expr>,
517 const Expr *SimpleNode = &
Node;
518 SimpleNode = SimpleNode->IgnoreParenImpCasts();
520 if (InnerMatcher.matches(*SimpleNode, Finder,
Builder))
523 auto DREHasInit = ignoringImpCasts(
524 declRefExpr(to(varDecl(hasInitializer(ignoringImpCasts(InnerMatcher))))));
526 if (DREHasInit.matches(*SimpleNode, Finder,
Builder))
529 const char *
const VarDeclName =
"variable-declaration";
530 auto DREHasDefinition = ignoringImpCasts(declRefExpr(
531 to(varDecl().bind(VarDeclName)),
532 hasAncestor(compoundStmt(hasDescendant(binaryOperator(
533 hasLHS(declRefExpr(to(varDecl(equalsBoundNode(VarDeclName))))),
534 hasRHS(ignoringImpCasts(InnerMatcher))))))));
536 if (DREHasDefinition.matches(*SimpleNode, Finder,
Builder))
545 binaryOperator(hasOperatorName(
"+"),
546 hasEitherOperand(ignoringParenImpCasts(integerLiteral())));
549 binaryOperator(hasOperatorName(
"-"),
550 hasEitherOperand(ignoringParenImpCasts(integerLiteral())));
552 auto HasIncOp = anyOf(ignoringImpCasts(IncOp), hasDescendant(IncOp));
553 auto HasDecOp = anyOf(ignoringImpCasts(DecOp), hasDescendant(DecOp));
555 auto Container = ignoringImpCasts(cxxMemberCallExpr(hasDescendant(declRefExpr(
556 hasType(hasUnqualifiedDesugaredType(recordType(hasDeclaration(recordDecl(
557 hasAnyName(
"::std::vector",
"::std::list",
"::std::deque"))))))))));
559 auto StringTy = type(hasUnqualifiedDesugaredType(recordType(
560 hasDeclaration(cxxRecordDecl(hasName(
"::std::basic_string"))))));
563 anyOf(hasType(StringTy), hasType(qualType(pointsTo(StringTy))));
565 auto CharTyArray = hasType(qualType(hasCanonicalType(
568 auto CharTyPointer = hasType(
569 qualType(hasCanonicalType(pointerType(pointee(isAnyCharacter())))));
571 auto AnyOfCharTy = anyOf(CharTyArray, CharTyPointer);
579 callExpr(callee(functionDecl(hasAnyName(
"::strlen",
"::wcslen"))))
584 cxxMemberCallExpr(on(expr(AnyOfStringTy).bind(
"Foo")),
585 has(memberExpr(member(hasAnyName(
"size",
"length")))))
589 auto SizeOfCharExpr = unaryExprOrTypeTraitExpr(has(expr(AnyOfCharTy)));
592 ignoringImpCasts(anyOf(Strlen, SizeOrLength, hasDescendant(Strlen),
593 hasDescendant(SizeOrLength)));
597 ignoringImpCasts(declRefExpr(to(varDecl(hasInitializer(WrongLength)))));
599 auto AnyOfCallOrDREWithoutInc = anyOf(DREWithoutInc, WrongLength);
602 auto CallExprReturnWithoutInc = ignoringImpCasts(callExpr(callee(functionDecl(
603 hasBody(has(returnStmt(hasReturnValue(AnyOfCallOrDREWithoutInc))))))));
606 auto DREHasReturnWithoutInc = ignoringImpCasts(
607 declRefExpr(to(varDecl(hasInitializer(CallExprReturnWithoutInc)))));
609 auto AnyOfWrongLengthInit =
610 anyOf(WrongLength, AnyOfCallOrDREWithoutInc, CallExprReturnWithoutInc,
611 DREHasReturnWithoutInc);
619 auto SizeExpr = anyOf(SizeOfCharExpr, integerLiteral(equals(1)));
621 auto MallocLengthExpr = allOf(
623 hasAnyName(
"::alloca",
"::calloc",
"malloc",
"realloc"))),
627 auto DestMalloc = anyOf(callExpr(MallocLengthExpr),
628 hasDescendant(callExpr(MallocLengthExpr)));
631 auto DestCXXNewExpr = ignoringImpCasts(
634 auto AnyOfDestInit = anyOf(DestMalloc, DestCXXNewExpr);
637 auto DestArrayTyDecl = declRefExpr(
642 auto DestUnknownDecl =
647 auto AnyOfDestDecl = ignoringImpCasts(
648 anyOf(allOf(hasDefinition(anyOf(AnyOfDestInit, DestArrayTyDecl,
649 hasDescendant(DestArrayTyDecl))),
651 anyOf(DestUnknownDecl, hasDescendant(DestUnknownDecl))));
653 auto NullTerminatorExpr = binaryOperator(
654 hasLHS(anyOf(hasDescendant(declRefExpr(to(varDecl(
656 hasDescendant(declRefExpr(
658 hasRHS(ignoringImpCasts(
659 anyOf(characterLiteral(equals(0U)), integerLiteral(equals(0))))));
663 anyOf(hasAncestor(cxxMemberCallExpr().bind(
SrcExprName)),
667 ignoringImpCasts(anyOf(stringLiteral().bind(
SrcExprName),
669 SrcDecl, hasDescendant(SrcDecl)));
676 CallContext(StringRef
Name, std::optional<unsigned> DestinationPos,
677 std::optional<unsigned> SourcePos,
unsigned LengthPos,
679 :
Name(
Name), DestinationPos(DestinationPos), SourcePos(SourcePos),
680 LengthPos(LengthPos), WithIncrease(WithIncrease){};
683 std::optional<unsigned> DestinationPos;
684 std::optional<unsigned> SourcePos;
689 auto MatchDestination = [=](CallContext
CC) {
690 return hasArgument(*
CC.DestinationPos,
692 unless(hasAncestor(compoundStmt(
693 hasDescendant(NullTerminatorExpr)))),
697 auto MatchSource = [=](CallContext
CC) {
698 return hasArgument(*
CC.SourcePos, AnyOfSrcDecl);
701 auto MatchGivenLength = [=](CallContext
CC) {
707 allOf(unless(hasDefinition(SizeOfCharExpr)),
708 allOf(
CC.WithIncrease
709 ? ignoringImpCasts(hasDefinition(HasIncOp))
710 : ignoringImpCasts(allOf(
711 unless(hasDefinition(HasIncOp)),
712 anyOf(hasDefinition(binaryOperator().bind(
714 hasDefinition(anything())))),
715 AnyOfWrongLengthInit))),
719 auto MatchCall = [=](CallContext
CC) {
720 std::string CharHandlerFuncName =
"::" +
CC.Name.str();
723 std::string WcharHandlerFuncName =
724 "::" + (
CC.Name.starts_with(
"mem") ?
"w" +
CC.Name.str()
725 :
"wcs" +
CC.Name.substr(3).str());
727 return allOf(callee(functionDecl(
728 hasAnyName(CharHandlerFuncName, WcharHandlerFuncName))),
729 MatchGivenLength(
CC));
732 auto Match = [=](CallContext
CC) {
733 if (
CC.DestinationPos &&
CC.SourcePos)
734 return allOf(MatchCall(
CC), MatchDestination(
CC), MatchSource(
CC));
736 if (
CC.DestinationPos && !
CC.SourcePos)
737 return allOf(MatchCall(
CC), MatchDestination(
CC),
738 hasArgument(*
CC.DestinationPos, anything()));
740 if (!
CC.DestinationPos &&
CC.SourcePos)
741 return allOf(MatchCall(
CC), MatchSource(
CC),
742 hasArgument(*
CC.SourcePos, anything()));
744 llvm_unreachable(
"Unhandled match");
748 auto Memcpy = Match({
"memcpy", 0, 1, 2,
false});
751 auto MemcpyS = Match({
"memcpy_s", 0, 2, 3,
false});
754 auto Memchr = Match({
"memchr", std::nullopt, 0, 2,
false});
757 auto Memmove = Match({
"memmove", 0, 1, 2,
false});
760 auto MemmoveS = Match({
"memmove_s", 0, 2, 3,
false});
763 auto StrncmpRHS = Match({
"strncmp", std::nullopt, 1, 2,
true});
764 auto StrncmpLHS = Match({
"strncmp", std::nullopt, 0, 2,
true});
767 auto Strxfrm = Match({
"strxfrm", 0, 1, 2,
false});
770 auto StrerrorS = Match({
"strerror_s", 0, std::nullopt, 1,
false});
772 auto AnyOfMatchers = anyOf(Memcpy, MemcpyS, Memmove, MemmoveS, StrncmpRHS,
773 StrncmpLHS, Strxfrm, StrerrorS);
780 unless(hasAncestor(castExpr(unless(implicitCastExpr())))))
784 castExpr(allOf(unless(implicitCastExpr()),
791 const MatchFinder::MatchResult &Result) {
792 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
793 if (FunctionExpr->getBeginLoc().isMacroID())
796 if (WantToUseSafeFunctions &&
PP->isMacroDefined(
"__STDC_LIB_EXT1__")) {
797 std::optional<bool> AreSafeFunctionsWanted;
799 Preprocessor::macro_iterator It =
PP->macro_begin();
800 while (It !=
PP->macro_end() && !AreSafeFunctionsWanted) {
801 if (It->first->getName() ==
"__STDC_WANT_LIB_EXT1__") {
802 const auto *MI =
PP->getMacroInfo(It->first);
805 const auto &T = MI->tokens().back();
806 if (T.isLiteral() && T.getLiteralData()) {
807 StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
808 llvm::APInt IntValue;
809 ValueStr.getAsInteger(10, IntValue);
810 AreSafeFunctionsWanted = IntValue.getZExtValue();
818 if (AreSafeFunctionsWanted)
819 UseSafeFunctions = *AreSafeFunctionsWanted;
822 StringRef
Name = FunctionExpr->getDirectCallee()->getName();
823 if (
Name.starts_with(
"mem") ||
Name.starts_with(
"wmem"))
824 memoryHandlerFunctionFix(
Name, Result);
825 else if (
Name ==
"strerror_s")
826 strerror_sFix(Result);
827 else if (
Name.ends_with(
"ncmp"))
828 ncmpFix(
Name, Result);
829 else if (
Name.ends_with(
"xfrm"))
830 xfrmFix(
Name, Result);
833void NotNullTerminatedResultCheck::memoryHandlerFunctionFix(
834 StringRef
Name,
const MatchFinder::MatchResult &Result) {
838 if (
Name.ends_with(
"chr")) {
839 memchrFix(
Name, Result);
843 if ((
Name.contains(
"cpy") ||
Name.contains(
"move")) &&
849 "the result from calling '%0' is not null-terminated")
852 if (
Name.ends_with(
"cpy")) {
853 memcpyFix(
Name, Result, Diag);
854 }
else if (
Name.ends_with(
"cpy_s")) {
855 memcpy_sFix(
Name, Result, Diag);
856 }
else if (
Name.ends_with(
"move")) {
857 memmoveFix(
Name, Result, Diag);
858 }
else if (
Name.ends_with(
"move_s")) {
864void NotNullTerminatedResultCheck::memcpyFix(
865 StringRef
Name,
const MatchFinder::MatchResult &Result,
866 DiagnosticBuilder &Diag) {
873 bool IsSafe = UseSafeFunctions && IsOverflows &&
isKnownDest(Result) &&
876 bool IsDestLengthNotRequired =
882 if (IsSafe && !IsDestLengthNotRequired)
888 if (!IsCopy && !IsSafe)
892void NotNullTerminatedResultCheck::memcpy_sFix(
893 StringRef
Name,
const MatchFinder::MatchResult &Result,
894 DiagnosticBuilder &Diag) {
902 bool IsSafe = IsOverflows;
906 if (!IsSafe || (IsSafe && RemoveDestLength))
914 if (!IsCopy && !IsSafe)
918void NotNullTerminatedResultCheck::memchrFix(
919 StringRef
Name,
const MatchFinder::MatchResult &Result) {
920 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
921 if (
const auto *GivenCL = dyn_cast<CharacterLiteral>(FunctionExpr->getArg(1)))
922 if (GivenCL->getValue() != 0)
925 auto Diag =
diag(FunctionExpr->getArg(2)->IgnoreParenCasts()->getBeginLoc(),
926 "the length is too short to include the null terminator");
928 if (
const auto *CastExpr = Result.Nodes.getNodeAs<Expr>(
CastExprName)) {
929 const auto CastRemoveFix = FixItHint::CreateRemoval(
930 SourceRange(CastExpr->getBeginLoc(),
931 FunctionExpr->getBeginLoc().getLocWithOffset(-1)));
932 Diag << CastRemoveFix;
935 StringRef NewFuncName = (
Name[0] !=
'w') ?
"strchr" :
"wcschr";
940void NotNullTerminatedResultCheck::memmoveFix(
941 StringRef
Name,
const MatchFinder::MatchResult &Result,
942 DiagnosticBuilder &Diag)
const {
946 renameFunc((
Name[0] !=
'w') ?
"memmove_s" :
"wmemmove_s", Result, Diag);
953void NotNullTerminatedResultCheck::strerror_sFix(
954 const MatchFinder::MatchResult &Result) {
957 "the result from calling 'strerror_s' is not null-terminated and "
958 "missing the last character of the error message");
964void NotNullTerminatedResultCheck::ncmpFix(
965 StringRef
Name,
const MatchFinder::MatchResult &Result) {
966 const auto *FunctionExpr = Result.Nodes.getNodeAs<CallExpr>(
FunctionExprName);
967 const Expr *FirstArgExpr = FunctionExpr->getArg(0)->IgnoreImpCasts();
968 const Expr *SecondArgExpr = FunctionExpr->getArg(1)->IgnoreImpCasts();
969 bool IsLengthTooLong =
false;
972 const Expr *LengthExprArg = StrlenExpr->getArg(0);
973 StringRef FirstExprStr =
exprToStr(FirstArgExpr, Result).trim();
974 StringRef SecondExprStr =
exprToStr(SecondArgExpr, Result).trim();
975 StringRef LengthArgStr =
exprToStr(LengthExprArg, Result).trim();
977 LengthArgStr == FirstExprStr || LengthArgStr == SecondExprStr;
982 if (SrcLength != 0 && GivenLength != 0)
983 IsLengthTooLong = GivenLength > SrcLength;
989 auto Diag =
diag(FunctionExpr->getArg(2)->IgnoreParenCasts()->getBeginLoc(),
990 "comparison length is too long and might lead to a "
996void NotNullTerminatedResultCheck::xfrmFix(
997 StringRef
Name,
const MatchFinder::MatchResult &Result) {
1003 "the result from calling '%0' is not null-terminated")
const FunctionDecl * Decl
llvm::SmallString< 256U > Name
CodeCompletionBuilder Builder
::clang::DynTypedNode Node
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
const LangOptions & getLangOpts() const
Returns the language options from the context.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
Override this to register PPCallbacks in the preprocessor.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
NotNullTerminatedResultCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
constexpr llvm::StringLiteral CastExprName
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)
static bool isKnownDest(const MatchFinder::MatchResult &Result)
static bool isDestAndSrcEquals(const MatchFinder::MatchResult &Result)
AST_MATCHER_P(FunctionDecl, parameterCountGE, unsigned, N)
Matches functions that have at least the specified amount of parameters.
static bool isDestExprFix(const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag)
constexpr llvm::StringLiteral FunctionExprName
static SourceLocation exprLocEnd(const Expr *E, const MatchFinder::MatchResult &Result)
constexpr llvm::StringLiteral UnknownLengthName
static int getGivenLength(const MatchFinder::MatchResult &Result)
constexpr llvm::StringLiteral WrongLengthExprName
constexpr llvm::StringLiteral LengthExprName
static bool isDestBasedOnGivenLength(const MatchFinder::MatchResult &Result)
constexpr llvm::StringLiteral DestMallocExprName
constexpr llvm::StringLiteral DestArrayTyName
constexpr llvm::StringLiteral UnknownDestName
static const Expr * getDestCapacityExpr(const MatchFinder::MatchResult &Result)
static bool isGivenLengthEqualToSrcLength(const MatchFinder::MatchResult &Result)
constexpr llvm::StringLiteral SrcVarDeclName
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)
constexpr llvm::StringLiteral DestVarDeclName
static void removeArg(int ArgPos, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag)
static unsigned getLength(const Expr *E, const MatchFinder::MatchResult &Result)
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 llvm::StringLiteral SrcExprName
constexpr llvm::StringLiteral DestExprName
llvm::StringMap< ClangTidyValue > OptionMap