#include "clang/AST/CharUnits.h"
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Checkers/Taint.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
using namespace ento;
using namespace taint;
namespace {
class VLASizeChecker
: public Checker<check::PreStmt<DeclStmt>,
check::PreStmt<UnaryExprOrTypeTraitExpr>> {
mutable std::unique_ptr<BugType> BT;
enum VLASize_Kind {
VLA_Garbage,
VLA_Zero,
VLA_Tainted,
VLA_Negative,
VLA_Overflow
};
ProgramStateRef checkVLA(CheckerContext &C, ProgramStateRef State,
const VariableArrayType *VLA, SVal &ArraySize) const;
ProgramStateRef checkVLAIndexSize(CheckerContext &C, ProgramStateRef State,
const Expr *SizeE) const;
void reportBug(VLASize_Kind Kind, const Expr *SizeE, ProgramStateRef State,
CheckerContext &C,
std::unique_ptr<BugReporterVisitor> Visitor = nullptr) const;
public:
void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
void checkPreStmt(const UnaryExprOrTypeTraitExpr *UETTE,
CheckerContext &C) const;
};
}
ProgramStateRef VLASizeChecker::checkVLA(CheckerContext &C,
ProgramStateRef State,
const VariableArrayType *VLA,
SVal &ArraySize) const {
assert(VLA && "Function should be called with non-null VLA argument.");
const VariableArrayType *VLALast = nullptr;
llvm::SmallVector<const Expr *, 2> VLASizes;
while (VLA) {
const Expr *SizeE = VLA->getSizeExpr();
State = checkVLAIndexSize(C, State, SizeE);
if (!State)
return nullptr;
VLASizes.push_back(SizeE);
VLALast = VLA;
VLA = C.getASTContext().getAsVariableArrayType(VLA->getElementType());
};
assert(VLALast &&
"Array should have at least one variably-modified dimension.");
ASTContext &Ctx = C.getASTContext();
SValBuilder &SVB = C.getSValBuilder();
CanQualType SizeTy = Ctx.getSizeType();
uint64_t SizeMax =
SVB.getBasicValueFactory().getMaxValue(SizeTy).getZExtValue();
CharUnits EleSize = Ctx.getTypeSizeInChars(VLALast->getElementType());
NonLoc ArrSize =
SVB.makeIntVal(EleSize.getQuantity(), SizeTy).castAs<NonLoc>();
uint64_t KnownSize = 0;
if (const llvm::APSInt *KV = SVB.getKnownValue(State, ArrSize))
KnownSize = KV->getZExtValue();
for (const Expr *SizeE : VLASizes) {
auto SizeD = C.getSVal(SizeE).castAs<DefinedSVal>();
NonLoc IndexLength =
SVB.evalCast(SizeD, SizeTy, SizeE->getType()).castAs<NonLoc>();
SVal Mul = SVB.evalBinOpNN(State, BO_Mul, ArrSize, IndexLength, SizeTy);
if (auto MulNonLoc = Mul.getAs<NonLoc>())
ArrSize = *MulNonLoc;
else
return State;
if (const llvm::APSInt *IndexLVal = SVB.getKnownValue(State, IndexLength)) {
uint64_t IndexL = IndexLVal->getZExtValue();
if (IndexL == 0)
return nullptr;
if (KnownSize <= SizeMax / IndexL) {
KnownSize *= IndexL;
} else {
reportBug(VLA_Overflow, SizeE, State, C);
return nullptr;
}
} else {
KnownSize = 0;
}
}
ArraySize = ArrSize;
return State;
}
ProgramStateRef VLASizeChecker::checkVLAIndexSize(CheckerContext &C,
ProgramStateRef State,
const Expr *SizeE) const {
SVal SizeV = C.getSVal(SizeE);
if (SizeV.isUndef()) {
reportBug(VLA_Garbage, SizeE, State, C);
return nullptr;
}
if (SizeV.isUnknown())
return nullptr;
if (isTainted(State, SizeV)) {
reportBug(VLA_Tainted, SizeE, nullptr, C,
std::make_unique<TaintBugVisitor>(SizeV));
return nullptr;
}
DefinedSVal SizeD = SizeV.castAs<DefinedSVal>();
ProgramStateRef StateNotZero, StateZero;
std::tie(StateNotZero, StateZero) = State->assume(SizeD);
if (StateZero && !StateNotZero) {
reportBug(VLA_Zero, SizeE, StateZero, C);
return nullptr;
}
State = StateNotZero;
SValBuilder &SVB = C.getSValBuilder();
QualType SizeTy = SizeE->getType();
DefinedOrUnknownSVal Zero = SVB.makeZeroVal(SizeTy);
SVal LessThanZeroVal = SVB.evalBinOp(State, BO_LT, SizeD, Zero, SizeTy);
if (Optional<DefinedSVal> LessThanZeroDVal =
LessThanZeroVal.getAs<DefinedSVal>()) {
ConstraintManager &CM = C.getConstraintManager();
ProgramStateRef StatePos, StateNeg;
std::tie(StateNeg, StatePos) = CM.assumeDual(State, *LessThanZeroDVal);
if (StateNeg && !StatePos) {
reportBug(VLA_Negative, SizeE, State, C);
return nullptr;
}
State = StatePos;
}
return State;
}
void VLASizeChecker::reportBug(
VLASize_Kind Kind, const Expr *SizeE, ProgramStateRef State,
CheckerContext &C, std::unique_ptr<BugReporterVisitor> Visitor) const {
ExplodedNode *N = C.generateErrorNode(State);
if (!N)
return;
if (!BT)
BT.reset(new BuiltinBug(
this, "Dangerous variable-length array (VLA) declaration"));
SmallString<256> buf;
llvm::raw_svector_ostream os(buf);
os << "Declared variable-length array (VLA) ";
switch (Kind) {
case VLA_Garbage:
os << "uses a garbage value as its size";
break;
case VLA_Zero:
os << "has zero size";
break;
case VLA_Tainted:
os << "has tainted size";
break;
case VLA_Negative:
os << "has negative size";
break;
case VLA_Overflow:
os << "has too large size";
break;
}
auto report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
report->addVisitor(std::move(Visitor));
report->addRange(SizeE->getSourceRange());
bugreporter::trackExpressionValue(N, SizeE, *report);
C.emitReport(std::move(report));
}
void VLASizeChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
if (!DS->isSingleDecl())
return;
ASTContext &Ctx = C.getASTContext();
SValBuilder &SVB = C.getSValBuilder();
ProgramStateRef State = C.getState();
QualType TypeToCheck;
const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
if (VD)
TypeToCheck = VD->getType().getCanonicalType();
else if (const auto *TND = dyn_cast<TypedefNameDecl>(DS->getSingleDecl()))
TypeToCheck = TND->getUnderlyingType().getCanonicalType();
else
return;
const VariableArrayType *VLA = Ctx.getAsVariableArrayType(TypeToCheck);
if (!VLA)
return;
SVal ArraySize;
State = checkVLA(C, State, VLA, ArraySize);
if (!State)
return;
if (!isa<NonLoc>(ArraySize)) {
C.addTransition(State);
return;
}
if (VD) {
State =
setDynamicExtent(State, State->getRegion(VD, C.getLocationContext()),
ArraySize.castAs<NonLoc>(), SVB);
}
C.addTransition(State);
}
void VLASizeChecker::checkPreStmt(const UnaryExprOrTypeTraitExpr *UETTE,
CheckerContext &C) const {
if (UETTE->getKind() != UETT_SizeOf)
return;
if (!UETTE->isArgumentType())
return;
const VariableArrayType *VLA = C.getASTContext().getAsVariableArrayType(
UETTE->getTypeOfArgument().getCanonicalType());
if (!VLA)
return;
ProgramStateRef State = C.getState();
SVal ArraySize;
State = checkVLA(C, State, VLA, ArraySize);
if (!State)
return;
C.addTransition(State);
}
void ento::registerVLASizeChecker(CheckerManager &mgr) {
mgr.registerChecker<VLASizeChecker>();
}
bool ento::shouldRegisterVLASizeChecker(const CheckerManager &mgr) {
return true;
}