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/StaticAnalyzer/Core/Checker.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
18 #include "clang/AST/StmtVisitor.h"
20 using namespace clang;
24 class WalkAST : public StmtVisitor<WalkAST> {
28 WalkAST(BugReporter &br) : BR(br) {}
29 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
30 void VisitStmt(Stmt *S) { VisitChildren(S); }
31 void VisitChildren(Stmt *S);
35 void WalkAST::VisitChildren(Stmt *S) {
36 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
41 // CWE-467: Use of sizeof() on a Pointer Type
42 void WalkAST::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) {
43 if (E->getKind() != UETT_SizeOf)
46 // If an explicit type is used in the code, usually the coder knows what he is
48 if (E->isArgumentType())
51 QualType T = E->getTypeOfArgument();
52 if (T->isPointerType()) {
54 // Many false positives have the form 'sizeof *p'. This is reasonable
55 // because people know what they are doing when they intentionally
56 // dereference the pointer.
57 Expr *ArgEx = E->getArgumentExpr();
58 if (!isa<DeclRefExpr>(ArgEx->IgnoreParens()))
61 SourceRange R = ArgEx->getSourceRange();
62 BR.EmitBasicReport("Potential unintended use of sizeof() on pointer type",
64 "The code calls sizeof() on a pointer type. "
65 "This can produce an unexpected result.",
66 E->getLocStart(), &R, 1);
70 //===----------------------------------------------------------------------===//
71 // SizeofPointerChecker
72 //===----------------------------------------------------------------------===//
75 class SizeofPointerChecker : public Checker<check::ASTCodeBody> {
77 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
78 BugReporter &BR) const {
80 walker.Visit(D->getBody());
85 void ento::registerSizeofPointerChecker(CheckerManager &mgr) {
86 mgr.registerChecker<SizeofPointerChecker>();