blob: cbac423b467cdef2d9701f03274991dfffadb592 [file] [log] [blame]
Zhongxing Xuede7eb22009-11-09 13:23:31 +00001//=== PointerArithChecker.cpp - Pointer arithmetic checker -----*- 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 files defines PointerArithChecker, a builtin checker that checks for
11// pointer arithmetic on locations other than array elements.
12//
13//===----------------------------------------------------------------------===//
14
Zhongxing Xuede7eb22009-11-09 13:23:31 +000015#include "GRExprEngineInternalChecks.h"
Benjamin Kramer5e2d2c22010-03-27 21:19:47 +000016#include "clang/Checker/BugReporter/BugType.h"
17#include "clang/Checker/PathSensitive/CheckerVisitor.h"
Zhongxing Xuede7eb22009-11-09 13:23:31 +000018
19using namespace clang;
20
21namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000022class PointerArithChecker
Zhongxing Xuede7eb22009-11-09 13:23:31 +000023 : public CheckerVisitor<PointerArithChecker> {
24 BuiltinBug *BT;
25public:
26 PointerArithChecker() : BT(0) {}
27 static void *getTag();
28 void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
29};
30}
31
32void *PointerArithChecker::getTag() {
33 static int x;
34 return &x;
35}
36
37void PointerArithChecker::PreVisitBinaryOperator(CheckerContext &C,
38 const BinaryOperator *B) {
John McCall2de56d12010-08-25 11:45:40 +000039 if (B->getOpcode() != BO_Sub && B->getOpcode() != BO_Add)
Zhongxing Xuede7eb22009-11-09 13:23:31 +000040 return;
41
42 const GRState *state = C.getState();
Ted Kremenek13976632010-02-08 16:18:51 +000043 SVal LV = state->getSVal(B->getLHS());
44 SVal RV = state->getSVal(B->getRHS());
Zhongxing Xuede7eb22009-11-09 13:23:31 +000045
46 const MemRegion *LR = LV.getAsRegion();
47
48 if (!LR || !RV.isConstant())
49 return;
50
51 // If pointer arithmetic is done on variables of non-array type, this often
52 // means behavior rely on memory organization, which is dangerous.
53 if (isa<VarRegion>(LR) || isa<CodeTextRegion>(LR) ||
54 isa<CompoundLiteralRegion>(LR)) {
55
Ted Kremenek19d67b52009-11-23 22:22:01 +000056 if (ExplodedNode *N = C.GenerateNode()) {
Zhongxing Xuede7eb22009-11-09 13:23:31 +000057 if (!BT)
58 BT = new BuiltinBug("Dangerous pointer arithmetic",
59 "Pointer arithmetic done on non-array variables "
60 "means reliance on memory layout, which is "
61 "dangerous.");
Benjamin Kramerd02e2322009-11-14 12:08:24 +000062 RangedBugReport *R = new RangedBugReport(*BT, BT->getDescription(), N);
Zhongxing Xuede7eb22009-11-09 13:23:31 +000063 R->addRange(B->getSourceRange());
64 C.EmitReport(R);
65 }
66 }
67}
68
69void clang::RegisterPointerArithChecker(GRExprEngine &Eng) {
70 Eng.registerCheck(new PointerArithChecker());
71}