1 //=== PointerSubChecker.cpp - Pointer subtraction checker ------*- C++ -*--===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This files defines PointerSubChecker, a builtin checker that checks for
10 // pointer subtractions on two pointers pointing to different memory chunks.
11 // This check corresponds to CWE-469.
13 //===----------------------------------------------------------------------===//
15 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
16 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
17 #include "clang/StaticAnalyzer/Core/Checker.h"
18 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
21 using namespace clang;
25 class PointerSubChecker
26 : public Checker< check::PreStmt<BinaryOperator> > {
27 mutable std::unique_ptr<BuiltinBug> BT;
30 void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
34 void PointerSubChecker::checkPreStmt(const BinaryOperator *B,
35 CheckerContext &C) const {
36 // When doing pointer subtraction, if the two pointers do not point to the
37 // same memory chunk, emit a warning.
38 if (B->getOpcode() != BO_Sub)
41 SVal LV = C.getSVal(B->getLHS());
42 SVal RV = C.getSVal(B->getRHS());
44 const MemRegion *LR = LV.getAsRegion();
45 const MemRegion *RR = RV.getAsRegion();
50 const MemRegion *BaseLR = LR->getBaseRegion();
51 const MemRegion *BaseRR = RR->getBaseRegion();
56 // Allow arithmetic on different symbolic regions.
57 if (isa<SymbolicRegion>(BaseLR) || isa<SymbolicRegion>(BaseRR))
60 if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
63 new BuiltinBug(this, "Pointer subtraction",
64 "Subtraction of two pointers that do not point to "
65 "the same memory chunk may cause incorrect result."));
67 std::make_unique<PathSensitiveBugReport>(*BT, BT->getDescription(), N);
68 R->addRange(B->getSourceRange());
69 C.emitReport(std::move(R));
73 void ento::registerPointerSubChecker(CheckerManager &mgr) {
74 mgr.registerChecker<PointerSubChecker>();
77 bool ento::shouldRegisterPointerSubChecker(const CheckerManager &mgr) {