#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"
using namespace clang;
using namespace ento;
namespace {
class BoolAssignmentChecker : public Checker< check::Bind > {
mutable std::unique_ptr<BuiltinBug> BT;
void emitReport(ProgramStateRef state, CheckerContext &C,
bool IsTainted = false) const;
public:
void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
};
}
void BoolAssignmentChecker::emitReport(ProgramStateRef state, CheckerContext &C,
bool IsTainted) const {
if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) {
if (!BT)
BT.reset(new BuiltinBug(this, "Assignment of a non-Boolean value"));
StringRef Msg = IsTainted ? "Might assign a tainted non-Boolean value"
: "Assignment of a non-Boolean value";
C.emitReport(std::make_unique<PathSensitiveBugReport>(*BT, Msg, N));
}
}
static bool isBooleanType(QualType Ty) {
if (Ty->isBooleanType()) return true;
if (const TypedefType *TT = Ty->getAs<TypedefType>())
return TT->getDecl()->getName() == "BOOL" || TT->getDecl()->getName() == "_Bool" || TT->getDecl()->getName() == "Boolean";
return false;
}
void BoolAssignmentChecker::checkBind(SVal loc, SVal val, const Stmt *S,
CheckerContext &C) const {
const TypedValueRegion *TR =
dyn_cast_or_null<TypedValueRegion>(loc.getAsRegion());
if (!TR)
return;
QualType valTy = TR->getValueType();
if (!isBooleanType(valTy))
return;
Optional<NonLoc> NV = val.getAs<NonLoc>();
if (!NV)
return;
ProgramStateRef state = C.getState();
SValBuilder &svalBuilder = C.getSValBuilder();
BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
ConstraintManager &CM = C.getConstraintManager();
llvm::APSInt Zero = BVF.getValue(0, valTy);
llvm::APSInt One = BVF.getValue(1, valTy);
ProgramStateRef StIn, StOut;
std::tie(StIn, StOut) = CM.assumeInclusiveRangeDual(state, *NV, Zero, One);
if (!StIn)
emitReport(StOut, C);
if (StIn && StOut && taint::isTainted(state, *NV))
emitReport(StOut, C, true);
}
void ento::registerBoolAssignmentChecker(CheckerManager &mgr) {
mgr.registerChecker<BoolAssignmentChecker>();
}
bool ento::shouldRegisterBoolAssignmentChecker(const CheckerManager &mgr) {
return true;
}