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 ReturnPointerRangeChecker : |
26 | public Checker< check::PreStmt<ReturnStmt> > { |
27 | mutable std::unique_ptr<BuiltinBug> BT; |
28 | |
29 | public: |
30 | void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const; |
31 | }; |
32 | } |
33 | |
34 | void ReturnPointerRangeChecker::checkPreStmt(const ReturnStmt *RS, |
35 | CheckerContext &C) const { |
36 | ProgramStateRef state = C.getState(); |
37 | |
38 | const Expr *RetE = RS->getRetValue(); |
39 | if (!RetE) |
40 | return; |
41 | |
42 | SVal V = C.getSVal(RetE); |
43 | const MemRegion *R = V.getAsRegion(); |
44 | |
45 | const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(R); |
46 | if (!ER) |
47 | return; |
48 | |
49 | DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>(); |
50 | |
51 | |
52 | if (Idx.isZeroConstant()) |
53 | return; |
54 | |
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 | |
66 | if (!N) |
67 | return; |
68 | |
69 | |
70 | |
71 | if (!BT) |
72 | BT.reset(new BuiltinBug( |
73 | this, "Return of pointer value outside of expected range", |
74 | "Returned pointer value points outside the original object " |
75 | "(potential buffer overflow)")); |
76 | |
77 | |
78 | |
79 | |
80 | |
81 | |
82 | auto report = llvm::make_unique<BugReport>(*BT, BT->getDescription(), N); |
83 | |
84 | report->addRange(RetE->getSourceRange()); |
85 | C.emitReport(std::move(report)); |
86 | } |
87 | } |
88 | |
89 | void ento::registerReturnPointerRangeChecker(CheckerManager &mgr) { |
90 | mgr.registerChecker<ReturnPointerRangeChecker>(); |
91 | } |
92 | |
93 | bool ento::shouldRegisterReturnPointerRangeChecker(const LangOptions &LO) { |
94 | return true; |
95 | } |
96 | |