| 1 | //===--- StaticObjectExceptionCheck.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 "StaticObjectExceptionCheck.h" |
| 10 | #include "clang/AST/ASTContext.h" |
| 11 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
| 12 | |
| 13 | using namespace clang::ast_matchers; |
| 14 | |
| 15 | namespace clang::tidy::cert { |
| 16 | |
| 17 | void StaticObjectExceptionCheck::registerMatchers(MatchFinder *Finder) { |
| 18 | // Match any static or thread_local variable declaration that has an |
| 19 | // initializer that can throw. |
| 20 | Finder->addMatcher( |
| 21 | NodeMatch: traverse( |
| 22 | TK: TK_AsIs, |
| 23 | InnerMatcher: varDecl( |
| 24 | anyOf(hasThreadStorageDuration(), hasStaticStorageDuration()), |
| 25 | unless(anyOf(isConstexpr(), hasType(InnerMatcher: cxxRecordDecl(isLambda())), |
| 26 | hasAncestor(functionDecl()))), |
| 27 | anyOf(hasDescendant(cxxConstructExpr(hasDeclaration( |
| 28 | InnerMatcher: cxxConstructorDecl(unless(isNoThrow())).bind(ID: "func" )))), |
| 29 | hasDescendant(cxxNewExpr(hasDeclaration( |
| 30 | InnerMatcher: functionDecl(unless(isNoThrow())).bind(ID: "func" )))), |
| 31 | hasDescendant(callExpr(hasDeclaration( |
| 32 | InnerMatcher: functionDecl(unless(isNoThrow())).bind(ID: "func" )))))) |
| 33 | .bind(ID: "var" )), |
| 34 | Action: this); |
| 35 | } |
| 36 | |
| 37 | void StaticObjectExceptionCheck::check(const MatchFinder::MatchResult &Result) { |
| 38 | const auto *VD = Result.Nodes.getNodeAs<VarDecl>(ID: "var" ); |
| 39 | const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>(ID: "func" ); |
| 40 | |
| 41 | diag(VD->getLocation(), |
| 42 | "initialization of %0 with %select{static|thread_local}1 storage " |
| 43 | "duration may throw an exception that cannot be caught" ) |
| 44 | << VD << (VD->getStorageDuration() == SD_Static ? 0 : 1); |
| 45 | |
| 46 | SourceLocation FuncLocation = Func->getLocation(); |
| 47 | if (FuncLocation.isValid()) { |
| 48 | diag(Loc: FuncLocation, |
| 49 | Description: "possibly throwing %select{constructor|function}0 declared here" , |
| 50 | Level: DiagnosticIDs::Note) |
| 51 | << (isa<CXXConstructorDecl>(Val: Func) ? 0 : 1); |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | } // namespace clang::tidy::cert |
| 56 | |