brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.3 KiB · fbcde0a Raw
66 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 9#include "AvoidSetjmpLongjmpCheck.h"10#include "clang/AST/ASTContext.h"11#include "clang/ASTMatchers/ASTMatchFinder.h"12#include "clang/Frontend/CompilerInstance.h"13#include "clang/Lex/PPCallbacks.h"14#include "clang/Lex/Preprocessor.h"15 16using namespace clang::ast_matchers;17 18namespace clang::tidy::modernize {19 20namespace {21const char DiagWording[] =22    "do not call %0; consider using exception handling instead";23 24class SetJmpMacroCallbacks : public PPCallbacks {25  AvoidSetjmpLongjmpCheck &Check;26 27public:28  explicit SetJmpMacroCallbacks(AvoidSetjmpLongjmpCheck &Check)29      : Check(Check) {}30 31  void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,32                    SourceRange Range, const MacroArgs *Args) override {33    const auto *II = MacroNameTok.getIdentifierInfo();34    if (!II)35      return;36 37    if (II->getName() == "setjmp")38      Check.diag(Range.getBegin(), DiagWording) << II;39  }40};41} // namespace42 43void AvoidSetjmpLongjmpCheck::registerPPCallbacks(44    const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {45  // Per [headers]p5, setjmp must be exposed as a macro instead of a function,46  // despite the allowance in C for setjmp to also be an extern function.47  PP->addPPCallbacks(std::make_unique<SetJmpMacroCallbacks>(*this));48}49 50void AvoidSetjmpLongjmpCheck::registerMatchers(MatchFinder *Finder) {51  // In case there is an implementation that happens to define setjmp as a52  // function instead of a macro, this will also catch use of it. However, we53  // are primarily searching for uses of longjmp.54  Finder->addMatcher(55      callExpr(callee(functionDecl(hasAnyName("setjmp", "longjmp"))))56          .bind("expr"),57      this);58}59 60void AvoidSetjmpLongjmpCheck::check(const MatchFinder::MatchResult &Result) {61  const auto *E = Result.Nodes.getNodeAs<CallExpr>("expr");62  diag(E->getExprLoc(), DiagWording) << cast<NamedDecl>(E->getCalleeDecl());63}64 65} // namespace clang::tidy::modernize66