clang 18.0.0git
ReturnPointerRangeChecker.cpp
Go to the documentation of this file.
1//== ReturnPointerRangeChecker.cpp ------------------------------*- C++ -*--==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines ReturnPointerRangeChecker, which is a path-sensitive check
10// which looks for an out-of-bound pointer being returned to callers.
11//
12//===----------------------------------------------------------------------===//
13
22
23using namespace clang;
24using namespace ento;
25
26namespace {
27class ReturnPointerRangeChecker :
28 public Checker< check::PreStmt<ReturnStmt> > {
29 mutable std::unique_ptr<BugType> BT;
30
31public:
32 void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
33};
34}
35
36void ReturnPointerRangeChecker::checkPreStmt(const ReturnStmt *RS,
37 CheckerContext &C) const {
38 ProgramStateRef state = C.getState();
39
40 const Expr *RetE = RS->getRetValue();
41 if (!RetE)
42 return;
43
44 // Skip "body farmed" functions.
45 if (RetE->getSourceRange().isInvalid())
46 return;
47
48 SVal V = C.getSVal(RetE);
49 const MemRegion *R = V.getAsRegion();
50
51 const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(R);
52 if (!ER)
53 return;
54
56 // Zero index is always in bound, this also passes ElementRegions created for
57 // pointer casts.
58 if (Idx.isZeroConstant())
59 return;
60
61 // FIXME: All of this out-of-bounds checking should eventually be refactored
62 // into a common place.
64 state, ER->getSuperRegion(), C.getSValBuilder(), ER->getValueType());
65
66 // We assume that the location after the last element in the array is used as
67 // end() iterator. Reporting on these would return too many false positives.
68 if (Idx == ElementCount)
69 return;
70
71 ProgramStateRef StInBound, StOutBound;
72 std::tie(StInBound, StOutBound) = state->assumeInBoundDual(Idx, ElementCount);
73 if (StOutBound && !StInBound) {
74 ExplodedNode *N = C.generateErrorNode(StOutBound);
75
76 if (!N)
77 return;
78
79 // FIXME: This bug correspond to CWE-466. Eventually we should have bug
80 // types explicitly reference such exploit categories (when applicable).
81 if (!BT)
82 BT.reset(new BugType(this, "Buffer overflow"));
83 constexpr llvm::StringLiteral Msg =
84 "Returned pointer value points outside the original object "
85 "(potential buffer overflow)";
86
87 // Generate a report for this bug.
88 auto Report = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
89 Report->addRange(RetE->getSourceRange());
90
91 const auto ConcreteElementCount = ElementCount.getAs<nonloc::ConcreteInt>();
92 const auto ConcreteIdx = Idx.getAs<nonloc::ConcreteInt>();
93
94 const auto *DeclR = ER->getSuperRegion()->getAs<DeclRegion>();
95
96 if (DeclR)
97 Report->addNote("Original object declared here",
98 {DeclR->getDecl(), C.getSourceManager()});
99
100 if (ConcreteElementCount) {
101 SmallString<128> SBuf;
102 llvm::raw_svector_ostream OS(SBuf);
103 OS << "Original object ";
104 if (DeclR) {
105 OS << "'";
106 DeclR->getDecl()->printName(OS);
107 OS << "' ";
108 }
109 OS << "is an array of " << ConcreteElementCount->getValue() << " '";
110 ER->getValueType().print(OS,
111 PrintingPolicy(C.getASTContext().getLangOpts()));
112 OS << "' objects";
113 if (ConcreteIdx) {
114 OS << ", returned pointer points at index " << ConcreteIdx->getValue();
115 }
116
117 Report->addNote(SBuf,
118 {RetE, C.getSourceManager(), C.getLocationContext()});
119 }
120
121 bugreporter::trackExpressionValue(N, RetE, *Report);
122
123 C.emitReport(std::move(Report));
124 }
125}
126
127void ento::registerReturnPointerRangeChecker(CheckerManager &mgr) {
128 mgr.registerChecker<ReturnPointerRangeChecker>();
129}
130
131bool ento::shouldRegisterReturnPointerRangeChecker(const CheckerManager &mgr) {
132 return true;
133}
#define V(N, I)
Definition: ASTContext.h:3241
This represents one expression.
Definition: Expr.h:110
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3013
Expr * getRetValue()
Definition: Stmt.h:3044
bool isInvalid() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:325
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
ElementRegion is used to represent both array elements and casts.
Definition: MemRegion.h:1194
QualType getValueType() const override
Definition: MemRegion.h:1216
NonLoc getIndex() const
Definition: MemRegion.h:1214
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:96
const RegionTy * getAs() const
Definition: MemRegion.h:1383
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition: SVals.h:55
bool isZeroConstant() const
Definition: SVals.cpp:258
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition: SVals.h:86
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:82
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getSuperRegion() const
Definition: MemRegion.h:454
Value representing integer constant.
Definition: SVals.h:305
const llvm::APSInt & getValue() const
Definition: SVals.h:309
bool trackExpressionValue(const ExplodedNode *N, const Expr *E, PathSensitiveBugReport &R, TrackingOptions Opts={})
Attempts to add visitors to track expression value back to its point of origin.
DefinedOrUnknownSVal getDynamicElementCount(ProgramStateRef State, const MemRegion *MR, SValBuilder &SVB, QualType Ty)
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57