| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" |
| 15 | #include "clang/StaticAnalyzer/Core/BugReporter/BugType.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/PathSensitive/ExprEngine.h" |
| 20 | |
| 21 | using namespace clang; |
| 22 | using namespace ento; |
| 23 | |
| 24 | namespace { |
| 25 | class ArrayBoundChecker : |
| 26 | public Checker<check::Location> { |
| 27 | mutable std::unique_ptr<BuiltinBug> BT; |
| 28 | |
| 29 | public: |
| 30 | void checkLocation(SVal l, bool isLoad, const Stmt* S, |
| 31 | CheckerContext &C) const; |
| 32 | }; |
| 33 | } |
| 34 | |
| 35 | void ArrayBoundChecker::checkLocation(SVal l, bool isLoad, const Stmt* LoadS, |
| 36 | CheckerContext &C) const { |
| 37 | |
| 38 | const MemRegion *R = l.getAsRegion(); |
| 39 | if (!R) |
| 40 | return; |
| 41 | |
| 42 | const ElementRegion *ER = dyn_cast<ElementRegion>(R); |
| 43 | if (!ER) |
| 44 | return; |
| 45 | |
| 46 | |
| 47 | DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>(); |
| 48 | |
| 49 | |
| 50 | |
| 51 | if (Idx.isZeroConstant()) |
| 52 | return; |
| 53 | |
| 54 | ProgramStateRef state = C.getState(); |
| 55 | |
| 56 | |
| 57 | DefinedOrUnknownSVal NumElements |
| 58 | = C.getStoreManager().getSizeInElements(state, ER->getSuperRegion(), |
| 59 | ER->getValueType()); |
| 60 | |
| 61 | ProgramStateRef StInBound = state->assumeInBound(Idx, NumElements, true); |
| 62 | ProgramStateRef StOutBound = state->assumeInBound(Idx, NumElements, false); |
| 63 | if (StOutBound && !StInBound) { |
| 64 | ExplodedNode *N = C.generateErrorNode(StOutBound); |
| 65 | if (!N) |
| 66 | return; |
| 67 | |
| 68 | if (!BT) |
| 69 | BT.reset(new BuiltinBug( |
| 70 | this, "Out-of-bound array access", |
| 71 | "Access out-of-bound array element (buffer overflow)")); |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | auto report = llvm::make_unique<BugReport>(*BT, BT->getDescription(), N); |
| 79 | |
| 80 | report->addRange(LoadS->getSourceRange()); |
| 81 | C.emitReport(std::move(report)); |
| 82 | return; |
| 83 | } |
| 84 | |
| 85 | |
| 86 | |
| 87 | C.addTransition(StInBound); |
| 88 | } |
| 89 | |
| 90 | void ento::registerArrayBoundChecker(CheckerManager &mgr) { |
| 91 | mgr.registerChecker<ArrayBoundChecker>(); |
| 92 | } |
| 93 | |
| 94 | bool ento::shouldRegisterArrayBoundChecker(const LangOptions &LO) { |
| 95 | return true; |
| 96 | } |
| 97 | |