xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp (revision 601687bf731a33364a7de0ece7acd1c17c9dd60d)
1 //=== VLASizeChecker.cpp - Undefined dereference checker --------*- 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 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.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "Taint.h"
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"
27 
28 using namespace clang;
29 using namespace ento;
30 using namespace taint;
31 
32 namespace {
33 class VLASizeChecker : public Checker< check::PreStmt<DeclStmt> > {
34   mutable std::unique_ptr<BugType> BT;
35   enum VLASize_Kind { VLA_Garbage, VLA_Zero, VLA_Tainted, VLA_Negative };
36 
37   void reportBug(VLASize_Kind Kind, const Expr *SizeE, ProgramStateRef State,
38                  CheckerContext &C,
39                  std::unique_ptr<BugReporterVisitor> Visitor = nullptr) const;
40 
41 public:
42   void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
43 };
44 } // end anonymous namespace
45 
46 void VLASizeChecker::reportBug(
47     VLASize_Kind Kind, const Expr *SizeE, ProgramStateRef State,
48     CheckerContext &C, std::unique_ptr<BugReporterVisitor> Visitor) const {
49   // Generate an error node.
50   ExplodedNode *N = C.generateErrorNode(State);
51   if (!N)
52     return;
53 
54   if (!BT)
55     BT.reset(new BuiltinBug(
56         this, "Dangerous variable-length array (VLA) declaration"));
57 
58   SmallString<256> buf;
59   llvm::raw_svector_ostream os(buf);
60   os << "Declared variable-length array (VLA) ";
61   switch (Kind) {
62   case VLA_Garbage:
63     os << "uses a garbage value as its size";
64     break;
65   case VLA_Zero:
66     os << "has zero size";
67     break;
68   case VLA_Tainted:
69     os << "has tainted size";
70     break;
71   case VLA_Negative:
72     os << "has negative size";
73     break;
74   }
75 
76   auto report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
77   report->addVisitor(std::move(Visitor));
78   report->addRange(SizeE->getSourceRange());
79   bugreporter::trackExpressionValue(N, SizeE, *report);
80   C.emitReport(std::move(report));
81 }
82 
83 void VLASizeChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
84   if (!DS->isSingleDecl())
85     return;
86 
87   const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
88   if (!VD)
89     return;
90 
91   ASTContext &Ctx = C.getASTContext();
92   const VariableArrayType *VLA = Ctx.getAsVariableArrayType(VD->getType());
93   if (!VLA)
94     return;
95 
96   // FIXME: Handle multi-dimensional VLAs.
97   const Expr *SE = VLA->getSizeExpr();
98   ProgramStateRef state = C.getState();
99   SVal sizeV = C.getSVal(SE);
100 
101   if (sizeV.isUndef()) {
102     reportBug(VLA_Garbage, SE, state, C);
103     return;
104   }
105 
106   // See if the size value is known. It can't be undefined because we would have
107   // warned about that already.
108   if (sizeV.isUnknown())
109     return;
110 
111   // Check if the size is tainted.
112   if (isTainted(state, sizeV)) {
113     reportBug(VLA_Tainted, SE, nullptr, C,
114               std::make_unique<TaintBugVisitor>(sizeV));
115     return;
116   }
117 
118   // Check if the size is zero.
119   DefinedSVal sizeD = sizeV.castAs<DefinedSVal>();
120 
121   ProgramStateRef stateNotZero, stateZero;
122   std::tie(stateNotZero, stateZero) = state->assume(sizeD);
123 
124   if (stateZero && !stateNotZero) {
125     reportBug(VLA_Zero, SE, stateZero, C);
126     return;
127   }
128 
129   // From this point on, assume that the size is not zero.
130   state = stateNotZero;
131 
132   // VLASizeChecker is responsible for defining the extent of the array being
133   // declared. We do this by multiplying the array length by the element size,
134   // then matching that with the array region's extent symbol.
135 
136   // Check if the size is negative.
137   SValBuilder &svalBuilder = C.getSValBuilder();
138 
139   QualType Ty = SE->getType();
140   DefinedOrUnknownSVal Zero = svalBuilder.makeZeroVal(Ty);
141 
142   SVal LessThanZeroVal = svalBuilder.evalBinOp(state, BO_LT, sizeD, Zero, Ty);
143   if (Optional<DefinedSVal> LessThanZeroDVal =
144         LessThanZeroVal.getAs<DefinedSVal>()) {
145     ConstraintManager &CM = C.getConstraintManager();
146     ProgramStateRef StatePos, StateNeg;
147 
148     std::tie(StateNeg, StatePos) = CM.assumeDual(state, *LessThanZeroDVal);
149     if (StateNeg && !StatePos) {
150       reportBug(VLA_Negative, SE, state, C);
151       return;
152     }
153     state = StatePos;
154   }
155 
156   // Convert the array length to size_t.
157   QualType SizeTy = Ctx.getSizeType();
158   NonLoc ArrayLength =
159       svalBuilder.evalCast(sizeD, SizeTy, SE->getType()).castAs<NonLoc>();
160 
161   // Get the element size.
162   CharUnits EleSize = Ctx.getTypeSizeInChars(VLA->getElementType());
163   SVal EleSizeVal = svalBuilder.makeIntVal(EleSize.getQuantity(), SizeTy);
164 
165   // Multiply the array length by the element size.
166   SVal ArraySizeVal = svalBuilder.evalBinOpNN(
167       state, BO_Mul, ArrayLength, EleSizeVal.castAs<NonLoc>(), SizeTy);
168 
169   // Finally, assume that the array's size matches the given size.
170   const LocationContext *LC = C.getLocationContext();
171   DefinedOrUnknownSVal DynSize =
172       getDynamicSize(state, state->getRegion(VD, LC), svalBuilder);
173 
174   DefinedOrUnknownSVal ArraySize = ArraySizeVal.castAs<DefinedOrUnknownSVal>();
175   DefinedOrUnknownSVal sizeIsKnown =
176       svalBuilder.evalEQ(state, DynSize, ArraySize);
177   state = state->assume(sizeIsKnown, true);
178 
179   // Assume should not fail at this point.
180   assert(state);
181 
182   // Remember our assumptions!
183   C.addTransition(state);
184 }
185 
186 void ento::registerVLASizeChecker(CheckerManager &mgr) {
187   mgr.registerChecker<VLASizeChecker>();
188 }
189 
190 bool ento::shouldRegisterVLASizeChecker(const LangOptions &LO) {
191   return true;
192 }
193