1 //=== PointerSubChecker.cpp - Pointer subtraction checker ------*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "ClangSACheckers.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18 #include "clang/StaticAnalyzer/Core/Checker.h"
19 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22 using namespace clang;
26 class PointerSubChecker
27 : public Checker< check::PreStmt<BinaryOperator> > {
28 mutable OwningPtr<BuiltinBug> BT;
31 void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
35 void PointerSubChecker::checkPreStmt(const BinaryOperator *B,
36 CheckerContext &C) const {
37 // When doing pointer subtraction, if the two pointers do not point to the
38 // same memory chunk, emit a warning.
39 if (B->getOpcode() != BO_Sub)
42 ProgramStateRef state = C.getState();
43 const LocationContext *LCtx = C.getLocationContext();
44 SVal LV = state->getSVal(B->getLHS(), LCtx);
45 SVal RV = state->getSVal(B->getRHS(), LCtx);
47 const MemRegion *LR = LV.getAsRegion();
48 const MemRegion *RR = RV.getAsRegion();
53 const MemRegion *BaseLR = LR->getBaseRegion();
54 const MemRegion *BaseRR = RR->getBaseRegion();
59 // Allow arithmetic on different symbolic regions.
60 if (isa<SymbolicRegion>(BaseLR) || isa<SymbolicRegion>(BaseRR))
63 if (ExplodedNode *N = C.addTransition()) {
65 BT.reset(new BuiltinBug("Pointer subtraction",
66 "Subtraction of two pointers that do not point to "
67 "the same memory chunk may cause incorrect result."));
68 BugReport *R = new BugReport(*BT, BT->getDescription(), N);
69 R->addRange(B->getSourceRange());
74 void ento::registerPointerSubChecker(CheckerManager &mgr) {
75 mgr.registerChecker<PointerSubChecker>();