1 //==- CheckSizeofPointer.cpp - Check for sizeof on pointers ------*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a check for unintended use of sizeof() on pointer
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.h"
16 #include "clang/AST/StmtVisitor.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
18 #include "clang/StaticAnalyzer/Core/Checker.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
21 using namespace clang;
25 class WalkAST : public StmtVisitor<WalkAST> {
27 const CheckerBase *Checker;
28 AnalysisDeclContext* AC;
31 WalkAST(BugReporter &br, const CheckerBase *checker, AnalysisDeclContext *ac)
32 : BR(br), Checker(checker), AC(ac) {}
33 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
34 void VisitStmt(Stmt *S) { VisitChildren(S); }
35 void VisitChildren(Stmt *S);
39 void WalkAST::VisitChildren(Stmt *S) {
40 for (Stmt *Child : S->children())
45 // CWE-467: Use of sizeof() on a Pointer Type
46 void WalkAST::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) {
47 if (E->getKind() != UETT_SizeOf)
50 // If an explicit type is used in the code, usually the coder knows what they are
52 if (E->isArgumentType())
55 QualType T = E->getTypeOfArgument();
56 if (T->isPointerType()) {
58 // Many false positives have the form 'sizeof *p'. This is reasonable
59 // because people know what they are doing when they intentionally
60 // dereference the pointer.
61 Expr *ArgEx = E->getArgumentExpr();
62 if (!isa<DeclRefExpr>(ArgEx->IgnoreParens()))
65 PathDiagnosticLocation ELoc =
66 PathDiagnosticLocation::createBegin(E, BR.getSourceManager(), AC);
67 BR.EmitBasicReport(AC->getDecl(), Checker,
68 "Potential unintended use of sizeof() on pointer type",
69 categories::LogicError,
70 "The code calls sizeof() on a pointer type. "
71 "This can produce an unexpected result.",
72 ELoc, ArgEx->getSourceRange());
76 //===----------------------------------------------------------------------===//
77 // SizeofPointerChecker
78 //===----------------------------------------------------------------------===//
81 class SizeofPointerChecker : public Checker<check::ASTCodeBody> {
83 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
84 BugReporter &BR) const {
85 WalkAST walker(BR, this, mgr.getAnalysisDeclContext(D));
86 walker.Visit(D->getBody());
91 void ento::registerSizeofPointerChecker(CheckerManager &mgr) {
92 mgr.registerChecker<SizeofPointerChecker>();