clang-tools 22.0.0git
SuspiciousReallocUsageCheck.cpp
Go to the documentation of this file.
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-exception
6//
7//===----------------------------------------------------------------------===//
8
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 same
21/// "pointer expression". The "pointer expression" can consist of member
22/// expressions and declaration references only (like \c a->b->c), otherwise the
23/// 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 of
27 /// the visit functions. Every visit function starts by converting \c OtherE
28 /// 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 variable
60/// \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 FindAssignToVarBefore
63 : 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 return llvm::any_of(S->children(), [this](const Stmt *Child) {
96 return Child && Visit(Child);
97 });
98 }
99};
100
101} // namespace
102
103namespace clang::tidy::bugprone {
104
106 // void *realloc(void *ptr, size_t size);
107 auto ReallocDecl =
108 functionDecl(hasName("::realloc"), parameterCountIs(2),
109 hasParameter(0, hasType(pointerType(pointee(voidType())))),
110 hasParameter(1, hasType(isInteger())))
111 .bind("realloc");
112
113 auto ReallocCall =
114 callExpr(callee(ReallocDecl), hasArgument(0, expr().bind("ptr_input")),
115 hasAncestor(functionDecl().bind("parent_function")))
116 .bind("call");
117 Finder->addMatcher(binaryOperator(hasOperatorName("="),
118 hasLHS(expr().bind("ptr_result")),
119 hasRHS(ignoringParenCasts(ReallocCall))),
120 this);
121}
122
124 const MatchFinder::MatchResult &Result) {
125 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
126 if (!Call)
127 return;
128 const auto *PtrInputExpr = Result.Nodes.getNodeAs<Expr>("ptr_input");
129 const auto *PtrResultExpr = Result.Nodes.getNodeAs<Expr>("ptr_result");
130 if (!PtrInputExpr || !PtrResultExpr)
131 return;
132 const auto *ReallocD = Result.Nodes.getNodeAs<Decl>("realloc");
133 assert(ReallocD && "Value for 'realloc' should exist if 'call' was found.");
134 SourceManager &SM = ReallocD->getASTContext().getSourceManager();
135
136 if (!IsSamePtrExpr{}.check(PtrInputExpr, PtrResultExpr))
137 return;
138
139 if (const auto *DeclRef =
140 dyn_cast<DeclRefExpr>(PtrInputExpr->IgnoreParenImpCasts()))
141 if (const auto *Var = dyn_cast<VarDecl>(DeclRef->getDecl()))
142 if (const auto *Func =
143 Result.Nodes.getNodeAs<FunctionDecl>("parent_function"))
144 if (FindAssignToVarBefore{Var, DeclRef, SM}.Visit(Func->getBody()))
145 return;
146
147 const StringRef CodeOfAssignedExpr = Lexer::getSourceText(
148 CharSourceRange::getTokenRange(PtrResultExpr->getSourceRange()), SM,
149 getLangOpts());
150 diag(Call->getBeginLoc(), "'%0' may be set to null if 'realloc' fails, which "
151 "may result in a leak of the original buffer")
152 << CodeOfAssignedExpr << PtrInputExpr->getSourceRange()
153 << PtrResultExpr->getSourceRange();
154}
155
156} // namespace clang::tidy::bugprone
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
bool check(llvm::StringRef File, const ThreadsafeFS &TFS, const ClangdLSPServer::Options &Opts)
Definition Check.cpp:462
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//