1 //===--- ComparisonInTempFailureRetryCheck.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 "../utils/Matchers.h" 10 #include "ComparisonInTempFailureRetryCheck.h" 11 #include "clang/AST/ASTContext.h" 12 #include "clang/ASTMatchers/ASTMatchFinder.h" 13 #include "clang/Lex/Lexer.h" 14 15 using namespace clang::ast_matchers; 16 17 namespace clang { 18 namespace tidy { 19 namespace android { 20 21 namespace { 22 AST_MATCHER(BinaryOperator, isRHSATempFailureRetryArg) { 23 if (!Node.getBeginLoc().isMacroID()) 24 return false; 25 26 const SourceManager &SM = Finder->getASTContext().getSourceManager(); 27 if (!SM.isMacroArgExpansion(Node.getRHS()->IgnoreParenCasts()->getBeginLoc())) 28 return false; 29 30 const LangOptions &Opts = Finder->getASTContext().getLangOpts(); 31 SourceLocation LocStart = Node.getBeginLoc(); 32 while (LocStart.isMacroID()) { 33 SourceLocation Invocation = SM.getImmediateMacroCallerLoc(LocStart); 34 Token Tok; 35 if (!Lexer::getRawToken(SM.getSpellingLoc(Invocation), Tok, SM, Opts, 36 /*IgnoreWhiteSpace=*/true)) { 37 if (Tok.getKind() == tok::raw_identifier && 38 Tok.getRawIdentifier() == "TEMP_FAILURE_RETRY") 39 return true; 40 } 41 42 LocStart = Invocation; 43 } 44 return false; 45 } 46 } // namespace 47 48 void ComparisonInTempFailureRetryCheck::registerMatchers(MatchFinder *Finder) { 49 // Both glibc's and Bionic's TEMP_FAILURE_RETRY macros structurally look like: 50 // 51 // #define TEMP_FAILURE_RETRY(x) ({ \ 52 // typeof(x) y; \ 53 // do y = (x); \ 54 // while (y == -1 && errno == EINTR); \ 55 // y; \ 56 // }) 57 // 58 // (glibc uses `long int` instead of `typeof(x)` for the type of y). 59 // 60 // It's unclear how to walk up the AST from inside the expansion of `x`, and 61 // we need to not complain about things like TEMP_FAILURE_RETRY(foo(x == 1)), 62 // so we just match the assignment of `y = (x)` and inspect `x` from there. 63 Finder->addMatcher( 64 binaryOperator( 65 hasOperatorName("="), 66 hasRHS(ignoringParenCasts( 67 binaryOperator(matchers::isComparisonOperator()).bind("binop"))), 68 isRHSATempFailureRetryArg()), 69 this); 70 } 71 72 void ComparisonInTempFailureRetryCheck::check( 73 const MatchFinder::MatchResult &Result) { 74 const auto &BinOp = *Result.Nodes.getNodeAs<BinaryOperator>("binop"); 75 diag(BinOp.getOperatorLoc(), "top-level comparison in TEMP_FAILURE_RETRY"); 76 77 // FIXME: FixIts would be nice, but potentially nontrivial when nested macros 78 // happen, e.g. `TEMP_FAILURE_RETRY(IS_ZERO(foo()))` 79 } 80 81 } // namespace android 82 } // namespace tidy 83 } // namespace clang 84