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