blob: ebe051e6e954390d1383f89eb52542cb238ba4c8 [file] [log] [blame]
Zhongxing Xu3ce2dc32009-11-09 05:34:10 +00001//=== PointerSubChecker.cpp - Pointer subtraction 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 PointerSubChecker, a builtin checker that checks for
11// pointer subtractions on two pointers pointing to different memory chunks.
12// This check corresponds to CWE-469.
13//
14//===----------------------------------------------------------------------===//
15
16#include "clang/Analysis/PathSensitive/CheckerVisitor.h"
17#include "GRExprEngineInternalChecks.h"
18
19using namespace clang;
20
21namespace {
22class VISIBILITY_HIDDEN PointerSubChecker
23 : public CheckerVisitor<PointerSubChecker> {
24 BuiltinBug *BT;
25public:
26 PointerSubChecker() : BT(0) {}
27 static void *getTag();
28 void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
29};
30}
31
32void *PointerSubChecker::getTag() {
33 static int x;
34 return &x;
35}
36
37void PointerSubChecker::PreVisitBinaryOperator(CheckerContext &C,
38 const BinaryOperator *B) {
39 // When doing pointer subtraction, if the two pointers do not point to the
40 // same memory chunk, emit a warning.
41 if (B->getOpcode() != BinaryOperator::Sub)
42 return;
43
44 const GRState *state = C.getState();
45 SVal LV = state->getSVal(B->getLHS());
46 SVal RV = state->getSVal(B->getRHS());
47
48 const MemRegion *LR = LV.getAsRegion();
49 const MemRegion *RR = RV.getAsRegion();
50
51 if (!(LR && RR) || (LR == RR))
52 return;
53
54 // We don't reason about SymbolicRegions for now.
55 if (isa<SymbolicRegion>(LR) || isa<SymbolicRegion>(RR))
56 return;
57
58 if (ExplodedNode *N = C.GenerateNode(B)) {
59 if (!BT)
60 BT = new BuiltinBug("Pointer subtraction",
61 "Subtraction of two pointers that do not point to the same memory chunk may cause incorrect result.");
62 RangedBugReport *R = new RangedBugReport(*BT, BT->getDescription().c_str(),
63 N);
64 R->addRange(B->getSourceRange());
65 C.EmitReport(R);
66 }
67}
68
69void clang::RegisterPointerSubChecker(GRExprEngine &Eng) {
70 Eng.registerCheck(new PointerSubChecker());
71}