void InaccurateEraseCheck::registerMatchers(MatchFinder *Finder) {
  // Only register the matchers for C++; the functionality currently does not
  // provide any benefit to other languages, despite being benign.
  if (!getLangOpts().CPlusPlus)
    return;

  const auto CheckForEndCall = hasArgument(
      1, anyOf(cxxConstructExpr(has(ignoringParenImpCasts(
                   cxxMemberCallExpr(callee(cxxMethodDecl(hasName("end"))))
                       .bind("InaccEndCall")))),
               anything()));

  Finder->addMatcher(
      cxxMemberCallExpr(
          on(hasType(namedDecl(matchesName("^::std::")))),
          callee(cxxMethodDecl(hasName("erase"))), argumentCountIs(1),
          hasArgument(0, has(ignoringParenImpCasts(
                             callExpr(callee(functionDecl(matchesName(
                                          "^::std::(remove(_if)?|unique)$"))),
                                      CheckForEndCall)
                                 .bind("InaccAlgCall")))),
          unless(isInTemplateInstantiation()))
          .bind("InaccErase"),
      this);
}
void InaccurateEraseCheck::registerMatchers(MatchFinder *Finder) {
  // Only register the matchers for C++; the functionality currently does not
  // provide any benefit to other languages, despite being benign.
  if (!getLangOpts().CPlusPlus)
    return;

  const auto EndCall =
      callExpr(
          callee(functionDecl(hasAnyName("remove", "remove_if", "unique"))),
          hasArgument(
              1,
              anyOf(cxxConstructExpr(has(ignoringImplicit(
                        cxxMemberCallExpr(callee(cxxMethodDecl(hasName("end"))))
                            .bind("end")))),
                    anything())))
          .bind("alg");

  const auto DeclInStd = type(hasUnqualifiedDesugaredType(
      tagType(hasDeclaration(decl(isInStdNamespace())))));
  Finder->addMatcher(
      cxxMemberCallExpr(
          on(anyOf(hasType(DeclInStd), hasType(pointsTo(DeclInStd)))),
          callee(cxxMethodDecl(hasName("erase"))), argumentCountIs(1),
          hasArgument(0, has(ignoringImplicit(
                             anyOf(EndCall, has(ignoringImplicit(EndCall)))))),
          unless(isInTemplateInstantiation()))
          .bind("erase"),
      this);
}
void StrCatAppendCheck::registerMatchers(MatchFinder *Finder) {
  if (!getLangOpts().CPlusPlus)
  	return;
  const auto StrCat = functionDecl(hasName("::absl::StrCat"));
  // The arguments of absl::StrCat are implicitly converted to AlphaNum. This 
  // matches to the arguments because of that behavior. 
  const auto AlphaNum = IgnoringTemporaries(cxxConstructExpr(
      argumentCountIs(1), hasType(cxxRecordDecl(hasName("::absl::AlphaNum"))),
      hasArgument(0, ignoringImpCasts(declRefExpr(to(equalsBoundNode("LHS")),
                                                  expr().bind("Arg0"))))));

  const auto HasAnotherReferenceToLhs =
      callExpr(hasAnyArgument(expr(hasDescendant(declRefExpr(
          to(equalsBoundNode("LHS")), unless(equalsBoundNode("Arg0")))))));

  // Now look for calls to operator= with an object on the LHS and a call to
  // StrCat on the RHS. The first argument of the StrCat call should be the same
  // as the LHS. Ignore calls from template instantiations.
  Finder->addMatcher(
      cxxOperatorCallExpr(
          unless(isInTemplateInstantiation()), hasOverloadedOperatorName("="),
          hasArgument(0, declRefExpr(to(decl().bind("LHS")))),
          hasArgument(1, IgnoringTemporaries(
                             callExpr(callee(StrCat), hasArgument(0, AlphaNum),
                                      unless(HasAnotherReferenceToLhs))
                                 .bind("Call"))))
          .bind("Op"),
      this);
}
void UseUncaughtExceptionsCheck::registerMatchers(MatchFinder *Finder) {
  if (!getLangOpts().CPlusPlus17)
    return;

  std::string MatchText = "::std::uncaught_exception";

  // Using declaration: warning and fix-it.
  Finder->addMatcher(
      usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(hasName(MatchText))))
          .bind("using_decl"),
      this);

  // DeclRefExpr: warning, no fix-it.
  Finder->addMatcher(declRefExpr(allOf(to(functionDecl(hasName(MatchText))),
                                       unless(callExpr())))
                         .bind("decl_ref_expr"),
                     this);

  // CallExpr: warning, fix-it.
  Finder->addMatcher(
      callExpr(allOf(hasDeclaration(functionDecl(hasName(MatchText))),
                     unless(hasAncestor(initListExpr()))))
          .bind("call_expr"),
      this);
  // CallExpr in initialisation list: warning, fix-it with avoiding narrowing
  // conversions.
  Finder->addMatcher(
      callExpr(allOf(hasAncestor(initListExpr()),
                     hasDeclaration(functionDecl(hasName(MatchText)))))
          .bind("init_call_expr"),
      this);
}
TEST_F(StructuralEquivalenceCXXMethodTest, Operator) {
  auto t = makeDecls<FunctionDecl>(
      "struct X { int operator +(int); };",
      "struct X { int operator -(int); };", Lang_CXX,
      functionDecl(hasOverloadedOperatorName("+")),
      functionDecl(hasOverloadedOperatorName("-")));
  EXPECT_FALSE(testStructuralMatch(t));
}
void FoldInitTypeCheck::registerMatchers(MatchFinder *Finder) {
  // We match functions of interest and bind the iterator and init value types.
  // Note: Right now we check only builtin types.
  const auto BuiltinTypeWithId = [](const char *ID) {
    return hasCanonicalType(builtinType().bind(ID));
  };
  const auto IteratorWithValueType = [&BuiltinTypeWithId](const char *ID) {
    return anyOf(
        // Pointer types.
        pointsTo(BuiltinTypeWithId(ID)),
        // Iterator types.
        recordType(hasDeclaration(has(typedefNameDecl(
            hasName("value_type"), hasType(BuiltinTypeWithId(ID)))))));
  };

  const auto IteratorParam = parmVarDecl(
      hasType(hasCanonicalType(IteratorWithValueType("IterValueType"))));
  const auto Iterator2Param = parmVarDecl(
      hasType(hasCanonicalType(IteratorWithValueType("Iter2ValueType"))));
  const auto InitParam = parmVarDecl(hasType(BuiltinTypeWithId("InitType")));

  // std::accumulate, std::reduce.
  Finder->addMatcher(
      callExpr(callee(functionDecl(
                   hasAnyName("::std::accumulate", "::std::reduce"),
                   hasParameter(0, IteratorParam), hasParameter(2, InitParam))),
               argumentCountIs(3))
          .bind("Call"),
      this);
  // std::inner_product.
  Finder->addMatcher(
      callExpr(callee(functionDecl(hasName("::std::inner_product"),
                                   hasParameter(0, IteratorParam),
                                   hasParameter(2, Iterator2Param),
                                   hasParameter(3, InitParam))),
               argumentCountIs(4))
          .bind("Call"),
      this);
  // std::reduce with a policy.
  Finder->addMatcher(
      callExpr(callee(functionDecl(hasName("::std::reduce"),
                                   hasParameter(1, IteratorParam),
                                   hasParameter(3, InitParam))),
               argumentCountIs(4))
          .bind("Call"),
      this);
  // std::inner_product with a policy.
  Finder->addMatcher(
      callExpr(callee(functionDecl(hasName("::std::inner_product"),
                                   hasParameter(1, IteratorParam),
                                   hasParameter(3, Iterator2Param),
                                   hasParameter(4, InitParam))),
               argumentCountIs(5))
          .bind("Call"),
      this);
}
void MisplacedOperatorInStrlenInAllocCheck::registerMatchers(
    MatchFinder *Finder) {
  const auto StrLenFunc = functionDecl(anyOf(
      hasName("::strlen"), hasName("::std::strlen"), hasName("::strnlen"),
      hasName("::std::strnlen"), hasName("::strnlen_s"),
      hasName("::std::strnlen_s"), hasName("::wcslen"),
      hasName("::std::wcslen"), hasName("::wcsnlen"), hasName("::std::wcsnlen"),
      hasName("::wcsnlen_s"), hasName("std::wcsnlen_s")));

  const auto BadUse =
      callExpr(callee(StrLenFunc),
               hasAnyArgument(ignoringImpCasts(
                   binaryOperator(
                       hasOperatorName("+"),
                       hasRHS(ignoringParenImpCasts(integerLiteral(equals(1)))))
                       .bind("BinOp"))))
          .bind("StrLen");

  const auto BadArg = anyOf(
      allOf(unless(binaryOperator(
                hasOperatorName("+"), hasLHS(BadUse),
                hasRHS(ignoringParenImpCasts(integerLiteral(equals(1)))))),
            hasDescendant(BadUse)),
      BadUse);

  const auto Alloc0Func =
      functionDecl(anyOf(hasName("::malloc"), hasName("std::malloc"),
                         hasName("::alloca"), hasName("std::alloca")));
  const auto Alloc1Func =
      functionDecl(anyOf(hasName("::calloc"), hasName("std::calloc"),
                         hasName("::realloc"), hasName("std::realloc")));

  const auto Alloc0FuncPtr =
      varDecl(hasType(isConstQualified()),
              hasInitializer(ignoringParenImpCasts(
                  declRefExpr(hasDeclaration(Alloc0Func)))));
  const auto Alloc1FuncPtr =
      varDecl(hasType(isConstQualified()),
              hasInitializer(ignoringParenImpCasts(
                  declRefExpr(hasDeclaration(Alloc1Func)))));

  Finder->addMatcher(callExpr(callee(decl(anyOf(Alloc0Func, Alloc0FuncPtr))),
                              hasArgument(0, BadArg))
                         .bind("Alloc"),
                     this);
  Finder->addMatcher(callExpr(callee(decl(anyOf(Alloc1Func, Alloc1FuncPtr))),
                              hasArgument(1, BadArg))
                         .bind("Alloc"),
                     this);
  Finder->addMatcher(
      cxxNewExpr(isArray(), hasArraySize(BadArg)).bind("Alloc"), this);
}
void DefinitionsInHeadersCheck::registerMatchers(MatchFinder *Finder) {
  if (UseHeaderFileExtension) {
    Finder->addMatcher(
        namedDecl(anyOf(functionDecl(isDefinition()), varDecl(isDefinition())),
                  isHeaderFileExtension()).bind("name-decl"),
        this);
  } else {
    Finder->addMatcher(
        namedDecl(anyOf(functionDecl(isDefinition()), varDecl(isDefinition())),
                  anyOf(isHeaderFileExtension(),
                        unless(isExpansionInMainFile()))).bind("name-decl"),
        this);
  }
}
void
OverloadedUnaryAndCheck::registerMatchers(ast_matchers::MatchFinder *Finder) {
    // Match unary methods that overload operator&.
    Finder->addMatcher(methodDecl(parameterCountIs(0), hasOverloadedOperatorName(
                                      "&")).bind("overload"),
                       this);
    // Also match freestanding unary operator& overloads. Be careful not to match
    // binary methods.
    Finder->addMatcher(
        functionDecl(
            allOf(unless(methodDecl()),
                  functionDecl(parameterCountIs(1),
                               hasOverloadedOperatorName("&")).bind("overload"))),
        this);
}
void CommandProcessorCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(
      callExpr(
          callee(functionDecl(anyOf(hasName("::system"), hasName("::popen"),
                                    hasName("::_popen")))
                     .bind("func")),
          // Do not diagnose when the call expression passes a null pointer
          // constant to system(); that only checks for the presence of a
          // command processor, which is not a security risk by itself.
          unless(callExpr(callee(functionDecl(hasName("::system"))),
                          argumentCountIs(1),
                          hasArgument(0, nullPointerConstant()))))
          .bind("expr"),
      this);
}
namespace ProgrammingLanguage {

