1 //== ArrayBoundChecker.cpp ------------------------------*- 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 file defines ArrayBoundChecker, which is a path-sensitive check
11 // which looks for an out-of-bound array element access.
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.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"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
22 using namespace clang;
26 class ArrayBoundChecker :
27 public Checker<check::Location> {
28 mutable std::unique_ptr<BuiltinBug> BT;
31 void checkLocation(SVal l, bool isLoad, const Stmt* S,
32 CheckerContext &C) const;
36 void ArrayBoundChecker::checkLocation(SVal l, bool isLoad, const Stmt* LoadS,
37 CheckerContext &C) const {
38 // Check for out of bound array element access.
39 const MemRegion *R = l.getAsRegion();
43 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
47 // Get the index of the accessed element.
48 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
50 // Zero index is always in bound, this also passes ElementRegions created for
52 if (Idx.isZeroConstant())
55 ProgramStateRef state = C.getState();
57 // Get the size of the array.
58 DefinedOrUnknownSVal NumElements
59 = C.getStoreManager().getSizeInElements(state, ER->getSuperRegion(),
62 ProgramStateRef StInBound = state->assumeInBound(Idx, NumElements, true);
63 ProgramStateRef StOutBound = state->assumeInBound(Idx, NumElements, false);
64 if (StOutBound && !StInBound) {
65 ExplodedNode *N = C.generateErrorNode(StOutBound);
70 BT.reset(new BuiltinBug(
71 this, "Out-of-bound array access",
72 "Access out-of-bound array element (buffer overflow)"));
74 // FIXME: It would be nice to eventually make this diagnostic more clear,
75 // e.g., by referencing the original declaration or by saying *why* this
76 // reference is outside the range.
78 // Generate a report for this bug.
79 auto report = llvm::make_unique<BugReport>(*BT, BT->getDescription(), N);
81 report->addRange(LoadS->getSourceRange());
82 C.emitReport(std::move(report));
86 // Array bound check succeeded. From this point forward the array bound
87 // should always succeed.
88 C.addTransition(StInBound);
91 void ento::registerArrayBoundChecker(CheckerManager &mgr) {
92 mgr.registerChecker<ArrayBoundChecker>();