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/Checker.h"
17 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
22 using namespace clang;
26 class ArrayBoundChecker :
27 public Checker<check::Location> {
28 mutable llvm::OwningPtr<BuiltinBug> BT;
30 void checkLocation(SVal l, bool isLoad, CheckerContext &C) const;
34 void ArrayBoundChecker::checkLocation(SVal l, bool isLoad,
35 CheckerContext &C) const {
36 // Check for out of bound array element access.
37 const MemRegion *R = l.getAsRegion();
41 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
45 // Get the index of the accessed element.
46 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
48 // Zero index is always in bound, this also passes ElementRegions created for
50 if (Idx.isZeroConstant())
53 const GRState *state = C.getState();
55 // Get the size of the array.
56 DefinedOrUnknownSVal NumElements
57 = C.getStoreManager().getSizeInElements(state, ER->getSuperRegion(),
60 const GRState *StInBound = state->assumeInBound(Idx, NumElements, true);
61 const GRState *StOutBound = state->assumeInBound(Idx, NumElements, false);
62 if (StOutBound && !StInBound) {
63 ExplodedNode *N = C.generateSink(StOutBound);
68 BT.reset(new BuiltinBug("Out-of-bound array access",
69 "Access out-of-bound array element (buffer overflow)"));
71 // FIXME: It would be nice to eventually make this diagnostic more clear,
72 // e.g., by referencing the original declaration or by saying *why* this
73 // reference is outside the range.
75 // Generate a report for this bug.
76 RangedBugReport *report =
77 new RangedBugReport(*BT, BT->getDescription(), N);
79 report->addRange(C.getStmt()->getSourceRange());
84 // Array bound check succeeded. From this point forward the array bound
85 // should always succeed.
87 C.addTransition(StInBound);
90 void ento::registerArrayBoundChecker(CheckerManager &mgr) {
91 mgr.registerChecker<ArrayBoundChecker>();