├── CMakeLists.txt ├── COPYING ├── EarlyExitTidyModule.cpp ├── EarlyExitTidyModule.h ├── ExportMainCheck.cpp ├── ExportMainCheck.h ├── InitListCheck.cpp ├── InitListCheck.h ├── LogPrintfCheck.cpp ├── LogPrintfCheck.h ├── NoADLCheck.cpp ├── NoADLCheck.h ├── README.md ├── bitcoin-tidy.cpp ├── early_exit.h ├── example.cc ├── example.h ├── example_adl.cc ├── example_exportmain.cc ├── example_init.cc ├── example_logprintf.cc └── preload.tidy /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.9) 2 | 3 | project(bitcoin-tidy-experiments VERSION 1.0.0 DESCRIPTION "Experimental clang-tidy checks for Bitcoin Core") 4 | 5 | include(GNUInstallDirs) 6 | 7 | set(CMAKE_CXX_STANDARD 17) 8 | set(CMAKE_CXX_STANDARD_REQUIRED True) 9 | set(CMAKE_CXX_EXTENSIONS False) 10 | 11 | add_compile_options(-fno-rtti) 12 | add_compile_options(-fno-exceptions) 13 | 14 | add_library(bitcoin-tidy-experiments SHARED bitcoin-tidy.cpp EarlyExitTidyModule.cpp ExportMainCheck.cpp InitListCheck.cpp LogPrintfCheck.cpp NoADLCheck.cpp) 15 | 16 | install(TARGETS bitcoin-tidy-experiments LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) 17 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Cory Fields 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /EarlyExitTidyModule.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | #include "EarlyExitTidyModule.h" 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | namespace { 12 | 13 | static llvm::StringRef get_source_text(clang::SourceRange range, const clang::SourceManager& sm, const clang::LangOptions& lo) { 14 | // Mostly from https://stackoverflow.com/questions/11083066/getting-the-source-behind-clangs-ast 15 | const auto& start_loc = sm.getSpellingLoc(range.getBegin()); 16 | const auto& last_token_loc = sm.getSpellingLoc(range.getEnd()); 17 | const auto& end_loc = clang::Lexer::getLocForEndOfToken(last_token_loc, 0, sm, lo); 18 | const auto& char_range = clang::CharSourceRange::getCharRange({start_loc, end_loc}); 19 | return clang::Lexer::getSourceText(char_range, sm, lo); 20 | } 21 | } // anonymous namespace 22 | 23 | namespace bitcoin { 24 | 25 | void PropagateEarlyExitCheck::registerMatchers(clang::ast_matchers::MatchFinder *Finder) { 26 | using namespace clang::ast_matchers; 27 | auto matchtype = qualType(hasDeclaration(classTemplateSpecializationDecl(hasName("MaybeEarlyExit")))); 28 | Finder->addMatcher( 29 | callExpr( 30 | anyOf(hasType(matchtype),callee(functionDecl(hasName("ShutdownRequested"))),callee(functionDecl(hasName("StartShutdown")))), 31 | forCallable(functionDecl( 32 | unless(isMain()), 33 | unless(returns(matchtype)), 34 | optionally(hasBody(compoundStmt(unless(hasAnySubstatement(returnStmt()))).bind("stmt_needs_return"))) 35 | ).bind("func_should_early_exit")) 36 | ).bind("early_exit_call") 37 | , this); 38 | 39 | 40 | // Match bare "return;" statements in a functions that should now 41 | // return MaybeEarlyExit. 42 | Finder->addMatcher( 43 | returnStmt( 44 | forCallable( 45 | functionDecl( 46 | hasDescendant( 47 | callExpr( 48 | anyOf(hasType(matchtype),callee(functionDecl(hasName("ShutdownRequested"))),callee(functionDecl(hasName("StartShutdown")))) 49 | )))), 50 | unless( 51 | has( 52 | expr()))).bind("naked_return"), this); 53 | 54 | Finder->addMatcher( 55 | ifStmt(hasCondition(expr( 56 | hasDescendant(callExpr(hasType(matchtype)).bind("if_call_expr")), 57 | unless(hasDescendant(unaryOperator(hasOperatorName("!"), hasDescendant(callExpr(hasType(matchtype)))))) 58 | )) 59 | ).bind("conditional_early_exit"), this); 60 | 61 | Finder->addMatcher( 62 | ifStmt(hasCondition( 63 | hasDescendant(unaryOperator(hasOperatorName("!"), hasDescendant(callExpr(hasType(matchtype)).bind("if_not_call_expr"))).bind("not_operator")) 64 | ) 65 | ).bind("conditional_not_early_exit"), this); 66 | 67 | Finder->addMatcher(traverse(clang::TK_IgnoreUnlessSpelledInSource, 68 | binaryOperation( 69 | isAssignmentOperator(), 70 | hasRHS(callExpr(hasType(matchtype)).bind("assign_call_expr")), 71 | hasLHS(expr().bind("lhs")) 72 | ).bind("early_exit_assignment")), this); 73 | 74 | Finder->addMatcher(traverse(clang::TK_IgnoreUnlessSpelledInSource, 75 | declStmt( 76 | unless(isExpandedFromMacro("MAYBE_EXIT")), 77 | unless(isExpandedFromMacro("EXIT_OR_DECL")), 78 | unless(isExpandedFromMacro("EXIT_OR_ASSIGN")), 79 | unless(isExpandedFromMacro("EXIT_OR_IF")), 80 | unless(isExpandedFromMacro("EXIT_OR_IF_NOT")), 81 | unless(isExpandedFromMacro("NOOP_EXIT_OR_DECL")), 82 | unless(isExpandedFromMacro("NOOP_EXIT_OR_ASSIGN")), 83 | unless(isExpandedFromMacro("NOOP_EXIT_OR_IF")), 84 | unless(isExpandedFromMacro("NOOP_EXIT_OR_IF_NOT")), 85 | unless(isExpandedFromMacro("NOOP_MAYBE_EXIT")), 86 | has(varDecl( 87 | hasInitializer(callExpr(hasType(matchtype)).bind("callsite"))).bind("vardecl") 88 | )) 89 | .bind("declstmt")), this); 90 | 91 | Finder->addMatcher(traverse(clang::TK_IgnoreUnlessSpelledInSource, 92 | callExpr(hasType(matchtype), 93 | unless(hasParent(returnStmt())), 94 | unless(isExpandedFromMacro("EXIT_OR_DECL")), 95 | unless(isExpandedFromMacro("EXIT_OR_ASSIGN")), 96 | unless(isExpandedFromMacro("EXIT_OR_IF")), 97 | unless(isExpandedFromMacro("EXIT_OR_IF_NOT")), 98 | unless(isExpandedFromMacro("MAYBE_EXIT")), 99 | unless(isExpandedFromMacro("NOOP_EXIT_OR_DECL")), 100 | unless(isExpandedFromMacro("NOOP_EXIT_OR_ASSIGN")), 101 | unless(isExpandedFromMacro("NOOP_EXIT_OR_IF")), 102 | unless(isExpandedFromMacro("NOOP_EXIT_OR_IF_NOT")), 103 | unless(isExpandedFromMacro("NOOP_MAYBE_EXIT")), 104 | unless(isExpandedFromMacro("BUBBLE_UP")) 105 | ).bind("unused_early_exit")), this); 106 | 107 | Finder->addMatcher(traverse(clang::TK_IgnoreUnlessSpelledInSource, 108 | returnStmt(has(callExpr(hasType(matchtype)).bind("bubble_up_expr")) 109 | )), this); 110 | 111 | } 112 | 113 | void PropagateEarlyExitCheck::check(const clang::ast_matchers::MatchFinder::MatchResult &Result) { 114 | static llvm::SmallSet g_decls; 115 | static llvm::SmallSet g_calls; 116 | 117 | const auto& sm = *Result.SourceManager; 118 | if (const auto *decl = Result.Nodes.getNodeAs("func_should_early_exit")) { 119 | if(!g_decls.insert(decl->getID()).second) { 120 | return; 121 | } 122 | auto user_diag = diag(decl->getBeginLoc(), "%0 should return MaybeEarlyExit.") << decl; 123 | recursiveChangeType(decl, user_diag); 124 | } 125 | if (const auto *body = Result.Nodes.getNodeAs("stmt_needs_return")) 126 | { 127 | auto user_diag = diag(body->getEndLoc(), " now needs return statement."); 128 | addReturn(body, user_diag, sm); 129 | } 130 | if (const auto* stmt = Result.Nodes.getNodeAs("naked_return")) 131 | { 132 | auto user_diag = diag(stmt->getBeginLoc(), "Should return something."); 133 | updateReturn(stmt, user_diag); 134 | } 135 | if (const auto* expr = Result.Nodes.getNodeAs("conditional_early_exit")) 136 | { 137 | if (const auto* callexpr = Result.Nodes.getNodeAs("if_call_expr")) { 138 | if(!g_calls.insert(callexpr->getID(*Result.Context)).second) { 139 | return; 140 | } 141 | } 142 | auto beginLoc = expr->getIfLoc(); 143 | auto endLoc = expr->getLParenLoc(); 144 | clang::SourceRange range = {beginLoc, endLoc}; 145 | const auto user_diag = diag(beginLoc, "Adding Macros"); 146 | user_diag << clang::FixItHint::CreateReplacement(range, "EXIT_OR_IF("); 147 | // TODO: Maybe filter more? 148 | // TODO: "if (early_exit_call() == foo)" -> "if (*early_exit_call() == foo)" 149 | // TODO: "auto foo = early_exit_call().bar" -> "auto foo = early_exit_call()->bar" 150 | } 151 | if (const auto* expr = Result.Nodes.getNodeAs("not_operator")) 152 | { 153 | auto beginLoc = expr->getOperatorLoc(); 154 | auto endLoc = expr->getExprLoc(); 155 | clang::SourceRange range = {beginLoc, endLoc}; 156 | const auto user_diag = diag(beginLoc, "Adding Macros"); 157 | user_diag << clang::FixItHint::CreateRemoval(range); 158 | } 159 | if (const auto* expr = Result.Nodes.getNodeAs("conditional_not_early_exit")) 160 | { 161 | if (const auto* callexpr = Result.Nodes.getNodeAs("if_not_call_expr")) { 162 | if(!g_calls.insert(callexpr->getID(*Result.Context)).second) { 163 | return; 164 | } 165 | } 166 | auto beginLoc = expr->getIfLoc(); 167 | auto endLoc = expr->getLParenLoc(); 168 | clang::SourceRange range = {beginLoc, endLoc}; 169 | const auto user_diag = diag(beginLoc, "Adding Macros"); 170 | user_diag << clang::FixItHint::CreateReplacement(range, "EXIT_OR_IF_NOT("); 171 | } 172 | 173 | if (const auto* bin = Result.Nodes.getNodeAs("early_exit_assignment")) 174 | { 175 | // TODO: de-dupe with binaryOperator 176 | if (const auto* callexpr = Result.Nodes.getNodeAs("assign_call_expr")) { 177 | if(!g_calls.insert(callexpr->getID(*Result.Context)).second) { 178 | return; 179 | } 180 | } 181 | const auto user_diag = diag(bin->getBeginLoc(), "Adding Macros"); 182 | user_diag << clang::FixItHint::CreateInsertion(bin->getBeginLoc(), "EXIT_OR_ASSIGN("); 183 | 184 | const auto& beginLoc = bin->getOperatorLoc(); 185 | const auto& endLoc = bin->getExprLoc(); 186 | clang::SourceRange range = {beginLoc, endLoc}; 187 | user_diag << clang::FixItHint::CreateReplacement(range, ","); 188 | 189 | user_diag << clang::FixItHint::CreateInsertion(bin->getEndLoc(), ")"); 190 | } 191 | 192 | if (const auto* bin = Result.Nodes.getNodeAs("early_exit_assignment")) 193 | { 194 | if (const auto* callexpr = Result.Nodes.getNodeAs("assign_call_expr")) { 195 | if(!g_calls.insert(callexpr->getID(*Result.Context)).second) { 196 | return; 197 | } 198 | } 199 | const auto user_diag = diag(bin->getBeginLoc(), "Adding Macros"); 200 | user_diag << clang::FixItHint::CreateInsertion(bin->getBeginLoc(), "EXIT_OR_ASSIGN("); 201 | 202 | const auto& beginLoc = bin->getOperatorLoc(); 203 | const auto& endLoc = bin->getExprLoc(); 204 | clang::SourceRange range = {beginLoc, endLoc}; 205 | user_diag << clang::FixItHint::CreateReplacement(range, ","); 206 | 207 | user_diag << clang::FixItHint::CreateInsertion(bin->getEndLoc(), ")"); 208 | } 209 | 210 | if (const auto* decl = Result.Nodes.getNodeAs("declstmt")) 211 | { 212 | if (const auto* var = Result.Nodes.getNodeAs("vardecl")) { 213 | const auto user_diag = diag(decl->getBeginLoc(), "Adding Macros"); 214 | 215 | clang::SourceRange typerange; 216 | if (const auto* expr = Result.Nodes.getNodeAs("callsite")) { 217 | if(!g_calls.insert(expr->getID(*Result.Context)).second) { 218 | return; 219 | } 220 | typerange = {expr->getBeginLoc(), expr->getEndLoc()}; 221 | } 222 | 223 | std::string result = "EXIT_OR_DECL("; 224 | const auto& ctx = var->getASTContext(); 225 | const auto& opts = ctx.getLangOpts(); 226 | clang::SourceRange varrange = {var->getBeginLoc(), var->getTypeSpecEndLoc()}; 227 | result += get_source_text(varrange, sm, opts); 228 | result += " "; 229 | result += var->getQualifiedNameAsString(); 230 | result += ", "; 231 | result += get_source_text(typerange, sm, opts); 232 | result += ");"; 233 | user_diag << clang::FixItHint::CreateReplacement(decl->getSourceRange(), result); 234 | } 235 | } 236 | 237 | if (const auto* expr = Result.Nodes.getNodeAs("unused_early_exit")) 238 | { 239 | if(!g_calls.insert(expr->getID(*Result.Context)).second) { 240 | return; 241 | } 242 | const auto user_diag = diag(expr->getBeginLoc(), "Adding Macros"); 243 | user_diag << clang::FixItHint::CreateInsertion(expr->getBeginLoc(), "MAYBE_EXIT("); 244 | user_diag << clang::FixItHint::CreateInsertion(expr->getEndLoc(), ")"); 245 | } 246 | 247 | if (const auto* expr = Result.Nodes.getNodeAs("bubble_up_expr")) { 248 | if(!g_calls.insert(expr->getID(*Result.Context)).second) { 249 | return; 250 | } 251 | const auto user_diag = diag(expr->getBeginLoc(), "Adding Macros"); 252 | user_diag << clang::FixItHint::CreateInsertion(expr->getBeginLoc(), "BUBBLE_UP("); 253 | user_diag << clang::FixItHint::CreateInsertion(expr->getEndLoc(), ")"); 254 | } 255 | } 256 | 257 | void PropagateEarlyExitCheck::recursiveChangeType(const clang::FunctionDecl* decl, clang::DiagnosticBuilder& user_diag) 258 | { 259 | const auto& ctx = decl->getASTContext(); 260 | const auto& opts = ctx.getLangOpts(); 261 | clang::PrintingPolicy Policy(opts); 262 | auto rettype = decl->getDeclaredReturnType(); 263 | 264 | std::string retstring; 265 | if (!rettype->isVoidType()) { 266 | retstring = rettype.getAsString(Policy); 267 | } 268 | 269 | auto loc = decl->getBeginLoc(); 270 | if (loc.isMacroID()) { 271 | return; 272 | } 273 | 274 | for (const auto& redecl : decl->redecls()) 275 | { 276 | const auto& return_loc = redecl->getTypeSourceInfo()->getTypeLoc().getAs().getReturnLoc(); 277 | clang::SourceRange return_range{return_loc.getBeginLoc(), return_loc.getEndLoc()}; 278 | if (return_range.isInvalid()) { 279 | continue; 280 | } 281 | user_diag << clang::FixItHint::CreateReplacement(return_range, (llvm::Twine("MaybeEarlyExit<") + retstring + ">").str()); 282 | } 283 | return; 284 | } 285 | 286 | void PropagateEarlyExitCheck::addReturn(const clang::Stmt* body, clang::DiagnosticBuilder& user_diag, const clang::SourceManager &sm) 287 | { 288 | const clang::Stmt* laststmt; 289 | // Attempt to align the return to the column of the previous statement 290 | for (auto child = body->child_begin(); child != body->child_end(); child++) 291 | { 292 | laststmt = *child; 293 | } 294 | const auto& prevbegin = laststmt->getBeginLoc(); 295 | auto indentlevel = sm.getPresumedColumnNumber(prevbegin) - 1; 296 | 297 | user_diag << clang::FixItHint::CreateInsertion(body->getEndLoc(), std::string(indentlevel, ' ') + "return {};\n"); 298 | } 299 | 300 | void PropagateEarlyExitCheck::updateReturn(const clang::ReturnStmt* stmt, clang::DiagnosticBuilder& user_diag) 301 | { 302 | user_diag << clang::FixItHint::CreateReplacement(stmt->getReturnLoc(), "return {}"); 303 | } 304 | 305 | } // namespace 306 | -------------------------------------------------------------------------------- /EarlyExitTidyModule.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | #ifndef EARLY_EXIT_TIDY_MODULE_H 6 | #define EARLY_EXIT_TIDY_MODULE_H 7 | 8 | #include 9 | 10 | namespace bitcoin { 11 | 12 | class PropagateEarlyExitCheck final : public clang::tidy::ClangTidyCheck { 13 | 14 | public: 15 | PropagateEarlyExitCheck(clang::StringRef Name, clang::tidy::ClangTidyContext *Context) 16 | : clang::tidy::ClangTidyCheck(Name, Context) {} 17 | 18 | bool isLanguageVersionSupported(const clang::LangOptions &LangOpts) const override { 19 | return LangOpts.CPlusPlus; 20 | } 21 | void registerMatchers(clang::ast_matchers::MatchFinder *Finder) override; 22 | void check(const clang::ast_matchers::MatchFinder::MatchResult &Result) override; 23 | private: 24 | void recursiveChangeType(const clang::FunctionDecl*, clang::DiagnosticBuilder&); 25 | void addReturn(const clang::Stmt*, clang::DiagnosticBuilder&, const clang::SourceManager&); 26 | void updateReturn(const clang::ReturnStmt*, clang::DiagnosticBuilder&); 27 | }; 28 | 29 | } // namespace bitcoin 30 | 31 | #endif // EARLY_EXIT_TIDY_MODULE_H 32 | -------------------------------------------------------------------------------- /ExportMainCheck.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | #include "ExportMainCheck.h" 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | #include 12 | 13 | namespace { 14 | } // namespace 15 | 16 | namespace bitcoin { 17 | 18 | void ExportMainCheck::registerMatchers(clang::ast_matchers::MatchFinder *finder) 19 | { 20 | using namespace clang::ast_matchers; 21 | finder->addMatcher( 22 | functionDecl(isMain()).bind("mainfunc") 23 | , this); 24 | } 25 | 26 | void ExportMainCheck::check(const clang::ast_matchers::MatchFinder::MatchResult &Result) 27 | { 28 | const auto* lit = Result.Nodes.getNodeAs("mainfunc"); 29 | if (!lit) return; 30 | const auto& ctx = *Result.Context; 31 | 32 | // This does not seem to work as expected 33 | // if (!ctx.getTargetInfo().getCXXABI().isMicrosoft()) return; 34 | 35 | // This one does 36 | if (!ctx.getTargetInfo().getTriple().isOSWindows()) return; 37 | 38 | if (lit->hasAttr()) return; 39 | if (lit->hasAttr()) return; 40 | const auto user_diag = diag(lit->getBeginLoc(), "Un-exported main function"); 41 | } 42 | 43 | } // namespace bitcoin 44 | -------------------------------------------------------------------------------- /ExportMainCheck.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | #ifndef EXPORT_MAIN_CHECK_H 6 | #define EXPORT_MAIN_CHECK_H 7 | 8 | #include 9 | 10 | namespace bitcoin { 11 | 12 | class ExportMainCheck final : public clang::tidy::ClangTidyCheck { 13 | 14 | public: 15 | ExportMainCheck(clang::StringRef Name, clang::tidy::ClangTidyContext *Context) 16 | : clang::tidy::ClangTidyCheck(Name, Context) {} 17 | 18 | bool isLanguageVersionSupported(const clang::LangOptions &LangOpts) const override { 19 | return LangOpts.CPlusPlus; 20 | } 21 | void registerMatchers(clang::ast_matchers::MatchFinder *Finder) override; 22 | void check(const clang::ast_matchers::MatchFinder::MatchResult &Result) override; 23 | }; 24 | 25 | } // namespace bitcoin 26 | 27 | #endif // EXPORT_MAIN_CHECK_H 28 | -------------------------------------------------------------------------------- /InitListCheck.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | #include "InitListCheck.h" 6 | 7 | #include 8 | #include 9 | 10 | 11 | namespace { 12 | } // namespace 13 | 14 | namespace bitcoin { 15 | 16 | void InitListCheck::registerMatchers(clang::ast_matchers::MatchFinder *finder) 17 | { 18 | using namespace clang::ast_matchers; 19 | finder->addMatcher( 20 | implicitValueInitExpr( 21 | hasParent( 22 | initListExpr(has(designatedInitExpr())).bind("initlist")) 23 | ).bind("implicitval") 24 | , this); 25 | } 26 | 27 | void InitListCheck::check(const clang::ast_matchers::MatchFinder::MatchResult &Result) 28 | { 29 | std::string membertype; 30 | if (const auto* member = Result.Nodes.getNodeAs("implicitval")) { 31 | membertype = member->getType().getAsString(); 32 | } 33 | if (const auto* init = Result.Nodes.getNodeAs("initlist")) { 34 | diag(init->getBeginLoc(), "Designated initializer with uninitialized member of type: " + membertype); 35 | } 36 | } 37 | 38 | } // namespace bitcoin 39 | -------------------------------------------------------------------------------- /InitListCheck.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | #ifndef INITLIST_CHECK_H 6 | #define INITLIST_CHECK_H 7 | 8 | #include 9 | 10 | namespace bitcoin { 11 | 12 | class InitListCheck final : public clang::tidy::ClangTidyCheck { 13 | 14 | public: 15 | InitListCheck(clang::StringRef Name, clang::tidy::ClangTidyContext *Context) 16 | : clang::tidy::ClangTidyCheck(Name, Context) {} 17 | 18 | bool isLanguageVersionSupported(const clang::LangOptions &LangOpts) const override { 19 | return LangOpts.CPlusPlus; 20 | } 21 | void registerMatchers(clang::ast_matchers::MatchFinder *Finder) override; 22 | void check(const clang::ast_matchers::MatchFinder::MatchResult &Result) override; 23 | }; 24 | 25 | } // namespace bitcoin 26 | 27 | #endif // NOADL_CHECK_H 28 | -------------------------------------------------------------------------------- /LogPrintfCheck.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | #include "LogPrintfCheck.h" 6 | 7 | #include 8 | #include 9 | 10 | 11 | namespace { 12 | AST_MATCHER(clang::StringLiteral, unterminated) { 13 | size_t len = Node.getLength(); 14 | if(len == 0) { 15 | return false; 16 | } 17 | if(Node.getCodeUnit(len-1) == '\n') { 18 | return false; 19 | } 20 | if (len > 2 && 21 | Node.getCodeUnit(len-1) == '.' && 22 | Node.getCodeUnit(len-2) == '.' && 23 | Node.getCodeUnit(len-3) == '.') 24 | { 25 | return false; 26 | } 27 | return true; 28 | } 29 | } // namespace 30 | 31 | namespace bitcoin { 32 | 33 | void LogPrintfCheck::registerMatchers(clang::ast_matchers::MatchFinder *finder) 34 | { 35 | using namespace clang::ast_matchers; 36 | finder->addMatcher( 37 | callExpr( 38 | callee(functionDecl(hasName("LogPrintf_"))), 39 | hasArgument(5, stringLiteral(unterminated()).bind("logstring")) 40 | ).bind("logprintf"), 41 | this); 42 | } 43 | 44 | void LogPrintfCheck::check(const clang::ast_matchers::MatchFinder::MatchResult &Result) 45 | { 46 | if (const auto* lit = Result.Nodes.getNodeAs("logstring")) { 47 | const auto& ctx = *Result.Context; 48 | const auto user_diag = diag(lit->getEndLoc(), "Unterminated LogPrintf"); 49 | auto len = lit->getByteLength(); 50 | const auto& loc = lit->getLocationOfByte(len, *Result.SourceManager, ctx.getLangOpts(), ctx.getTargetInfo()); 51 | user_diag << clang::FixItHint::CreateInsertion(loc, "\\n"); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /LogPrintfCheck.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | #ifndef LOGPRINTF_CHECK_H 6 | #define LOGPRINTF_CHECK_H 7 | 8 | #include 9 | 10 | namespace bitcoin { 11 | 12 | class LogPrintfCheck final : public clang::tidy::ClangTidyCheck { 13 | 14 | public: 15 | LogPrintfCheck(clang::StringRef Name, clang::tidy::ClangTidyContext *Context) 16 | : clang::tidy::ClangTidyCheck(Name, Context) {} 17 | 18 | bool isLanguageVersionSupported(const clang::LangOptions &LangOpts) const override { 19 | return LangOpts.CPlusPlus; 20 | } 21 | void registerMatchers(clang::ast_matchers::MatchFinder *Finder) override; 22 | void check(const clang::ast_matchers::MatchFinder::MatchResult &Result) override; 23 | }; 24 | 25 | } // namespace bitcoin 26 | 27 | #endif // LOGPRINTF_CHECK_H 28 | -------------------------------------------------------------------------------- /NoADLCheck.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | #include "NoADLCheck.h" 6 | 7 | #include 8 | #include 9 | 10 | 11 | namespace { 12 | } // namespace 13 | 14 | namespace bitcoin { 15 | 16 | void NoADLCheck::registerMatchers(clang::ast_matchers::MatchFinder *finder) 17 | { 18 | using namespace clang::ast_matchers; 19 | finder->addMatcher( 20 | callExpr(usesADL()).bind("adlexpr") 21 | , this); 22 | } 23 | 24 | void NoADLCheck::check(const clang::ast_matchers::MatchFinder::MatchResult &Result) 25 | { 26 | if (const auto* lit = Result.Nodes.getNodeAs("adlexpr")) { 27 | const auto& ctx = *Result.Context; 28 | diag(lit->getEndLoc(), "Use of ADL"); 29 | } 30 | } 31 | 32 | } // namespace bitcoin 33 | -------------------------------------------------------------------------------- /NoADLCheck.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | #ifndef NOADL_CHECK_H 6 | #define NOADL_CHECK_H 7 | 8 | #include 9 | 10 | namespace bitcoin { 11 | 12 | class NoADLCheck final : public clang::tidy::ClangTidyCheck { 13 | 14 | public: 15 | NoADLCheck(clang::StringRef Name, clang::tidy::ClangTidyContext *Context) 16 | : clang::tidy::ClangTidyCheck(Name, Context) {} 17 | 18 | bool isLanguageVersionSupported(const clang::LangOptions &LangOpts) const override { 19 | return LangOpts.CPlusPlus; 20 | } 21 | void registerMatchers(clang::ast_matchers::MatchFinder *Finder) override; 22 | void check(const clang::ast_matchers::MatchFinder::MatchResult &Result) override; 23 | }; 24 | 25 | } // namespace bitcoin 26 | 27 | #endif // NOADL_CHECK_H 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Hacking on a clang-tidy plugin for Bitcoin Core 2 | 3 | This started with the propagate-early-exit check/fix as a way to transform 4 | Core's shutdown code, but a few other checks have been added as well. This is 5 | a catch-all repo for hacking until we decide to do something with these checks. 6 | 7 | ### Dependencies: 8 | llvm 14+ headers and clang-tidy 14+ are required, but libs are not. 9 | 10 | To install them, build llvm with clang-tools-extra enabled, and: 11 | `make install-llvm-headers install-clang-tidy-headers install-clang-headers-stripped` 12 | 13 | ### Building the plugin: 14 | - mkdir build 15 | - cd build 16 | - cmake .. 17 | - make 18 | 19 | ### Using the plugin: 20 | 21 | Example propagate-early-exit usage: 22 | 23 | ``clang-tidy --load=`pwd`/libbitcoin-tidy-experiments.so -checks='-*,bitcoin-propagate-early-exit' -fix ../example.cc -- -std=c++17`` 24 | 25 | ``` 26 | 25 warnings generated. 27 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:18:5: warning: Adding Macros [bitcoin-propagate-early-exit] 28 | auto foo = maybe_early_exit(); 29 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 30 | EXIT_OR_DECL(auto foo, maybe_early_exit()); 31 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:18:5: note: FIX-IT applied suggested code changes 32 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:19:5: warning: Adding Macros [bitcoin-propagate-early-exit] 33 | auto bar = maybe_early_exit(); 34 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 35 | EXIT_OR_DECL(auto bar, maybe_early_exit()); 36 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:19:5: note: FIX-IT applied suggested code changes 37 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:25:1: warning: 'caller2' should return MaybeEarlyExit. [bitcoin-propagate-early-exit] 38 | void caller2() // should warn for not returning MaybeEarlyExit. 39 | ^~~~ 40 | MaybeEarlyExit<> 41 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:23:1: note: FIX-IT applied suggested code changes 42 | void caller2(); 43 | ^ 44 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:24:19: note: FIX-IT applied suggested code changes 45 | auto caller2() -> void; 46 | ^ 47 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:25:1: note: FIX-IT applied suggested code changes 48 | void caller2() // should warn for not returning MaybeEarlyExit. 49 | ^ 50 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.h:10:1: note: FIX-IT applied suggested code changes 51 | void caller2(); 52 | ^ 53 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:27:5: warning: Adding Macros [bitcoin-propagate-early-exit] 54 | auto foo(maybe_early_exit()); 55 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 56 | EXIT_OR_DECL(auto foo, maybe_early_exit()); 57 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:27:5: note: FIX-IT applied suggested code changes 58 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:28:5: warning: Adding Macros [bitcoin-propagate-early-exit] 59 | const auto& bar = maybe_early_exit(); 60 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 61 | EXIT_OR_DECL(const auto& bar, maybe_early_exit()); 62 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:28:5: note: FIX-IT applied suggested code changes 63 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:30:5: warning: Adding Macros [bitcoin-propagate-early-exit] 64 | castret = maybe_early_exit(); 65 | ^ ~ 66 | EXIT_OR_ASSIGN( , ) 67 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:30:5: note: FIX-IT applied suggested code changes 68 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:30:13: note: FIX-IT applied suggested code changes 69 | castret = maybe_early_exit(); 70 | ^ 71 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:30:32: note: FIX-IT applied suggested code changes 72 | castret = maybe_early_exit(); 73 | ^ 74 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:31:5: warning: Should return something. [bitcoin-propagate-early-exit] 75 | return; // should rewrite as "return {};". 76 | ^~~~~~ 77 | return {} 78 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:31:5: note: FIX-IT applied suggested code changes 79 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:34:1: warning: 'caller3' should return MaybeEarlyExit. [bitcoin-propagate-early-exit] 80 | void caller3() // should warn for not returning MaybeEarlyExit. 81 | ^~~~ 82 | MaybeEarlyExit<> 83 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:34:1: note: FIX-IT applied suggested code changes 84 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:36:5: warning: Adding Macros [bitcoin-propagate-early-exit] 85 | auto foo = maybe_early_exit(); 86 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 87 | EXIT_OR_DECL(auto foo, maybe_early_exit()); 88 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:36:5: note: FIX-IT applied suggested code changes 89 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:37:5: warning: Adding Macros [bitcoin-propagate-early-exit] 90 | if (maybe_early_exit()) { 91 | ^~~~ 92 | EXIT_OR_IF( 93 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:37:5: note: FIX-IT applied suggested code changes 94 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:38:9: warning: Should return something. [bitcoin-propagate-early-exit] 95 | return; // should rewrite as "return {};" 96 | ^~~~~~ 97 | return {} 98 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:38:9: note: FIX-IT applied suggested code changes 99 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:40:5: warning: Adding Macros [bitcoin-propagate-early-exit] 100 | if (!maybe_early_exit()) { 101 | ^~~~ 102 | EXIT_OR_IF_NOT( 103 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:40:5: note: FIX-IT applied suggested code changes 104 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:40:9: warning: Adding Macros [bitcoin-propagate-early-exit] 105 | if (!maybe_early_exit()) { 106 | ^ 107 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:40:9: note: FIX-IT applied suggested code changes 108 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:41:9: warning: Should return something. [bitcoin-propagate-early-exit] 109 | return; // should rewrite as "return {};" 110 | ^~~~~~ 111 | return {} 112 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:41:9: note: FIX-IT applied suggested code changes 113 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:47:1: warning: now needs return statement. [bitcoin-propagate-early-exit] 114 | } 115 | ^ 116 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:47:1: note: FIX-IT applied suggested code changes 117 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:54:1: warning: 'caller4' should return MaybeEarlyExit. [bitcoin-propagate-early-exit] 118 | void caller4() 119 | ^~~~ 120 | MaybeEarlyExit<> 121 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:54:1: note: FIX-IT applied suggested code changes 122 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:58:5: warning: Adding Macros [bitcoin-propagate-early-exit] 123 | const auto& foo = fpointer(1); 124 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 125 | EXIT_OR_DECL(const auto& foo, fpointer(1)); 126 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:58:5: note: FIX-IT applied suggested code changes 127 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:59:1: warning: now needs return statement. [bitcoin-propagate-early-exit] 128 | } 129 | ^ 130 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:59:1: note: FIX-IT applied suggested code changes 131 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:60:1: warning: 'caller5' should return MaybeEarlyExit. [bitcoin-propagate-early-exit] 132 | void caller5() 133 | ^~~~ 134 | MaybeEarlyExit<> 135 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:60:1: note: FIX-IT applied suggested code changes 136 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:62:5: warning: Adding Macros [bitcoin-propagate-early-exit] 137 | maybe_early_exit(); 138 | ^ 139 | MAYBE_EXIT( ) 140 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:62:5: note: FIX-IT applied suggested code changes 141 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:62:22: note: FIX-IT applied suggested code changes 142 | maybe_early_exit(); 143 | ^ 144 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:63:1: warning: now needs return statement. [bitcoin-propagate-early-exit] 145 | } 146 | ^ 147 | /home/cory/dev/bitcoin-tidy-experiments/build/../example.cc:63:1: note: FIX-IT applied suggested code changes 148 | clang-tidy applied 27 of 27 suggested fixes. 149 | Suppressed 4 warnings (4 with check filters). 150 | ``` 151 | 152 | ### Caveats: 153 | 154 | The clang/clang-tidy libs are not ABI safe, so the clang-tidy runtime version 155 | must be the same as the headers used to build the plugin. 156 | -------------------------------------------------------------------------------- /bitcoin-tidy.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | #include "EarlyExitTidyModule.h" 6 | #include "ExportMainCheck.h" 7 | #include "InitListCheck.h" 8 | #include "LogPrintfCheck.h" 9 | #include "NoADLCheck.h" 10 | 11 | #include 12 | #include 13 | 14 | class BitcoinModule final : public clang::tidy::ClangTidyModule { 15 | public: 16 | void addCheckFactories(clang::tidy::ClangTidyCheckFactories &CheckFactories) override { 17 | CheckFactories.registerCheck("bitcoin-propagate-early-exit"); 18 | CheckFactories.registerCheck("bitcoin-unterminated-logprintf"); 19 | CheckFactories.registerCheck("bitcoin-adl-use"); 20 | CheckFactories.registerCheck("bitcoin-export-main"); 21 | CheckFactories.registerCheck("bitcoin-init-list"); 22 | } 23 | }; 24 | 25 | static clang::tidy::ClangTidyModuleRegistry::Add 26 | X("bitcoin-module", "Adds bitcoin checks."); 27 | 28 | volatile int PropagateEarlyExitCheckAnchorSource = 0; 29 | -------------------------------------------------------------------------------- /early_exit.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2009-2022 The Bitcoin Core developers 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | #ifndef BITCOIN_EARLY_EXIT_H 6 | #define BITCOIN_EARLY_EXIT_H 7 | 8 | #include 9 | #include 10 | 11 | enum class FatalError 12 | { 13 | UNKNOWN, 14 | BLOCK_DISCONNECT_ERROR, 15 | BLOCK_MUTATED, 16 | BLOCK_FLUSH_FAILED, 17 | BLOCK_READ_FAILED, 18 | BLOCK_READ_CORRUPT, 19 | BLOCK_WRITE_FAILED, 20 | BLOCK_INDEX_WRITE_FAILED, 21 | COINSDB_WRITE_FAILED, 22 | DISK_SPACE_ERROR, 23 | FLUSH_SYSTEM_ERROR, 24 | UNDO_FLUSH_FAILED, 25 | UNDO_WRITE_FAILED 26 | }; 27 | 28 | enum class VoidType{}; 29 | 30 | enum class UserInterrupted 31 | { 32 | UNKNOWN, 33 | BLOCK_IMPORT_COMPLETE, 34 | }; 35 | 36 | using EarlyExit = std::variant; 37 | 38 | template 39 | class MaybeEarlyExit; 40 | 41 | template 42 | EarlyExit BubbleUp(MaybeEarlyExit&& ret); 43 | 44 | template 45 | class [[nodiscard]] MaybeEarlyExit : std::variant 46 | { 47 | EarlyExit Bubble() const && 48 | { 49 | if (std::holds_alternative(*this)) { 50 | return std::get(*this); 51 | } else if (std::holds_alternative(*this)) { 52 | return std::get(*this); 53 | } else { 54 | return FatalError::UNKNOWN; 55 | } 56 | } 57 | friend EarlyExit BubbleUp(MaybeEarlyExit&&); 58 | 59 | public: 60 | using underlying = std::variant; 61 | using std::variant::variant; 62 | 63 | // No copying or moving, only bubbling up. 64 | MaybeEarlyExit& operator=(const MaybeEarlyExit&) = delete; 65 | MaybeEarlyExit(const MaybeEarlyExit&) = delete; 66 | MaybeEarlyExit& operator=(MaybeEarlyExit&&) = delete; 67 | MaybeEarlyExit(MaybeEarlyExit&&) = delete; 68 | 69 | // Set to FatalError by default so this works even when T can't be default-constructed 70 | MaybeEarlyExit(EarlyExit err) : std::variant(FatalError::UNKNOWN) 71 | { 72 | if (std::holds_alternative(err)) { 73 | underlying::template emplace(std::get(err)); 74 | } else if (std::holds_alternative(err)) { 75 | underlying::template emplace(std::get(err)); 76 | } 77 | } 78 | 79 | bool ShouldEarlyExit() const 80 | { 81 | return !std::holds_alternative(*this); 82 | } 83 | 84 | const T& operator*() const { 85 | assert(!ShouldEarlyExit()); 86 | return std::get(*this); 87 | } 88 | 89 | T& operator*() { 90 | assert(!ShouldEarlyExit()); 91 | return std::get(*this); 92 | } 93 | 94 | // Only intended for use by top-level callers to report errors 95 | EarlyExit GetEarlyExit() const 96 | { 97 | if (std::holds_alternative(*this)) { 98 | return std::get(*this); 99 | } 100 | if (std::holds_alternative(*this)) { 101 | return std::get(*this); 102 | } 103 | return std::monostate{}; 104 | } 105 | 106 | // Semantics similar to std::map::try_emplace 107 | // Only moves the value out if it exists, otherwise assume the caller 108 | // will bubble it up. 109 | bool TryMoveOut(T& val) const 110 | { 111 | if (ShouldEarlyExit()) { 112 | return false; 113 | } 114 | val = std::move(std::get(*this)); 115 | return true; 116 | } 117 | 118 | // To remove after transform 119 | [[deprecated]] operator T() const 120 | { 121 | assert(!ShouldEarlyExit()); 122 | return std::get(*this); 123 | } 124 | }; 125 | 126 | // User function to walk up the call-stack 127 | template 128 | EarlyExit BubbleUp(MaybeEarlyExit&& ret) 129 | { 130 | return std::move(ret).Bubble(); 131 | } 132 | 133 | #ifndef PASTE 134 | #define PASTE(x, y) x ## y 135 | #endif 136 | #ifndef PASTE2 137 | #define PASTE2(x, y) PASTE(x, y) 138 | #endif 139 | 140 | #define BUBBLE_UP(func) BubbleUp(func) 141 | #define MAYBE_EXIT(func) if(auto tmp_int_ret = func; tmp_int_ret.ShouldEarlyExit()) return BubbleUp(std::move(tmp_int_ret)); 142 | #define EXIT_OR_ASSIGN(ret_val, func) if (auto tmp_int_ret = func; !tmp_int_ret.TryMoveOut(ret_val)) return BubbleUp(std::move(tmp_int_ret)); 143 | #define EXIT_OR_IF(func) if(auto tmp_int_ret = func; tmp_int_ret.ShouldEarlyExit()) return BubbleUp(std::move(tmp_int_ret)); else if (*tmp_int_ret) 144 | #define EXIT_OR_IF_NOT(func) if(auto tmp_int_ret = func; tmp_int_ret.ShouldEarlyExit()) return BubbleUp(std::move(tmp_int_ret)); else if (!*tmp_int_ret) 145 | // Because the temporary here cannot be scoped like the others, make it per-line unique 146 | // __COUNTER__ could potentially be used instead, but it's non-standard and confuses LTO. 147 | #define EXIT_OR_DECL(ret_val, func) auto PASTE2(tmp_int_ret, __LINE__) = func; if(PASTE2(tmp_int_ret, __LINE__).ShouldEarlyExit()) return BubbleUp(std::move(PASTE2(tmp_int_ret, __LINE__))); ret_val = std::move(*PASTE2(tmp_int_ret, __LINE__)); 148 | 149 | 150 | // NOOP versions of the same macros for temporarily catching in top-level functions 151 | #define NOOP_MAYBE_EXIT(func) if ([[maybe_unused]] auto tmp_int_ret = func; true) ; 152 | #define NOOP_EXIT_OR_ASSIGN(ret_val, func) ret_val = *func; 153 | #define NOOP_EXIT_OR_IF(func) if(auto tmp_int_ret = func; *tmp_int_ret) 154 | #define NOOP_EXIT_OR_IF_NOT(func) if(auto tmp_int_ret = func; !*tmp_int_ret) 155 | #define NOOP_EXIT_OR_DECL(ret_val, func) ret_val = *func 156 | 157 | #endif // BITCOIN_EARLY_EXIT_H 158 | -------------------------------------------------------------------------------- /example.cc: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | // Warn about any function that calls into another function that returns 6 | // an MaybeEarlyExit. The intention is to force _any_ returned MaybeEarlyExit to 7 | // bubble all the way back up to main. Like manual exception catch/rethrowing. 8 | 9 | #include "example.h" 10 | 11 | MaybeEarlyExit maybe_early_exit() 12 | { 13 | return {}; 14 | } 15 | 16 | MaybeEarlyExit<> caller() 17 | { 18 | auto foo = maybe_early_exit(); 19 | 20 | struct quickstruct { 21 | int m_val{0}; 22 | }; 23 | quickstruct tempstruct; 24 | tempstruct.m_val = maybe_early_exit(); 25 | return {}; 26 | } 27 | 28 | struct Object 29 | { 30 | }; 31 | 32 | MaybeEarlyExit ObjectCaller() 33 | { 34 | Object object{}; 35 | return object; 36 | }; 37 | 38 | void caller2(); 39 | auto caller2() -> void; 40 | void caller2() // should warn for not returning MaybeEarlyExit. 41 | { 42 | auto foo(maybe_early_exit()); 43 | const auto& bar = maybe_early_exit(); 44 | int castret{0}; 45 | castret = maybe_early_exit(); 46 | return; // should rewrite as "return {};". 47 | } 48 | 49 | void caller3() // should warn for not returning MaybeEarlyExit. 50 | { 51 | auto foo = maybe_early_exit(); 52 | if (maybe_early_exit()) { 53 | return; // should rewrite as "return {};" 54 | } 55 | if (!maybe_early_exit()) { 56 | return; // should rewrite as "return {};" 57 | } 58 | if (true) { 59 | maybe_early_exit(); 60 | } 61 | if (true) maybe_early_exit(); 62 | 63 | class fooclass{ 64 | void myfunc() { return; } 65 | }; 66 | // Should add "return {};" 67 | } 68 | 69 | MaybeEarlyExit<> func(int arg) 70 | { 71 | return {}; 72 | } 73 | 74 | void caller4() 75 | { 76 | using functype = MaybeEarlyExit<>(*)(int); 77 | functype fpointer = func; 78 | const auto& foo = fpointer(1); 79 | } 80 | void caller5() 81 | { 82 | maybe_early_exit(); 83 | } 84 | 85 | void caller6() 86 | { 87 | Object object{}; 88 | object = ObjectCaller(); 89 | } 90 | 91 | int caller7() 92 | { 93 | return maybe_early_exit(); 94 | } 95 | -------------------------------------------------------------------------------- /example.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | #ifndef PROPAGATE_EARLY_EXIT_H 6 | #define PROPAGATE_EARLY_EXIT_H 7 | 8 | #include "early_exit.h" 9 | 10 | void caller2(); 11 | 12 | #endif // PROPAGATE_EARLY_EXIT_H 13 | -------------------------------------------------------------------------------- /example_adl.cc: -------------------------------------------------------------------------------- 1 | namespace NS { 2 | struct X {}; 3 | void y(X); 4 | } 5 | 6 | void y(...); 7 | 8 | void test() { 9 | NS::X x; 10 | y(x); // Matches 11 | NS::y(x); // Doesn't match 12 | y(42); // Doesn't match 13 | using NS::y; 14 | y(x); // Found by both unqualified lookup and ADL, doesn't match 15 | } 16 | -------------------------------------------------------------------------------- /example_exportmain.cc: -------------------------------------------------------------------------------- 1 | #if TEST_DECLSPEC 2 | #define EXPORT_ATTR __declspec(dllexport) 3 | #elif TEST_VISIBLE 4 | #define EXPORT_ATTR __attribute__ ((visibility ("default"))) 5 | #else 6 | #define EXPORT_ATTR 7 | #endif 8 | 9 | EXPORT_ATTR int main(int argc, char* argv[]){} 10 | 11 | -------------------------------------------------------------------------------- /example_init.cc: -------------------------------------------------------------------------------- 1 | struct A { 2 | struct Options { 3 | unsigned cache_size; 4 | signed delta; 5 | bool in_memory = false; 6 | }; 7 | A(const Options&) {} // unsafe (may have fields uninitialized) 8 | A(unsigned cache_size, signed delta, bool in_memory = false) {} // safe, all non-default args are initialized 9 | }; 10 | 11 | int main() { 12 | (void)A{ 13 | A::Options{ 14 | .delta = -1, 15 | }, 16 | }; 17 | } 18 | -------------------------------------------------------------------------------- /example_logprintf.cc: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Cory Fields 2 | // Distributed under the MIT software license, see the accompanying 3 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | 5 | // Warn about any use of LogPrintf that does not end with a newline. 6 | #include 7 | 8 | enum LogFlags { 9 | NONE 10 | }; 11 | 12 | enum Level { 13 | None 14 | }; 15 | 16 | template 17 | static inline void LogPrintf_(const std::string& logging_function, const std::string& source_file, const int source_line, const LogFlags flag, const Level level, const char* fmt, const Args&... args) 18 | { 19 | } 20 | 21 | #define LogPrintLevel_(category, level, ...) LogPrintf_(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__) 22 | #define LogPrintf(...) LogPrintLevel_(LogFlags::NONE, Level::None, __VA_ARGS__) 23 | 24 | // Use a macro instead of a function for conditional logging to prevent 25 | // evaluating arguments when logging for the category is not enabled. 26 | #define LogPrint(category, ...) \ 27 | do { \ 28 | LogPrintf(__VA_ARGS__); \ 29 | } while (0) 30 | 31 | void good_func() 32 | { 33 | LogPrintf("hello world!\n"); 34 | } 35 | void good_func2() 36 | { 37 | LogPrintf("hello world!..."); 38 | } 39 | void bad_func() 40 | { 41 | LogPrintf("hello world!"); 42 | } 43 | void bad_func2() 44 | { 45 | LogPrintf("hello world!.."); 46 | } 47 | -------------------------------------------------------------------------------- /preload.tidy: -------------------------------------------------------------------------------- 1 | l matchtype qualType(hasDeclaration(classTemplateSpecializationDecl(hasName("MaybeEarlyExit")))) 2 | --------------------------------------------------------------------------------