    //match a simple funcion including method
    DeclarationMatcher funcMatcherPL = functionDecl().bind("func");

    int countRef = 0;
}
void RedundantVoidArgCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(functionDecl(parameterCountIs(0), unless(isImplicit()),
                                  unless(isExternC()))
                         .bind(FunctionId),
                     this);
  Finder->addMatcher(typedefNameDecl().bind(TypedefId), this);
  auto ParenFunctionType = parenType(innerType(functionType()));
  auto PointerToFunctionType = pointee(ParenFunctionType);
  auto FunctionOrMemberPointer =
      anyOf(hasType(pointerType(PointerToFunctionType)),
            hasType(memberPointerType(PointerToFunctionType)));
  Finder->addMatcher(fieldDecl(FunctionOrMemberPointer).bind(FieldId), this);
  Finder->addMatcher(varDecl(FunctionOrMemberPointer).bind(VarId), this);
  auto CastDestinationIsFunction =
      hasDestinationType(pointsTo(ParenFunctionType));
  Finder->addMatcher(
      cStyleCastExpr(CastDestinationIsFunction).bind(CStyleCastId), this);
  Finder->addMatcher(
      cxxStaticCastExpr(CastDestinationIsFunction).bind(NamedCastId), this);
  Finder->addMatcher(
      cxxReinterpretCastExpr(CastDestinationIsFunction).bind(NamedCastId),
      this);
  Finder->addMatcher(
      cxxConstCastExpr(CastDestinationIsFunction).bind(NamedCastId), this);
  Finder->addMatcher(lambdaExpr().bind(LambdaId), this);
}
void InefficientAlgorithmCheck::registerMatchers(MatchFinder *Finder) {
  // Only register the matchers for C++; the functionality currently does not
  // provide any benefit to other languages, despite being benign.
  if (!getLangOpts().CPlusPlus)
    return;

  const std::string Algorithms =
      "^::std::(find|count|equal_range|lower_bound|upper_bound)$";
  const auto ContainerMatcher = classTemplateSpecializationDecl(
      matchesName("^::std::(unordered_)?(multi)?(set|map)$"));
  const auto Matcher =
      callExpr(
          callee(functionDecl(matchesName(Algorithms))),
          hasArgument(
              0, constructExpr(has(memberCallExpr(
                     callee(methodDecl(hasName("begin"))),
                     on(declRefExpr(
                            hasDeclaration(decl().bind("IneffContObj")),
                            anyOf(hasType(ContainerMatcher.bind("IneffCont")),
                                  hasType(pointsTo(
                                      ContainerMatcher.bind("IneffContPtr")))))
                            .bind("IneffContExpr")))))),
          hasArgument(1, constructExpr(has(memberCallExpr(
                             callee(methodDecl(hasName("end"))),
                             on(declRefExpr(hasDeclaration(
                                 equalsBoundNode("IneffContObj")))))))),
          hasArgument(2, expr().bind("AlgParam")),
          unless(isInTemplateInstantiation()))
          .bind("IneffAlg");

  Finder->addMatcher(Matcher, this);
}
void AvoidSpinlockCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(
      callExpr(callee((functionDecl(hasAnyName(
                   "OSSpinlockLock", "OSSpinlockUnlock", "OSSpinlockTry")))))
          .bind("spinlock"),
      this);
}
void FasterStringFindCheck::registerMatchers(MatchFinder *Finder) {
  if (!getLangOpts().CPlusPlus)
    return;

  const auto SingleChar =
      expr(ignoringParenCasts(stringLiteral(hasSize(1)).bind("literal")));

  const auto StringFindFunctions =
      anyOf(hasName("find"), hasName("rfind"), hasName("find_first_of"),
            hasName("find_first_not_of"), hasName("find_last_of"),
            hasName("find_last_not_of"));

  llvm::Optional<ast_matchers::internal::Matcher<NamedDecl>> IsStringClass;

  for (const auto &ClassName : StringLikeClasses) {
    const auto HasName = hasName(ClassName);
    IsStringClass = IsStringClass ? anyOf(*IsStringClass, HasName) : HasName;
  }

  if (IsStringClass) {
    Finder->addMatcher(
        cxxMemberCallExpr(
            callee(functionDecl(StringFindFunctions).bind("func")),
            anyOf(argumentCountIs(1), argumentCountIs(2)),
            hasArgument(0, SingleChar),
            on(expr(hasType(recordDecl(*IsStringClass)),
                    unless(hasSubstitutedType())))),
        this);
  }
}
void ConstReturnTypeCheck::registerMatchers(MatchFinder *Finder) {
  // Find all function definitions for which the return types are `const`
  // qualified.
  Finder->addMatcher(
      functionDecl(returns(isConstQualified()), isDefinition()).bind("func"),
      this);
}
RelationConstructionVisitor::RelationConstructionVisitor(
  SymbolsMapType &symbols) : mSymbols(symbols) {
  Matcher.addMatcher(
    functionDecl(
      forEachDescendant(
        declRefExpr().bind("declRefExpr"))).bind("functionDecl"),
    &gDeclRefExprHandler);
}
TEST_F(StructuralEquivalenceCXXMethodTest, OutOfClass2) {
  auto t = makeDecls<FunctionDecl>(
      "struct X { virtual void f(); }; void X::f() { }",
      "struct X { void f(); }; void X::f() { }",
      Lang_CXX,
      functionDecl(allOf(hasName("f"), isDefinition())));
  EXPECT_FALSE(testStructuralMatch(t));
}
void CloexecSocketCheck::registerMatchers(MatchFinder *Finder) {
  registerMatchersImpl(Finder,
                       functionDecl(isExternC(), returns(isInteger()),
                                    hasName("socket"),
                                    hasParameter(0, hasType(isInteger())),
                                    hasParameter(1, hasType(isInteger())),
                                    hasParameter(2, hasType(isInteger()))));
}
Beispiel #20
0
void ScopeChecker::registerMatchers(MatchFinder *AstMatcher) {
  AstMatcher->addMatcher(varDecl().bind("node"), this);
  AstMatcher->addMatcher(cxxNewExpr().bind("node"), this);
  AstMatcher->addMatcher(materializeTemporaryExpr().bind("node"), this);
  AstMatcher->addMatcher(
      callExpr(callee(functionDecl(heapAllocator()))).bind("node"), this);
  AstMatcher->addMatcher(parmVarDecl().bind("parm_vardecl"), this);
}
void
MemsetZeroLengthCheck::registerMatchers(ast_matchers::MatchFinder *Finder) {
  // Look for memset(x, y, 0) as those is most likely an argument swap.
  // TODO: Also handle other standard functions that suffer from the same
  //       problem, e.g. memchr.
  Finder->addMatcher(
      callExpr(callee(functionDecl(hasName("::memset"))), argumentCountIs(3),
               unless(isInTemplateInstantiation())).bind("decl"),
      this);
}
void DurationSubtractionCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(
      binaryOperator(
          hasOperatorName("-"),
          hasLHS(callExpr(callee(functionDecl(DurationConversionFunction())
                                     .bind("function_decl")),
                          hasArgument(0, expr().bind("lhs_arg")))))
          .bind("binop"),
      this);
}
void Rule_18_7_1::registerMatchers(ast_matchers::MatchFinder *Finder) {
  Finder->addMatcher(callExpr(callee(functionDecl(anyOf(hasName("::signal"),
                                                        hasName("::raise")))))
                         .bind("CallExpr"),
                     this);

  Finder->addMatcher(
      varDecl(hasType(namedDecl(hasName("::sig_atomic_t")))).bind("VarDecl"),
      this);
}
void StaticObjectExceptionCheck::registerMatchers(MatchFinder *Finder) {
  if ((!getLangOpts().CPlusPlus) || (!getLangOpts().CXXExceptions))
    return;

  // Match any static or thread_local variable declaration that has an
  // initializer that can throw.
  Finder->addMatcher(
      varDecl(anyOf(hasThreadStorageDuration(), hasStaticStorageDuration()),
              unless(anyOf(isConstexpr(), hasType(cxxRecordDecl(isLambda())),
                           hasAncestor(functionDecl()))),
              anyOf(hasDescendant(cxxConstructExpr(hasDeclaration(
                        cxxConstructorDecl(unless(isNoThrow())).bind("func")))),
                    hasDescendant(cxxNewExpr(hasDeclaration(
                        functionDecl(unless(isNoThrow())).bind("func")))),
                    hasDescendant(callExpr(hasDeclaration(
                        functionDecl(unless(isNoThrow())).bind("func"))))))
          .bind("var"),
      this);
}
void DurationAdditionCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(
      binaryOperator(hasOperatorName("+"),
                     hasEitherOperand(expr(ignoringParenImpCasts(
                         callExpr(callee(functionDecl(TimeConversionFunction())
                                             .bind("function_decl")))
                             .bind("call")))))
          .bind("binop"),
      this);
}
void AvoidBindCheck::registerMatchers(MatchFinder *Finder) {
  if (!getLangOpts().CPlusPlus14) // Need C++14 for generic lambdas.
    return;

  Finder->addMatcher(
      callExpr(callee(namedDecl(hasName("::std::bind"))),
               hasArgument(0, declRefExpr(to(functionDecl().bind("f")))))
          .bind("bind"),
      this);
}
void CloexecAcceptCheck::registerMatchers(MatchFinder *Finder) {
  auto SockAddrPointerType =
      hasType(pointsTo(recordDecl(isStruct(), hasName("sockaddr"))));
  auto SockLenPointerType = hasType(pointsTo(namedDecl(hasName("socklen_t"))));

  registerMatchersImpl(Finder,
                       functionDecl(returns(isInteger()), hasName("accept"),
                                    hasParameter(0, hasType(isInteger())),
                                    hasParameter(1, SockAddrPointerType),
                                    hasParameter(2, SockLenPointerType)));
}
void UnnecessaryValueParamCheck::registerMatchers(MatchFinder *Finder) {
  const auto ExpensiveValueParamDecl =
      parmVarDecl(hasType(hasCanonicalType(allOf(matchers::isExpensiveToCopy(),
                                                 unless(referenceType())))),
                  decl().bind("param"));
  Finder->addMatcher(
      functionDecl(isDefinition(), unless(cxxMethodDecl(isOverride())),
                   unless(isInstantiated()),
                   has(typeLoc(forEach(ExpensiveValueParamDecl))),
                   decl().bind("functionDecl")),
      this);
}
Beispiel #29
0
void FunctionSizeCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(
      functionDecl(
          unless(isInstantiated()),
          forEachDescendant(
              stmt(unless(compoundStmt()),
                   hasParent(stmt(anyOf(compoundStmt(), ifStmt(),
                                        anyOf(whileStmt(), doStmt(),
                                              forRangeStmt(), forStmt())))))
                  .bind("stmt"))).bind("func"),
      this);
}
void DurationConversionCastCheck::registerMatchers(MatchFinder *Finder) {
  auto CallMatcher = ignoringImpCasts(callExpr(
      callee(functionDecl(DurationConversionFunction()).bind("func_decl")),
      hasArgument(0, expr().bind("arg"))));

  Finder->addMatcher(
      expr(anyOf(
          cxxStaticCastExpr(hasSourceExpression(CallMatcher)).bind("cast_expr"),
          cStyleCastExpr(hasSourceExpression(CallMatcher)).bind("cast_expr"),
          cxxFunctionalCastExpr(hasSourceExpression(CallMatcher))
              .bind("cast_expr"))),
      this);
}