blob: bbe494c99da532441f78d68397ba2cbd74ae13fc [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001//==- CheckSizeofPointer.cpp - Check for sizeof on pointers ------*- C++ -*-==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a check for unintended use of sizeof() on pointer
11// expressions.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Checker/BugReporter/BugReporter.h"
16#include "clang/AST/StmtVisitor.h"
17#include "clang/Checker/Checkers/LocalCheckers.h"
18
19using namespace clang;
20
21namespace {
22class WalkAST : public StmtVisitor<WalkAST> {
23 BugReporter &BR;
24
25public:
26 WalkAST(BugReporter &br) : BR(br) {}
27 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
28 void VisitStmt(Stmt *S) { VisitChildren(S); }
29 void VisitChildren(Stmt *S);
30};
31}
32
33void WalkAST::VisitChildren(Stmt *S) {
34 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
35 if (Stmt *child = *I)
36 Visit(child);
37}
38
39// CWE-467: Use of sizeof() on a Pointer Type
40void WalkAST::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
41 if (!E->isSizeOf())
42 return;
43
44 // If an explicit type is used in the code, usually the coder knows what he is
45 // doing.
46 if (E->isArgumentType())
47 return;
48
49 QualType T = E->getTypeOfArgument();
50 if (T->isPointerType()) {
51
52 // Many false positives have the form 'sizeof *p'. This is reasonable
53 // because people know what they are doing when they intentionally
54 // dereference the pointer.
55 Expr *ArgEx = E->getArgumentExpr();
56 if (!isa<DeclRefExpr>(ArgEx->IgnoreParens()))
57 return;
58
59 SourceRange R = ArgEx->getSourceRange();
60 BR.EmitBasicReport("Potential unintended use of sizeof() on pointer type",
61 "Logic",
62 "The code calls sizeof() on a pointer type. "
63 "This can produce an unexpected result.",
64 E->getLocStart(), &R, 1);
65 }
66}
67
68void clang::CheckSizeofPointer(const Decl *D, BugReporter &BR) {
69 WalkAST walker(BR);
70 walker.Visit(D->getBody());
71}