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 traverse( 25 TK_AsIs, 26 varDecl( 27 anyOf(hasThreadStorageDuration(), hasStaticStorageDuration()), 28 unless(anyOf(isConstexpr(), hasType(cxxRecordDecl(isLambda())), 29 hasAncestor(functionDecl()))), 30 anyOf(hasDescendant(cxxConstructExpr(hasDeclaration( 31 cxxConstructorDecl(unless(isNoThrow())).bind("func")))), 32 hasDescendant(cxxNewExpr(hasDeclaration( 33 functionDecl(unless(isNoThrow())).bind("func")))), 34 hasDescendant(callExpr(hasDeclaration( 35 functionDecl(unless(isNoThrow())).bind("func")))))) 36 .bind("var")), 37 this); 38 } 39 40 void StaticObjectExceptionCheck::check(const MatchFinder::MatchResult &Result) { 41 const auto *VD = Result.Nodes.getNodeAs<VarDecl>("var"); 42 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func"); 43 44 diag(VD->getLocation(), 45 "initialization of %0 with %select{static|thread_local}1 storage " 46 "duration may throw an exception that cannot be caught") 47 << VD << (VD->getStorageDuration() == SD_Static ? 0 : 1); 48 49 SourceLocation FuncLocation = Func->getLocation(); 50 if (FuncLocation.isValid()) { 51 diag(FuncLocation, 52 "possibly throwing %select{constructor|function}0 declared here", 53 DiagnosticIDs::Note) 54 << (isa<CXXConstructorDecl>(Func) ? 0 : 1); 55 } 56 } 57 58 } // namespace cert 59 } // namespace tidy 60 } // namespace clang 61