blob: ada6082dd28e60a278a1fde9614548000e6e24b5 [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
15#include "clang/Analysis/PathSensitive/BugReporter.h"
16#include "clang/AST/StmtVisitor.h"
17#include "clang/Analysis/LocalCheckers.h"
18#include "llvm/Support/Compiler.h"
19
20using namespace clang;
21
22namespace {
23class VISIBILITY_HIDDEN WalkAST : public StmtVisitor<WalkAST> {
24 BugReporter &BR;
25
26public:
27 WalkAST(BugReporter &br) : BR(br) {}
28 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
29 void VisitStmt(Stmt *S) { VisitChildren(S); }
30 void VisitChildren(Stmt *S);
31};
32}
33
34void WalkAST::VisitChildren(Stmt *S) {
35 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
36 if (Stmt *child = *I)
37 Visit(child);
38}
39
40// CWE-467: Use of sizeof() on a Pointer Type
41void WalkAST::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
42 if (!E->isSizeOf())
43 return;
44
Zhongxing Xu52cb2772009-11-10 04:20:20 +000045 // If an explicit type is used in the code, usually the coder knows what he is
46 // doing.
47 if (E->isArgumentType())
48 return;
49
Zhongxing Xu28a109f2009-11-08 13:10:34 +000050 QualType T = E->getTypeOfArgument();
51 if (T->isPointerType()) {
Zhongxing Xu572ea262009-11-10 03:27:00 +000052 SourceRange R = E->getSourceRange();
Zhongxing Xu28a109f2009-11-08 13:10:34 +000053 BR.EmitBasicReport("Potential unintended use of sizeof() on pointer type",
54 "Logic",
Zhongxing Xudfed7a12009-11-09 07:29:39 +000055 "The code calls sizeof() on a pointer type. "
56 "This can produce an unexpected result.",
Zhongxing Xu28a109f2009-11-08 13:10:34 +000057 E->getLocStart(), &R, 1);
58 }
59}
60
61void clang::CheckSizeofPointer(const Decl *D, BugReporter &BR) {
62 WalkAST walker(BR);
63 walker.Visit(D->getBody());
64}