1 //== ReturnPointerRangeChecker.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 ReturnPointerRangeChecker, which is a path-sensitive check
11 // which looks for an out-of-bound pointer being returned to callers.
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 ReturnPointerRangeChecker :
27 public Checker< check::PreStmt<ReturnStmt> > {
28 mutable std::unique_ptr<BuiltinBug> BT;
31 void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
35 void ReturnPointerRangeChecker::checkPreStmt(const ReturnStmt *RS,
36 CheckerContext &C) const {
37 ProgramStateRef state = C.getState();
39 const Expr *RetE = RS->getRetValue();
43 SVal V = state->getSVal(RetE, C.getLocationContext());
44 const MemRegion *R = V.getAsRegion();
46 const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(R);
50 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
51 // Zero index is always in bound, this also passes ElementRegions created for
53 if (Idx.isZeroConstant())
55 // FIXME: All of this out-of-bounds checking should eventually be refactored
56 // into a common place.
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 // FIXME: This bug correspond to CWE-466. Eventually we should have bug
71 // types explicitly reference such exploit categories (when applicable).
73 BT.reset(new BuiltinBug(
74 this, "Return of pointer value outside of expected range",
75 "Returned pointer value points outside the original object "
76 "(potential buffer overflow)"));
78 // FIXME: It would be nice to eventually make this diagnostic more clear,
79 // e.g., by referencing the original declaration or by saying *why* this
80 // reference is outside the range.
82 // Generate a report for this bug.
83 auto report = llvm::make_unique<BugReport>(*BT, BT->getDescription(), N);
85 report->addRange(RetE->getSourceRange());
86 C.emitReport(std::move(report));
90 void ento::registerReturnPointerRangeChecker(CheckerManager &mgr) {
91 mgr.registerChecker<ReturnPointerRangeChecker>();