clang-tools 23.0.0git
BadSignalToKillThreadCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Lex/Preprocessor.h"
13#include <optional>
14
15using namespace clang::ast_matchers;
16
17namespace clang::tidy::bugprone {
18
20 Finder->addMatcher(
21 callExpr(callee(functionDecl(hasName("::pthread_kill"))),
22 argumentCountIs(2),
23 hasArgument(1, integerLiteral().bind("integer-literal")))
24 .bind("thread-kill"),
25 this);
26}
27
28static Preprocessor *PP;
29
30void BadSignalToKillThreadCheck::check(const MatchFinder::MatchResult &Result) {
31 const auto IsSigterm = [](const auto &KeyValue) -> bool {
32 return KeyValue.first->getName() == "SIGTERM" &&
33 KeyValue.first->hasMacroDefinition();
34 };
35 const auto Macros = PP->macros();
36 const auto TryExpandAsInteger =
37 [&](Preprocessor::macro_iterator It) -> std::optional<unsigned> {
38 if (It == Macros.end())
39 return std::nullopt;
40 const MacroInfo *MI = PP->getMacroInfo(It->first);
41 const Token &T = MI->tokens().back();
42
43 if (!T.isLiteral())
44 return std::nullopt;
45
46 SmallVector<char> Buffer;
47 bool Invalid = false;
48 const StringRef ValueStr = PP->getSpelling(T, Buffer, &Invalid);
49 if (Invalid)
50 return std::nullopt;
51
52 llvm::APInt IntValue;
53 constexpr unsigned AutoSenseRadix = 0;
54 if (ValueStr.getAsInteger(AutoSenseRadix, IntValue))
55 return std::nullopt;
56 return IntValue.getZExtValue();
57 };
58
59 const auto SigtermMacro = llvm::find_if(Macros, IsSigterm);
60
61 if (!SigtermValue && !(SigtermValue = TryExpandAsInteger(SigtermMacro)))
62 return;
63
64 const auto *MatchedExpr = Result.Nodes.getNodeAs<Expr>("thread-kill");
65 const auto *MatchedIntLiteral =
66 Result.Nodes.getNodeAs<IntegerLiteral>("integer-literal");
67 if (MatchedIntLiteral->getValue() == *SigtermValue) {
68 diag(MatchedExpr->getBeginLoc(),
69 "thread should not be terminated by raising the 'SIGTERM' signal");
70 }
71}
72
74 const SourceManager &SM, Preprocessor *Pp, Preprocessor *ModuleExpanderPP) {
75 PP = Pp;
76}
77
78} // namespace clang::tidy::bugprone
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override