1 //===-- CommandProcessorCheck.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 "CommandProcessorCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang {
16 namespace tidy {
17 namespace cert {
18 
19 void CommandProcessorCheck::registerMatchers(MatchFinder *Finder) {
20   Finder->addMatcher(
21       callExpr(
22           callee(functionDecl(anyOf(hasName("::system"), hasName("::popen"),
23                                     hasName("::_popen")))
24                      .bind("func")),
25           // Do not diagnose when the call expression passes a null pointer
26           // constant to system(); that only checks for the presence of a
27           // command processor, which is not a security risk by itself.
28           unless(callExpr(callee(functionDecl(hasName("::system"))),
29                           argumentCountIs(1),
30                           hasArgument(0, nullPointerConstant()))))
31           .bind("expr"),
32       this);
33 }
34 
35 void CommandProcessorCheck::check(const MatchFinder::MatchResult &Result) {
36   const auto *Fn = Result.Nodes.getNodeAs<FunctionDecl>("func");
37   const auto *E = Result.Nodes.getNodeAs<CallExpr>("expr");
38 
39   diag(E->getExprLoc(), "calling %0 uses a command processor") << Fn;
40 }
41 
42 } // namespace cert
43 } // namespace tidy
44 } // namespace clang
45