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 "../utils/Matchers.h" 11 #include "clang/AST/ASTContext.h" 12 #include "clang/ASTMatchers/ASTMatchFinder.h" 13 14 using namespace clang::ast_matchers; 15 16 namespace clang { 17 namespace tidy { 18 namespace cert { 19 20 void StaticObjectExceptionCheck::registerMatchers(MatchFinder *Finder) { 21 // Match any static or thread_local variable declaration that has an 22 // initializer that can throw. 23 Finder->addMatcher( 24 varDecl(anyOf(hasThreadStorageDuration(), hasStaticStorageDuration()), 25 unless(anyOf(isConstexpr(), hasType(cxxRecordDecl(isLambda())), 26 hasAncestor(functionDecl()))), 27 anyOf(hasDescendant(cxxConstructExpr(hasDeclaration( 28 cxxConstructorDecl(unless(isNoThrow())).bind("func")))), 29 hasDescendant(cxxNewExpr(hasDeclaration( 30 functionDecl(unless(isNoThrow())).bind("func")))), 31 hasDescendant(callExpr(hasDeclaration( 32 functionDecl(unless(isNoThrow())).bind("func")))))) 33 .bind("var"), 34 this); 35 } 36 37 void StaticObjectExceptionCheck::check(const MatchFinder::MatchResult &Result) { 38 const auto *VD = Result.Nodes.getNodeAs<VarDecl>("var"); 39 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("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(FuncLocation, 49 "possibly throwing %select{constructor|function}0 declared here", 50 DiagnosticIDs::Note) 51 << (isa<CXXConstructorDecl>(Func) ? 0 : 1); 52 } 53 } 54 55 } // namespace cert 56 } // namespace tidy 57 } // namespace clang 58