1 //===--- StringConstructorCheck.cpp - clang-tidy---------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "StringConstructorCheck.h" 10 #include "clang/AST/ASTContext.h" 11 #include "clang/ASTMatchers/ASTMatchFinder.h" 12 #include "clang/Tooling/FixIt.h" 13 14 using namespace clang::ast_matchers; 15 16 namespace clang { 17 namespace tidy { 18 namespace bugprone { 19 20 namespace { 21 AST_MATCHER_P(IntegerLiteral, isBiggerThan, unsigned, N) { 22 return Node.getValue().getZExtValue() > N; 23 } 24 } // namespace 25 26 StringConstructorCheck::StringConstructorCheck(StringRef Name, 27 ClangTidyContext *Context) 28 : ClangTidyCheck(Name, Context), 29 WarnOnLargeLength(Options.get("WarnOnLargeLength", true)), 30 LargeLengthThreshold(Options.get("LargeLengthThreshold", 0x800000)) {} 31 32 void StringConstructorCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { 33 Options.store(Opts, "WarnOnLargeLength", WarnOnLargeLength); 34 Options.store(Opts, "LargeLengthThreshold", LargeLengthThreshold); 35 } 36 37 void StringConstructorCheck::registerMatchers(MatchFinder *Finder) { 38 const auto ZeroExpr = expr(ignoringParenImpCasts(integerLiteral(equals(0)))); 39 const auto CharExpr = expr(ignoringParenImpCasts(characterLiteral())); 40 const auto NegativeExpr = expr(ignoringParenImpCasts( 41 unaryOperator(hasOperatorName("-"), 42 hasUnaryOperand(integerLiteral(unless(equals(0))))))); 43 const auto LargeLengthExpr = expr(ignoringParenImpCasts( 44 integerLiteral(isBiggerThan(LargeLengthThreshold)))); 45 const auto CharPtrType = type(anyOf(pointerType(), arrayType())); 46 47 // Match a string-literal; even through a declaration with initializer. 48 const auto BoundStringLiteral = stringLiteral().bind("str"); 49 const auto ConstStrLiteralDecl = varDecl( 50 isDefinition(), hasType(constantArrayType()), hasType(isConstQualified()), 51 hasInitializer(ignoringParenImpCasts(BoundStringLiteral))); 52 const auto ConstPtrStrLiteralDecl = varDecl( 53 isDefinition(), 54 hasType(pointerType(pointee(isAnyCharacter(), isConstQualified()))), 55 hasInitializer(ignoringParenImpCasts(BoundStringLiteral))); 56 const auto ConstStrLiteral = expr(ignoringParenImpCasts(anyOf( 57 BoundStringLiteral, declRefExpr(hasDeclaration(anyOf( 58 ConstPtrStrLiteralDecl, ConstStrLiteralDecl)))))); 59 60 // Check the fill constructor. Fills the string with n consecutive copies of 61 // character c. [i.e string(size_t n, char c);]. 62 Finder->addMatcher( 63 cxxConstructExpr( 64 hasDeclaration(cxxMethodDecl(hasName("basic_string"))), 65 hasArgument(0, hasType(qualType(isInteger()))), 66 hasArgument(1, hasType(qualType(isInteger()))), 67 anyOf( 68 // Detect the expression: string('x', 40); 69 hasArgument(0, CharExpr.bind("swapped-parameter")), 70 // Detect the expression: string(0, ...); 71 hasArgument(0, ZeroExpr.bind("empty-string")), 72 // Detect the expression: string(-4, ...); 73 hasArgument(0, NegativeExpr.bind("negative-length")), 74 // Detect the expression: string(0x1234567, ...); 75 hasArgument(0, LargeLengthExpr.bind("large-length")))) 76 .bind("constructor"), 77 this); 78 79 // Check the literal string constructor with char pointer and length 80 // parameters. [i.e. string (const char* s, size_t n);] 81 Finder->addMatcher( 82 cxxConstructExpr( 83 hasDeclaration(cxxMethodDecl(hasName("basic_string"))), 84 hasArgument(0, hasType(CharPtrType)), 85 hasArgument(1, hasType(isInteger())), 86 anyOf( 87 // Detect the expression: string("...", 0); 88 hasArgument(1, ZeroExpr.bind("empty-string")), 89 // Detect the expression: string("...", -4); 90 hasArgument(1, NegativeExpr.bind("negative-length")), 91 // Detect the expression: string("lit", 0x1234567); 92 hasArgument(1, LargeLengthExpr.bind("large-length")), 93 // Detect the expression: string("lit", 5) 94 allOf(hasArgument(0, ConstStrLiteral.bind("literal-with-length")), 95 hasArgument(1, ignoringParenImpCasts( 96 integerLiteral().bind("int")))))) 97 .bind("constructor"), 98 this); 99 100 // Check the literal string constructor with char pointer. 101 // [i.e. string (const char* s);] 102 Finder->addMatcher( 103 cxxConstructExpr(hasDeclaration(cxxMethodDecl(hasName("basic_string"))), 104 hasArgument(0, expr().bind("from-ptr")), 105 hasArgument(1, unless(hasType(isInteger())))) 106 .bind("constructor"), 107 this); 108 } 109 110 void StringConstructorCheck::check(const MatchFinder::MatchResult &Result) { 111 const ASTContext &Ctx = *Result.Context; 112 const auto *E = Result.Nodes.getNodeAs<CXXConstructExpr>("constructor"); 113 assert(E && "missing constructor expression"); 114 SourceLocation Loc = E->getBeginLoc(); 115 116 if (Result.Nodes.getNodeAs<Expr>("swapped-parameter")) { 117 const Expr *P0 = E->getArg(0); 118 const Expr *P1 = E->getArg(1); 119 diag(Loc, "string constructor parameters are probably swapped;" 120 " expecting string(count, character)") 121 << tooling::fixit::createReplacement(*P0, *P1, Ctx) 122 << tooling::fixit::createReplacement(*P1, *P0, Ctx); 123 } else if (Result.Nodes.getNodeAs<Expr>("empty-string")) { 124 diag(Loc, "constructor creating an empty string"); 125 } else if (Result.Nodes.getNodeAs<Expr>("negative-length")) { 126 diag(Loc, "negative value used as length parameter"); 127 } else if (Result.Nodes.getNodeAs<Expr>("large-length")) { 128 if (WarnOnLargeLength) 129 diag(Loc, "suspicious large length parameter"); 130 } else if (Result.Nodes.getNodeAs<Expr>("literal-with-length")) { 131 const auto *Str = Result.Nodes.getNodeAs<StringLiteral>("str"); 132 const auto *Lit = Result.Nodes.getNodeAs<IntegerLiteral>("int"); 133 if (Lit->getValue().ugt(Str->getLength())) { 134 diag(Loc, "length is bigger than string literal size"); 135 } 136 } else if (const auto *Ptr = Result.Nodes.getNodeAs<Expr>("from-ptr")) { 137 Expr::EvalResult ConstPtr; 138 if (!Ptr->isInstantiationDependent() && 139 Ptr->EvaluateAsRValue(ConstPtr, Ctx) && 140 ((ConstPtr.Val.isInt() && ConstPtr.Val.getInt().isNullValue()) || 141 (ConstPtr.Val.isLValue() && ConstPtr.Val.isNullPointer()))) { 142 diag(Loc, "constructing string from nullptr is undefined behaviour"); 143 } 144 } 145 } 146 147 } // namespace bugprone 148 } // namespace tidy 149 } // namespace clang 150