158 lines · cpp
1//===----------------------------------------------------------------------===//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-exception6//7//===----------------------------------------------------------------------===//8 9#include "SuspiciousReallocUsageCheck.h"10#include "clang/AST/ASTContext.h"11#include "clang/AST/StmtVisitor.h"12#include "clang/ASTMatchers/ASTMatchFinder.h"13#include "clang/ASTMatchers/ASTMatchers.h"14#include "clang/Lex/Lexer.h"15 16using namespace clang::ast_matchers;17using namespace clang;18 19namespace {20/// Check if two different expression nodes denote the same21/// "pointer expression". The "pointer expression" can consist of member22/// expressions and declaration references only (like \c a->b->c), otherwise the23/// check is always false.24class IsSamePtrExpr : public StmtVisitor<IsSamePtrExpr, bool> {25 /// The other expression to compare against.26 /// This variable is used to pass the data from a \c check function to any of27 /// the visit functions. Every visit function starts by converting \c OtherE28 /// to the current type and store it locally, and do not use \c OtherE later.29 const Expr *OtherE = nullptr;30 31public:32 bool VisitDeclRefExpr(const DeclRefExpr *E1) {33 const auto *E2 = dyn_cast<DeclRefExpr>(OtherE);34 if (!E2)35 return false;36 const Decl *D1 = E1->getDecl()->getCanonicalDecl();37 return isa<VarDecl, FieldDecl>(D1) &&38 D1 == E2->getDecl()->getCanonicalDecl();39 }40 41 bool VisitMemberExpr(const MemberExpr *E1) {42 const auto *E2 = dyn_cast<MemberExpr>(OtherE);43 if (!E2)44 return false;45 if (!check(E1->getBase(), E2->getBase()))46 return false;47 const DeclAccessPair FD = E1->getFoundDecl();48 return isa<FieldDecl>(FD.getDecl()) && FD == E2->getFoundDecl();49 }50 51 bool check(const Expr *E1, const Expr *E2) {52 E1 = E1->IgnoreParenCasts();53 E2 = E2->IgnoreParenCasts();54 OtherE = E2;55 return Visit(const_cast<Expr *>(E1));56 }57};58 59/// Check if there is an assignment or initialization that references a variable60/// \c Var (at right-hand side) and is before \c VarRef in the source code.61/// Only simple assignments like \code a = b \endcode are found.62class FindAssignToVarBefore63 : public ConstStmtVisitor<FindAssignToVarBefore, bool> {64 const VarDecl *Var;65 const DeclRefExpr *VarRef;66 SourceManager &SM;67 68 bool isAccessForVar(const Expr *E) const {69 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))70 return DeclRef->getDecl() &&71 DeclRef->getDecl()->getCanonicalDecl() == Var &&72 SM.isBeforeInTranslationUnit(E->getBeginLoc(),73 VarRef->getBeginLoc());74 return false;75 }76 77public:78 FindAssignToVarBefore(const VarDecl *Var, const DeclRefExpr *VarRef,79 SourceManager &SM)80 : Var(Var->getCanonicalDecl()), VarRef(VarRef), SM(SM) {}81 82 bool VisitDeclStmt(const DeclStmt *S) {83 for (const Decl *D : S->getDeclGroup())84 if (const auto *LeftVar = dyn_cast<VarDecl>(D))85 if (LeftVar->hasInit())86 return isAccessForVar(LeftVar->getInit());87 return false;88 }89 bool VisitBinaryOperator(const BinaryOperator *S) {90 if (S->getOpcode() == BO_Assign)91 return isAccessForVar(S->getRHS());92 return false;93 }94 bool VisitStmt(const Stmt *S) {95 for (const Stmt *Child : S->children())96 if (Child && Visit(Child))97 return true;98 return false;99 }100};101 102} // namespace103 104namespace clang::tidy::bugprone {105 106void SuspiciousReallocUsageCheck::registerMatchers(MatchFinder *Finder) {107 // void *realloc(void *ptr, size_t size);108 auto ReallocDecl =109 functionDecl(hasName("::realloc"), parameterCountIs(2),110 hasParameter(0, hasType(pointerType(pointee(voidType())))),111 hasParameter(1, hasType(isInteger())))112 .bind("realloc");113 114 auto ReallocCall =115 callExpr(callee(ReallocDecl), hasArgument(0, expr().bind("ptr_input")),116 hasAncestor(functionDecl().bind("parent_function")))117 .bind("call");118 Finder->addMatcher(binaryOperator(hasOperatorName("="),119 hasLHS(expr().bind("ptr_result")),120 hasRHS(ignoringParenCasts(ReallocCall))),121 this);122}123 124void SuspiciousReallocUsageCheck::check(125 const MatchFinder::MatchResult &Result) {126 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");127 if (!Call)128 return;129 const auto *PtrInputExpr = Result.Nodes.getNodeAs<Expr>("ptr_input");130 const auto *PtrResultExpr = Result.Nodes.getNodeAs<Expr>("ptr_result");131 if (!PtrInputExpr || !PtrResultExpr)132 return;133 const auto *ReallocD = Result.Nodes.getNodeAs<Decl>("realloc");134 assert(ReallocD && "Value for 'realloc' should exist if 'call' was found.");135 SourceManager &SM = ReallocD->getASTContext().getSourceManager();136 137 if (!IsSamePtrExpr{}.check(PtrInputExpr, PtrResultExpr))138 return;139 140 if (const auto *DeclRef =141 dyn_cast<DeclRefExpr>(PtrInputExpr->IgnoreParenImpCasts()))142 if (const auto *Var = dyn_cast<VarDecl>(DeclRef->getDecl()))143 if (const auto *Func =144 Result.Nodes.getNodeAs<FunctionDecl>("parent_function"))145 if (FindAssignToVarBefore{Var, DeclRef, SM}.Visit(Func->getBody()))146 return;147 148 const StringRef CodeOfAssignedExpr = Lexer::getSourceText(149 CharSourceRange::getTokenRange(PtrResultExpr->getSourceRange()), SM,150 getLangOpts());151 diag(Call->getBeginLoc(), "'%0' may be set to null if 'realloc' fails, which "152 "may result in a leak of the original buffer")153 << CodeOfAssignedExpr << PtrInputExpr->getSourceRange()154 << PtrResultExpr->getSourceRange();155}156 157} // namespace clang::tidy::bugprone158