BadSignalToKillThreadCheck.cpp 2.5 KB

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