#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
#include "clang/AST/Expr.h"
#include "clang/Basic/LLVM.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
REGISTER_MAP_WITH_PROGRAMSTATE(DynamicExtentMap, const clang::ento::MemRegion *,
clang::ento::DefinedOrUnknownSVal)
namespace clang {
namespace ento {
DefinedOrUnknownSVal getDynamicExtent(ProgramStateRef State,
const MemRegion *MR, SValBuilder &SVB) {
MR = MR->StripCasts();
if (const DefinedOrUnknownSVal *Size = State->get<DynamicExtentMap>(MR))
return *Size;
return MR->getMemRegionManager().getStaticSize(MR, SVB);
}
DefinedOrUnknownSVal getElementExtent(QualType Ty, SValBuilder &SVB) {
return SVB.makeIntVal(SVB.getContext().getTypeSizeInChars(Ty).getQuantity(),
SVB.getArrayIndexType());
}
DefinedOrUnknownSVal getDynamicElementCount(ProgramStateRef State,
const MemRegion *MR,
SValBuilder &SVB,
QualType ElementTy) {
MR = MR->StripCasts();
DefinedOrUnknownSVal Size = getDynamicExtent(State, MR, SVB);
SVal ElementSize = getElementExtent(ElementTy, SVB);
SVal ElementCount =
SVB.evalBinOp(State, BO_Div, Size, ElementSize, SVB.getArrayIndexType());
return ElementCount.castAs<DefinedOrUnknownSVal>();
}
SVal getDynamicExtentWithOffset(ProgramStateRef State, SVal BufV) {
SValBuilder &SvalBuilder = State->getStateManager().getSValBuilder();
const MemRegion *MRegion = BufV.getAsRegion();
if (!MRegion)
return UnknownVal();
RegionOffset Offset = MRegion->getAsOffset();
if (Offset.hasSymbolicOffset())
return UnknownVal();
const MemRegion *BaseRegion = MRegion->getBaseRegion();
if (!BaseRegion)
return UnknownVal();
NonLoc OffsetInBytes = SvalBuilder.makeArrayIndex(
Offset.getOffset() /
MRegion->getMemRegionManager().getContext().getCharWidth());
DefinedOrUnknownSVal ExtentInBytes =
getDynamicExtent(State, BaseRegion, SvalBuilder);
return SvalBuilder.evalBinOp(State, BinaryOperator::Opcode::BO_Sub,
ExtentInBytes, OffsetInBytes,
SvalBuilder.getArrayIndexType());
}
ProgramStateRef setDynamicExtent(ProgramStateRef State, const MemRegion *MR,
DefinedOrUnknownSVal Size, SValBuilder &SVB) {
MR = MR->StripCasts();
if (Size.isUnknown())
return State;
return State->set<DynamicExtentMap>(MR->StripCasts(), Size);
}
} }