1 //=== VLASizeChecker.cpp - Undefined dereference checker --------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This defines VLASizeChecker, a builtin check in ExprEngine that
10 // performs checks for declaration of VLA of undefined or zero size.
11 // In addition, VLASizeChecker is responsible for defining the extent
12 // of the MemRegion that represents a VLA.
14 //===----------------------------------------------------------------------===//
17 #include "clang/AST/CharUnits.h"
18 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20 #include "clang/StaticAnalyzer/Core/Checker.h"
21 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/Support/raw_ostream.h"
28 using namespace clang;
30 using namespace taint;
34 : public Checker<check::PreStmt<DeclStmt>,
35 check::PreStmt<UnaryExprOrTypeTraitExpr>> {
36 mutable std::unique_ptr<BugType> BT;
45 /// Check a VLA for validity.
46 /// Every dimension of the array and the total size is checked for validity.
47 /// Returns null or a new state where the size is validated.
48 /// 'ArraySize' will contain SVal that refers to the total size (in char)
50 ProgramStateRef checkVLA(CheckerContext &C, ProgramStateRef State,
51 const VariableArrayType *VLA, SVal &ArraySize) const;
52 /// Check a single VLA index size expression for validity.
53 ProgramStateRef checkVLAIndexSize(CheckerContext &C, ProgramStateRef State,
54 const Expr *SizeE) const;
56 void reportBug(VLASize_Kind Kind, const Expr *SizeE, ProgramStateRef State,
58 std::unique_ptr<BugReporterVisitor> Visitor = nullptr) const;
61 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
62 void checkPreStmt(const UnaryExprOrTypeTraitExpr *UETTE,
63 CheckerContext &C) const;
65 } // end anonymous namespace
67 ProgramStateRef VLASizeChecker::checkVLA(CheckerContext &C,
68 ProgramStateRef State,
69 const VariableArrayType *VLA,
70 SVal &ArraySize) const {
71 assert(VLA && "Function should be called with non-null VLA argument.");
73 const VariableArrayType *VLALast = nullptr;
74 llvm::SmallVector<const Expr *, 2> VLASizes;
76 // Walk over the VLAs for every dimension until a non-VLA is found.
77 // There is a VariableArrayType for every dimension (fixed or variable) until
78 // the most inner array that is variably modified.
79 // Dimension sizes are collected into 'VLASizes'. 'VLALast' is set to the
80 // innermost VLA that was encountered.
81 // In "int vla[x][2][y][3]" this will be the array for index "y" (with type
82 // int[3]). 'VLASizes' contains 'x', '2', and 'y'.
84 const Expr *SizeE = VLA->getSizeExpr();
85 State = checkVLAIndexSize(C, State, SizeE);
88 VLASizes.push_back(SizeE);
90 VLA = C.getASTContext().getAsVariableArrayType(VLA->getElementType());
93 "Array should have at least one variably-modified dimension.");
95 ASTContext &Ctx = C.getASTContext();
96 SValBuilder &SVB = C.getSValBuilder();
97 CanQualType SizeTy = Ctx.getSizeType();
99 SVB.getBasicValueFactory().getMaxValue(SizeTy).getZExtValue();
101 // Get the element size.
102 CharUnits EleSize = Ctx.getTypeSizeInChars(VLALast->getElementType());
104 SVB.makeIntVal(EleSize.getQuantity(), SizeTy).castAs<NonLoc>();
106 // Try to calculate the known real size of the array in KnownSize.
107 uint64_t KnownSize = 0;
108 if (const llvm::APSInt *KV = SVB.getKnownValue(State, ArrSize))
109 KnownSize = KV->getZExtValue();
111 for (const Expr *SizeE : VLASizes) {
112 auto SizeD = C.getSVal(SizeE).castAs<DefinedSVal>();
113 // Convert the array length to size_t.
115 SVB.evalCast(SizeD, SizeTy, SizeE->getType()).castAs<NonLoc>();
116 // Multiply the array length by the element size.
117 SVal Mul = SVB.evalBinOpNN(State, BO_Mul, ArrSize, IndexLength, SizeTy);
118 if (auto MulNonLoc = Mul.getAs<NonLoc>())
119 ArrSize = *MulNonLoc;
121 // Extent could not be determined.
124 if (const llvm::APSInt *IndexLVal = SVB.getKnownValue(State, IndexLength)) {
125 // Check if the array size will overflow.
126 // Size overflow check does not work with symbolic expressions because a
127 // overflow situation can not be detected easily.
128 uint64_t IndexL = IndexLVal->getZExtValue();
129 // FIXME: See https://reviews.llvm.org/D80903 for discussion of
130 // some difference in assume and getKnownValue that leads to
131 // unexpected behavior. Just bail on IndexL == 0 at this point.
135 if (KnownSize <= SizeMax / IndexL) {
138 // Array size does not fit into size_t.
139 reportBug(VLA_Overflow, SizeE, State, C);
152 ProgramStateRef VLASizeChecker::checkVLAIndexSize(CheckerContext &C,
153 ProgramStateRef State,
154 const Expr *SizeE) const {
155 SVal SizeV = C.getSVal(SizeE);
157 if (SizeV.isUndef()) {
158 reportBug(VLA_Garbage, SizeE, State, C);
162 // See if the size value is known. It can't be undefined because we would have
163 // warned about that already.
164 if (SizeV.isUnknown())
167 // Check if the size is tainted.
168 if (isTainted(State, SizeV)) {
169 reportBug(VLA_Tainted, SizeE, nullptr, C,
170 std::make_unique<TaintBugVisitor>(SizeV));
174 // Check if the size is zero.
175 DefinedSVal SizeD = SizeV.castAs<DefinedSVal>();
177 ProgramStateRef StateNotZero, StateZero;
178 std::tie(StateNotZero, StateZero) = State->assume(SizeD);
180 if (StateZero && !StateNotZero) {
181 reportBug(VLA_Zero, SizeE, StateZero, C);
185 // From this point on, assume that the size is not zero.
186 State = StateNotZero;
188 // Check if the size is negative.
189 SValBuilder &SVB = C.getSValBuilder();
191 QualType SizeTy = SizeE->getType();
192 DefinedOrUnknownSVal Zero = SVB.makeZeroVal(SizeTy);
194 SVal LessThanZeroVal = SVB.evalBinOp(State, BO_LT, SizeD, Zero, SizeTy);
195 if (Optional<DefinedSVal> LessThanZeroDVal =
196 LessThanZeroVal.getAs<DefinedSVal>()) {
197 ConstraintManager &CM = C.getConstraintManager();
198 ProgramStateRef StatePos, StateNeg;
200 std::tie(StateNeg, StatePos) = CM.assumeDual(State, *LessThanZeroDVal);
201 if (StateNeg && !StatePos) {
202 reportBug(VLA_Negative, SizeE, State, C);
211 void VLASizeChecker::reportBug(
212 VLASize_Kind Kind, const Expr *SizeE, ProgramStateRef State,
213 CheckerContext &C, std::unique_ptr<BugReporterVisitor> Visitor) const {
214 // Generate an error node.
215 ExplodedNode *N = C.generateErrorNode(State);
220 BT.reset(new BuiltinBug(
221 this, "Dangerous variable-length array (VLA) declaration"));
223 SmallString<256> buf;
224 llvm::raw_svector_ostream os(buf);
225 os << "Declared variable-length array (VLA) ";
228 os << "uses a garbage value as its size";
231 os << "has zero size";
234 os << "has tainted size";
237 os << "has negative size";
240 os << "has too large size";
244 auto report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
245 report->addVisitor(std::move(Visitor));
246 report->addRange(SizeE->getSourceRange());
247 bugreporter::trackExpressionValue(N, SizeE, *report);
248 C.emitReport(std::move(report));
251 void VLASizeChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
252 if (!DS->isSingleDecl())
255 ASTContext &Ctx = C.getASTContext();
256 SValBuilder &SVB = C.getSValBuilder();
257 ProgramStateRef State = C.getState();
258 QualType TypeToCheck;
260 const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
263 TypeToCheck = VD->getType().getCanonicalType();
264 else if (const auto *TND = dyn_cast<TypedefNameDecl>(DS->getSingleDecl()))
265 TypeToCheck = TND->getUnderlyingType().getCanonicalType();
269 const VariableArrayType *VLA = Ctx.getAsVariableArrayType(TypeToCheck);
273 // Check the VLA sizes for validity.
277 State = checkVLA(C, State, VLA, ArraySize);
281 auto ArraySizeNL = ArraySize.getAs<NonLoc>();
283 // Array size could not be determined but state may contain new assumptions.
284 C.addTransition(State);
288 // VLASizeChecker is responsible for defining the extent of the array being
289 // declared. We do this by multiplying the array length by the element size,
290 // then matching that with the array region's extent symbol.
293 // Assume that the array's size matches the region size.
294 const LocationContext *LC = C.getLocationContext();
295 DefinedOrUnknownSVal DynSize =
296 getDynamicSize(State, State->getRegion(VD, LC), SVB);
298 DefinedOrUnknownSVal SizeIsKnown = SVB.evalEQ(State, DynSize, *ArraySizeNL);
299 State = State->assume(SizeIsKnown, true);
301 // Assume should not fail at this point.
305 // Remember our assumptions!
306 C.addTransition(State);
309 void VLASizeChecker::checkPreStmt(const UnaryExprOrTypeTraitExpr *UETTE,
310 CheckerContext &C) const {
311 // Want to check for sizeof.
312 if (UETTE->getKind() != UETT_SizeOf)
315 // Ensure a type argument.
316 if (!UETTE->isArgumentType())
319 const VariableArrayType *VLA = C.getASTContext().getAsVariableArrayType(
320 UETTE->getTypeOfArgument().getCanonicalType());
321 // Ensure that the type is a VLA.
325 ProgramStateRef State = C.getState();
327 State = checkVLA(C, State, VLA, ArraySize);
331 C.addTransition(State);
334 void ento::registerVLASizeChecker(CheckerManager &mgr) {
335 mgr.registerChecker<VLASizeChecker>();
338 bool ento::shouldRegisterVLASizeChecker(const CheckerManager &mgr) {