blob: bbe494c99da532441f78d68397ba2cbd74ae13fc [file] [log] [blame]
Zhongxing Xu28a109f2009-11-08 13:10:34 +00001//==- 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
Ted Kremenek6b676302010-01-25 17:10:22 +000015#include "clang/Checker/BugReporter/BugReporter.h"
Zhongxing Xu28a109f2009-11-08 13:10:34 +000016#include "clang/AST/StmtVisitor.h"
Ted Kremenek97053092010-01-26 22:59:55 +000017#include "clang/Checker/Checkers/LocalCheckers.h"
Zhongxing Xu28a109f2009-11-08 13:10:34 +000018
19using namespace clang;
20
21namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000022class WalkAST : public StmtVisitor<WalkAST> {
Zhongxing Xu28a109f2009-11-08 13:10:34 +000023 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
Zhongxing Xu52cb2772009-11-10 04:20:20 +000044 // 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
Zhongxing Xu28a109f2009-11-08 13:10:34 +000049 QualType T = E->getTypeOfArgument();
50 if (T->isPointerType()) {
Zhongxing Xu37e9c472009-11-10 07:52:53 +000051
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();
Zhongxing Xub6aa69a2009-11-10 08:33:44 +000056 if (!isa<DeclRefExpr>(ArgEx->IgnoreParens()))
Zhongxing Xu37e9c472009-11-10 07:52:53 +000057 return;
58
59 SourceRange R = ArgEx->getSourceRange();
Zhongxing Xu28a109f2009-11-08 13:10:34 +000060 BR.EmitBasicReport("Potential unintended use of sizeof() on pointer type",
61 "Logic",
Zhongxing Xudfed7a12009-11-09 07:29:39 +000062 "The code calls sizeof() on a pointer type. "
63 "This can produce an unexpected result.",
Zhongxing Xu28a109f2009-11-08 13:10:34 +000064 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}