Page MenuHomePhabricator

No OneTemporary

File Metadata

Created
Tue, Oct 15, 9:31 PM
Index: cfe/trunk/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
===================================================================
--- cfe/trunk/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp (revision 290504)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp (revision 290505)
@@ -1,335 +1,347 @@
//== SimpleConstraintManager.cpp --------------------------------*- C++ -*--==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines SimpleConstraintManager, a class that holds code shared
// between BasicConstraintManager and RangeConstraintManager.
//
//===----------------------------------------------------------------------===//
#include "SimpleConstraintManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
namespace clang {
namespace ento {
SimpleConstraintManager::~SimpleConstraintManager() {}
bool SimpleConstraintManager::canReasonAbout(SVal X) const {
Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
if (SymVal && SymVal->isExpression()) {
const SymExpr *SE = SymVal->getSymbol();
if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) {
switch (SIE->getOpcode()) {
// We don't reason yet about bitwise-constraints on symbolic values.
case BO_And:
case BO_Or:
case BO_Xor:
return false;
// We don't reason yet about these arithmetic constraints on
// symbolic values.
case BO_Mul:
case BO_Div:
case BO_Rem:
case BO_Shl:
case BO_Shr:
return false;
// All other cases.
default:
return true;
}
}
if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(SE)) {
if (BinaryOperator::isComparisonOp(SSE->getOpcode())) {
// We handle Loc <> Loc comparisons, but not (yet) NonLoc <> NonLoc.
if (Loc::isLocType(SSE->getLHS()->getType())) {
assert(Loc::isLocType(SSE->getRHS()->getType()));
return true;
}
}
}
return false;
}
return true;
}
ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef State,
DefinedSVal Cond,
bool Assumption) {
// If we have a Loc value, cast it to a bool NonLoc first.
if (Optional<Loc> LV = Cond.getAs<Loc>()) {
SValBuilder &SVB = State->getStateManager().getSValBuilder();
QualType T;
const MemRegion *MR = LV->getAsRegion();
if (const TypedRegion *TR = dyn_cast_or_null<TypedRegion>(MR))
T = TR->getLocationType();
else
T = SVB.getContext().VoidPtrTy;
Cond = SVB.evalCast(*LV, SVB.getContext().BoolTy, T).castAs<DefinedSVal>();
}
return assume(State, Cond.castAs<NonLoc>(), Assumption);
}
ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef State,
NonLoc Cond, bool Assumption) {
State = assumeAux(State, Cond, Assumption);
if (NotifyAssumeClients && SU)
return SU->processAssume(State, Cond, Assumption);
return State;
}
ProgramStateRef
SimpleConstraintManager::assumeAuxForSymbol(ProgramStateRef State,
SymbolRef Sym, bool Assumption) {
BasicValueFactory &BVF = getBasicVals();
QualType T = Sym->getType();
// None of the constraint solvers currently support non-integer types.
if (!T->isIntegralOrEnumerationType())
return State;
const llvm::APSInt &zero = BVF.getValue(0, T);
if (Assumption)
return assumeSymNE(State, Sym, zero, zero);
else
return assumeSymEQ(State, Sym, zero, zero);
}
ProgramStateRef SimpleConstraintManager::assumeAux(ProgramStateRef State,
NonLoc Cond,
bool Assumption) {
// We cannot reason about SymSymExprs, and can only reason about some
// SymIntExprs.
if (!canReasonAbout(Cond)) {
// Just add the constraint to the expression without trying to simplify.
SymbolRef Sym = Cond.getAsSymExpr();
return assumeAuxForSymbol(State, Sym, Assumption);
}
switch (Cond.getSubKind()) {
default:
llvm_unreachable("'Assume' not implemented for this NonLoc");
case nonloc::SymbolValKind: {
nonloc::SymbolVal SV = Cond.castAs<nonloc::SymbolVal>();
SymbolRef Sym = SV.getSymbol();
assert(Sym);
// Handle SymbolData.
if (!SV.isExpression()) {
return assumeAuxForSymbol(State, Sym, Assumption);
// Handle symbolic expression.
} else if (const SymIntExpr *SE = dyn_cast<SymIntExpr>(Sym)) {
// We can only simplify expressions whose RHS is an integer.
BinaryOperator::Opcode Op = SE->getOpcode();
if (BinaryOperator::isComparisonOp(Op)) {
if (!Assumption)
Op = BinaryOperator::negateComparisonOp(Op);
return assumeSymRel(State, SE->getLHS(), Op, SE->getRHS());
}
} else if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(Sym)) {
// Translate "a != b" to "(b - a) != 0".
// We invert the order of the operands as a heuristic for how loop
// conditions are usually written ("begin != end") as compared to length
// calculations ("end - begin"). The more correct thing to do would be to
// canonicalize "a - b" and "b - a", which would allow us to treat
// "a != b" and "b != a" the same.
SymbolManager &SymMgr = getSymbolManager();
BinaryOperator::Opcode Op = SSE->getOpcode();
assert(BinaryOperator::isComparisonOp(Op));
// For now, we only support comparing pointers.
assert(Loc::isLocType(SSE->getLHS()->getType()));
assert(Loc::isLocType(SSE->getRHS()->getType()));
QualType DiffTy = SymMgr.getContext().getPointerDiffType();
SymbolRef Subtraction =
SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub, SSE->getLHS(), DiffTy);
const llvm::APSInt &Zero = getBasicVals().getValue(0, DiffTy);
Op = BinaryOperator::reverseComparisonOp(Op);
if (!Assumption)
Op = BinaryOperator::negateComparisonOp(Op);
return assumeSymRel(State, Subtraction, Op, Zero);
}
// If we get here, there's nothing else we can do but treat the symbol as
// opaque.
return assumeAuxForSymbol(State, Sym, Assumption);
}
case nonloc::ConcreteIntKind: {
bool b = Cond.castAs<nonloc::ConcreteInt>().getValue() != 0;
bool isFeasible = b ? Assumption : !Assumption;
return isFeasible ? State : nullptr;
}
case nonloc::PointerToMemberKind: {
bool IsNull = !Cond.castAs<nonloc::PointerToMember>().isNullMemberPointer();
bool IsFeasible = IsNull ? Assumption : !Assumption;
return IsFeasible ? State : nullptr;
}
case nonloc::LocAsIntegerKind:
return assume(State, Cond.castAs<nonloc::LocAsInteger>().getLoc(),
Assumption);
} // end switch
}
ProgramStateRef SimpleConstraintManager::assumeInclusiveRange(
ProgramStateRef State, NonLoc Value, const llvm::APSInt &From,
const llvm::APSInt &To, bool InRange) {
assert(From.isUnsigned() == To.isUnsigned() &&
From.getBitWidth() == To.getBitWidth() &&
"Values should have same types!");
if (!canReasonAbout(Value)) {
// Just add the constraint to the expression without trying to simplify.
SymbolRef Sym = Value.getAsSymExpr();
assert(Sym);
return assumeSymWithinInclusiveRange(State, Sym, From, To, InRange);
}
switch (Value.getSubKind()) {
default:
llvm_unreachable("'assumeInclusiveRange' is not implemented"
"for this NonLoc");
case nonloc::LocAsIntegerKind:
case nonloc::SymbolValKind: {
if (SymbolRef Sym = Value.getAsSymbol())
return assumeSymWithinInclusiveRange(State, Sym, From, To, InRange);
return State;
} // end switch
case nonloc::ConcreteIntKind: {
const llvm::APSInt &IntVal = Value.castAs<nonloc::ConcreteInt>().getValue();
bool IsInRange = IntVal >= From && IntVal <= To;
bool isFeasible = (IsInRange == InRange);
return isFeasible ? State : nullptr;
}
} // end switch
}
static void computeAdjustment(SymbolRef &Sym, llvm::APSInt &Adjustment) {
// Is it a "($sym+constant1)" expression?
if (const SymIntExpr *SE = dyn_cast<SymIntExpr>(Sym)) {
BinaryOperator::Opcode Op = SE->getOpcode();
if (Op == BO_Add || Op == BO_Sub) {
Sym = SE->getLHS();
Adjustment = APSIntType(Adjustment).convert(SE->getRHS());
// Don't forget to negate the adjustment if it's being subtracted.
// This should happen /after/ promotion, in case the value being
// subtracted is, say, CHAR_MIN, and the promoted type is 'int'.
if (Op == BO_Sub)
Adjustment = -Adjustment;
}
}
}
ProgramStateRef SimpleConstraintManager::assumeSymRel(ProgramStateRef State,
const SymExpr *LHS,
BinaryOperator::Opcode Op,
const llvm::APSInt &Int) {
assert(BinaryOperator::isComparisonOp(Op) &&
"Non-comparison ops should be rewritten as comparisons to zero.");
+ SymbolRef Sym = LHS;
+
+ // Simplification: translate an assume of a constraint of the form
+ // "(exp comparison_op expr) != 0" to true into an assume of
+ // "exp comparison_op expr" to true. (And similarly, an assume of the form
+ // "(exp comparison_op expr) == 0" to true into an assume of
+ // "exp comparison_op expr" to false.)
+ if (Int == 0 && (Op == BO_EQ || Op == BO_NE)) {
+ if (const BinarySymExpr *SE = dyn_cast<BinarySymExpr>(Sym))
+ if (BinaryOperator::isComparisonOp(SE->getOpcode()))
+ return assume(State, nonloc::SymbolVal(Sym), (Op == BO_NE ? true : false));
+ }
+
// Get the type used for calculating wraparound.
BasicValueFactory &BVF = getBasicVals();
APSIntType WraparoundType = BVF.getAPSIntType(LHS->getType());
// We only handle simple comparisons of the form "$sym == constant"
// or "($sym+constant1) == constant2".
// The adjustment is "constant1" in the above expression. It's used to
// "slide" the solution range around for modular arithmetic. For example,
// x < 4 has the solution [0, 3]. x+2 < 4 has the solution [0-2, 3-2], which
// in modular arithmetic is [0, 1] U [UINT_MAX-1, UINT_MAX]. It's up to
// the subclasses of SimpleConstraintManager to handle the adjustment.
- SymbolRef Sym = LHS;
llvm::APSInt Adjustment = WraparoundType.getZeroValue();
computeAdjustment(Sym, Adjustment);
// Convert the right-hand side integer as necessary.
APSIntType ComparisonType = std::max(WraparoundType, APSIntType(Int));
llvm::APSInt ConvertedInt = ComparisonType.convert(Int);
// Prefer unsigned comparisons.
if (ComparisonType.getBitWidth() == WraparoundType.getBitWidth() &&
ComparisonType.isUnsigned() && !WraparoundType.isUnsigned())
Adjustment.setIsSigned(false);
switch (Op) {
default:
llvm_unreachable("invalid operation not caught by assertion above");
case BO_EQ:
return assumeSymEQ(State, Sym, ConvertedInt, Adjustment);
case BO_NE:
return assumeSymNE(State, Sym, ConvertedInt, Adjustment);
case BO_GT:
return assumeSymGT(State, Sym, ConvertedInt, Adjustment);
case BO_GE:
return assumeSymGE(State, Sym, ConvertedInt, Adjustment);
case BO_LT:
return assumeSymLT(State, Sym, ConvertedInt, Adjustment);
case BO_LE:
return assumeSymLE(State, Sym, ConvertedInt, Adjustment);
} // end switch
}
ProgramStateRef SimpleConstraintManager::assumeSymWithinInclusiveRange(
ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
const llvm::APSInt &To, bool InRange) {
// Get the type used for calculating wraparound.
BasicValueFactory &BVF = getBasicVals();
APSIntType WraparoundType = BVF.getAPSIntType(Sym->getType());
llvm::APSInt Adjustment = WraparoundType.getZeroValue();
SymbolRef AdjustedSym = Sym;
computeAdjustment(AdjustedSym, Adjustment);
// Convert the right-hand side integer as necessary.
APSIntType ComparisonType = std::max(WraparoundType, APSIntType(From));
llvm::APSInt ConvertedFrom = ComparisonType.convert(From);
llvm::APSInt ConvertedTo = ComparisonType.convert(To);
// Prefer unsigned comparisons.
if (ComparisonType.getBitWidth() == WraparoundType.getBitWidth() &&
ComparisonType.isUnsigned() && !WraparoundType.isUnsigned())
Adjustment.setIsSigned(false);
if (InRange)
return assumeSymbolWithinInclusiveRange(State, AdjustedSym, ConvertedFrom,
ConvertedTo, Adjustment);
return assumeSymbolOutOfInclusiveRange(State, AdjustedSym, ConvertedFrom,
ConvertedTo, Adjustment);
}
} // end of namespace ento
} // end of namespace clang
Index: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp
===================================================================
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp (revision 290504)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp (revision 290505)
@@ -1,1104 +1,1094 @@
//=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines ExprEngine's support for C expressions.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ExprCXX.h"
#include "clang/AST/DeclCXX.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
using namespace clang;
using namespace ento;
using llvm::APSInt;
void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
ExplodedNode *Pred,
ExplodedNodeSet &Dst) {
Expr *LHS = B->getLHS()->IgnoreParens();
Expr *RHS = B->getRHS()->IgnoreParens();
// FIXME: Prechecks eventually go in ::Visit().
ExplodedNodeSet CheckedSet;
ExplodedNodeSet Tmp2;
getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
// With both the LHS and RHS evaluated, process the operation itself.
for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
it != ei; ++it) {
ProgramStateRef state = (*it)->getState();
const LocationContext *LCtx = (*it)->getLocationContext();
SVal LeftV = state->getSVal(LHS, LCtx);
SVal RightV = state->getSVal(RHS, LCtx);
BinaryOperator::Opcode Op = B->getOpcode();
if (Op == BO_Assign) {
// EXPERIMENTAL: "Conjured" symbols.
// FIXME: Handle structs.
if (RightV.isUnknown()) {
unsigned Count = currBldrCtx->blockCount();
RightV = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx,
Count);
}
// Simulate the effects of a "store": bind the value of the RHS
// to the L-Value represented by the LHS.
SVal ExprVal = B->isGLValue() ? LeftV : RightV;
evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
LeftV, RightV);
continue;
}
if (!B->isAssignmentOp()) {
StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx);
if (B->isAdditiveOp()) {
// If one of the operands is a location, conjure a symbol for the other
// one (offset) if it's unknown so that memory arithmetic always
// results in an ElementRegion.
// TODO: This can be removed after we enable history tracking with
// SymSymExpr.
unsigned Count = currBldrCtx->blockCount();
if (LeftV.getAs<Loc>() &&
RHS->getType()->isIntegralOrEnumerationType() &&
RightV.isUnknown()) {
RightV = svalBuilder.conjureSymbolVal(RHS, LCtx, RHS->getType(),
Count);
}
if (RightV.getAs<Loc>() &&
LHS->getType()->isIntegralOrEnumerationType() &&
LeftV.isUnknown()) {
LeftV = svalBuilder.conjureSymbolVal(LHS, LCtx, LHS->getType(),
Count);
}
}
// Although we don't yet model pointers-to-members, we do need to make
// sure that the members of temporaries have a valid 'this' pointer for
// other checks.
if (B->getOpcode() == BO_PtrMemD)
state = createTemporaryRegionIfNeeded(state, LCtx, LHS);
// Process non-assignments except commas or short-circuited
// logical expressions (LAnd and LOr).
SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
if (Result.isUnknown()) {
Bldr.generateNode(B, *it, state);
continue;
}
state = state->BindExpr(B, LCtx, Result);
Bldr.generateNode(B, *it, state);
continue;
}
assert (B->isCompoundAssignmentOp());
switch (Op) {
default:
llvm_unreachable("Invalid opcode for compound assignment.");
case BO_MulAssign: Op = BO_Mul; break;
case BO_DivAssign: Op = BO_Div; break;
case BO_RemAssign: Op = BO_Rem; break;
case BO_AddAssign: Op = BO_Add; break;
case BO_SubAssign: Op = BO_Sub; break;
case BO_ShlAssign: Op = BO_Shl; break;
case BO_ShrAssign: Op = BO_Shr; break;
case BO_AndAssign: Op = BO_And; break;
case BO_XorAssign: Op = BO_Xor; break;
case BO_OrAssign: Op = BO_Or; break;
}
// Perform a load (the LHS). This performs the checks for
// null dereferences, and so on.
ExplodedNodeSet Tmp;
SVal location = LeftV;
evalLoad(Tmp, B, LHS, *it, state, location);
for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
++I) {
state = (*I)->getState();
const LocationContext *LCtx = (*I)->getLocationContext();
SVal V = state->getSVal(LHS, LCtx);
// Get the computation type.
QualType CTy =
cast<CompoundAssignOperator>(B)->getComputationResultType();
CTy = getContext().getCanonicalType(CTy);
QualType CLHSTy =
cast<CompoundAssignOperator>(B)->getComputationLHSType();
CLHSTy = getContext().getCanonicalType(CLHSTy);
QualType LTy = getContext().getCanonicalType(LHS->getType());
// Promote LHS.
V = svalBuilder.evalCast(V, CLHSTy, LTy);
// Compute the result of the operation.
SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
B->getType(), CTy);
// EXPERIMENTAL: "Conjured" symbols.
// FIXME: Handle structs.
SVal LHSVal;
if (Result.isUnknown()) {
// The symbolic value is actually for the type of the left-hand side
// expression, not the computation type, as this is the value the
// LValue on the LHS will bind to.
LHSVal = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx, LTy,
currBldrCtx->blockCount());
// However, we need to convert the symbol to the computation type.
Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
}
else {
// The left-hand side may bind to a different value then the
// computation type.
LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
}
// In C++, assignment and compound assignment operators return an
// lvalue.
if (B->isGLValue())
state = state->BindExpr(B, LCtx, location);
else
state = state->BindExpr(B, LCtx, Result);
evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
}
}
// FIXME: postvisits eventually go in ::Visit()
getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
}
void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
ExplodedNodeSet &Dst) {
CanQualType T = getContext().getCanonicalType(BE->getType());
const BlockDecl *BD = BE->getBlockDecl();
// Get the value of the block itself.
SVal V = svalBuilder.getBlockPointer(BD, T,
Pred->getLocationContext(),
currBldrCtx->blockCount());
ProgramStateRef State = Pred->getState();
// If we created a new MemRegion for the block, we should explicitly bind
// the captured variables.
if (const BlockDataRegion *BDR =
dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
E = BDR->referenced_vars_end();
auto CI = BD->capture_begin();
auto CE = BD->capture_end();
for (; I != E; ++I) {
const VarRegion *capturedR = I.getCapturedRegion();
const VarRegion *originalR = I.getOriginalRegion();
// If the capture had a copy expression, use the result of evaluating
// that expression, otherwise use the original value.
// We rely on the invariant that the block declaration's capture variables
// are a prefix of the BlockDataRegion's referenced vars (which may include
// referenced globals, etc.) to enable fast lookup of the capture for a
// given referenced var.
const Expr *copyExpr = nullptr;
if (CI != CE) {
assert(CI->getVariable() == capturedR->getDecl());
copyExpr = CI->getCopyExpr();
CI++;
}
if (capturedR != originalR) {
SVal originalV;
if (copyExpr) {
originalV = State->getSVal(copyExpr, Pred->getLocationContext());
} else {
originalV = State->getSVal(loc::MemRegionVal(originalR));
}
State = State->bindLoc(loc::MemRegionVal(capturedR), originalV);
}
}
}
ExplodedNodeSet Tmp;
StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
Bldr.generateNode(BE, Pred,
State->BindExpr(BE, Pred->getLocationContext(), V),
nullptr, ProgramPoint::PostLValueKind);
// FIXME: Move all post/pre visits to ::Visit().
getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
}
ProgramStateRef ExprEngine::handleLValueBitCast(
ProgramStateRef state, const Expr* Ex, const LocationContext* LCtx,
QualType T, QualType ExTy, const CastExpr* CastE, StmtNodeBuilder& Bldr,
ExplodedNode* Pred) {
// Delegate to SValBuilder to process.
SVal V = state->getSVal(Ex, LCtx);
V = svalBuilder.evalCast(V, T, ExTy);
// Negate the result if we're treating the boolean as a signed i1
if (CastE->getCastKind() == CK_BooleanToSignedIntegral)
V = evalMinus(V);
state = state->BindExpr(CastE, LCtx, V);
Bldr.generateNode(CastE, Pred, state);
return state;
}
ProgramStateRef ExprEngine::handleLVectorSplat(
ProgramStateRef state, const LocationContext* LCtx, const CastExpr* CastE,
StmtNodeBuilder &Bldr, ExplodedNode* Pred) {
// Recover some path sensitivity by conjuring a new value.
QualType resultType = CastE->getType();
if (CastE->isGLValue())
resultType = getContext().getPointerType(resultType);
SVal result = svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx,
resultType,
currBldrCtx->blockCount());
state = state->BindExpr(CastE, LCtx, result);
Bldr.generateNode(CastE, Pred, state);
return state;
}
void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
ExplodedNode *Pred, ExplodedNodeSet &Dst) {
ExplodedNodeSet dstPreStmt;
getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
if (CastE->getCastKind() == CK_LValueToRValue) {
for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
I!=E; ++I) {
ExplodedNode *subExprNode = *I;
ProgramStateRef state = subExprNode->getState();
const LocationContext *LCtx = subExprNode->getLocationContext();
evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
}
return;
}
// All other casts.
QualType T = CastE->getType();
QualType ExTy = Ex->getType();
if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
T = ExCast->getTypeAsWritten();
StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
I != E; ++I) {
Pred = *I;
ProgramStateRef state = Pred->getState();
const LocationContext *LCtx = Pred->getLocationContext();
switch (CastE->getCastKind()) {
case CK_LValueToRValue:
llvm_unreachable("LValueToRValue casts handled earlier.");
case CK_ToVoid:
continue;
// The analyzer doesn't do anything special with these casts,
// since it understands retain/release semantics already.
case CK_ARCProduceObject:
case CK_ARCConsumeObject:
case CK_ARCReclaimReturnedObject:
case CK_ARCExtendBlockObject: // Fall-through.
case CK_CopyAndAutoreleaseBlockObject:
// The analyser can ignore atomic casts for now, although some future
// checkers may want to make certain that you're not modifying the same
// value through atomic and nonatomic pointers.
case CK_AtomicToNonAtomic:
case CK_NonAtomicToAtomic:
// True no-ops.
case CK_NoOp:
case CK_ConstructorConversion:
case CK_UserDefinedConversion:
case CK_FunctionToPointerDecay:
case CK_BuiltinFnToFnPtr: {
// Copy the SVal of Ex to CastE.
ProgramStateRef state = Pred->getState();
const LocationContext *LCtx = Pred->getLocationContext();
SVal V = state->getSVal(Ex, LCtx);
state = state->BindExpr(CastE, LCtx, V);
Bldr.generateNode(CastE, Pred, state);
continue;
}
case CK_MemberPointerToBoolean:
case CK_PointerToBoolean: {
SVal V = state->getSVal(Ex, LCtx);
auto PTMSV = V.getAs<nonloc::PointerToMember>();
if (PTMSV)
V = svalBuilder.makeTruthVal(!PTMSV->isNullMemberPointer(), ExTy);
if (V.isUndef() || PTMSV) {
state = state->BindExpr(CastE, LCtx, V);
Bldr.generateNode(CastE, Pred, state);
continue;
}
// Explicitly proceed with default handler for this case cascade.
state =
handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
continue;
}
case CK_Dependent:
case CK_ArrayToPointerDecay:
case CK_BitCast:
case CK_AddressSpaceConversion:
case CK_BooleanToSignedIntegral:
case CK_NullToPointer:
case CK_IntegralToPointer:
case CK_PointerToIntegral: {
SVal V = state->getSVal(Ex, LCtx);
if (V.getAs<nonloc::PointerToMember>()) {
state = state->BindExpr(CastE, LCtx, UnknownVal());
Bldr.generateNode(CastE, Pred, state);
continue;
}
// Explicitly proceed with default handler for this case cascade.
state =
handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
continue;
}
case CK_IntegralToBoolean:
case CK_IntegralToFloating:
case CK_FloatingToIntegral:
case CK_FloatingToBoolean:
case CK_FloatingCast:
case CK_FloatingRealToComplex:
case CK_FloatingComplexToReal:
case CK_FloatingComplexToBoolean:
case CK_FloatingComplexCast:
case CK_FloatingComplexToIntegralComplex:
case CK_IntegralRealToComplex:
case CK_IntegralComplexToReal:
case CK_IntegralComplexToBoolean:
case CK_IntegralComplexCast:
case CK_IntegralComplexToFloatingComplex:
case CK_CPointerToObjCPointerCast:
case CK_BlockPointerToObjCPointerCast:
case CK_AnyPointerToBlockPointerCast:
case CK_ObjCObjectLValueCast:
case CK_ZeroToOCLEvent:
case CK_ZeroToOCLQueue:
case CK_IntToOCLSampler:
case CK_LValueBitCast: {
state =
handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
continue;
}
case CK_IntegralCast: {
// Delegate to SValBuilder to process.
SVal V = state->getSVal(Ex, LCtx);
V = svalBuilder.evalIntegralCast(state, V, T, ExTy);
state = state->BindExpr(CastE, LCtx, V);
Bldr.generateNode(CastE, Pred, state);
continue;
}
case CK_DerivedToBase:
case CK_UncheckedDerivedToBase: {
// For DerivedToBase cast, delegate to the store manager.
SVal val = state->getSVal(Ex, LCtx);
val = getStoreManager().evalDerivedToBase(val, CastE);
state = state->BindExpr(CastE, LCtx, val);
Bldr.generateNode(CastE, Pred, state);
continue;
}
// Handle C++ dyn_cast.
case CK_Dynamic: {
SVal val = state->getSVal(Ex, LCtx);
// Compute the type of the result.
QualType resultType = CastE->getType();
if (CastE->isGLValue())
resultType = getContext().getPointerType(resultType);
bool Failed = false;
// Check if the value being cast evaluates to 0.
if (val.isZeroConstant())
Failed = true;
// Else, evaluate the cast.
else
val = getStoreManager().attemptDownCast(val, T, Failed);
if (Failed) {
if (T->isReferenceType()) {
// A bad_cast exception is thrown if input value is a reference.
// Currently, we model this, by generating a sink.
Bldr.generateSink(CastE, Pred, state);
continue;
} else {
// If the cast fails on a pointer, bind to 0.
state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
}
} else {
// If we don't know if the cast succeeded, conjure a new symbol.
if (val.isUnknown()) {
DefinedOrUnknownSVal NewSym =
svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
currBldrCtx->blockCount());
state = state->BindExpr(CastE, LCtx, NewSym);
} else
// Else, bind to the derived region value.
state = state->BindExpr(CastE, LCtx, val);
}
Bldr.generateNode(CastE, Pred, state);
continue;
}
case CK_BaseToDerived: {
SVal val = state->getSVal(Ex, LCtx);
QualType resultType = CastE->getType();
if (CastE->isGLValue())
resultType = getContext().getPointerType(resultType);
bool Failed = false;
if (!val.isConstant()) {
val = getStoreManager().attemptDownCast(val, T, Failed);
}
// Failed to cast or the result is unknown, fall back to conservative.
if (Failed || val.isUnknown()) {
val =
svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
currBldrCtx->blockCount());
}
state = state->BindExpr(CastE, LCtx, val);
Bldr.generateNode(CastE, Pred, state);
continue;
}
case CK_NullToMemberPointer: {
SVal V = svalBuilder.getMemberPointer(nullptr);
state = state->BindExpr(CastE, LCtx, V);
Bldr.generateNode(CastE, Pred, state);
continue;
}
case CK_DerivedToBaseMemberPointer:
case CK_BaseToDerivedMemberPointer:
case CK_ReinterpretMemberPointer: {
SVal V = state->getSVal(Ex, LCtx);
if (auto PTMSV = V.getAs<nonloc::PointerToMember>()) {
SVal CastedPTMSV = svalBuilder.makePointerToMember(
getBasicVals().accumCXXBase(
llvm::make_range<CastExpr::path_const_iterator>(
CastE->path_begin(), CastE->path_end()), *PTMSV));
state = state->BindExpr(CastE, LCtx, CastedPTMSV);
Bldr.generateNode(CastE, Pred, state);
continue;
}
// Explicitly proceed with default handler for this case cascade.
state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
continue;
}
// Various C++ casts that are not handled yet.
case CK_ToUnion:
case CK_VectorSplat: {
state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
continue;
}
}
}
}
void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
ExplodedNode *Pred,
ExplodedNodeSet &Dst) {
StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
ProgramStateRef State = Pred->getState();
const LocationContext *LCtx = Pred->getLocationContext();
const Expr *Init = CL->getInitializer();
SVal V = State->getSVal(CL->getInitializer(), LCtx);
if (isa<CXXConstructExpr>(Init)) {
// No work needed. Just pass the value up to this expression.
} else {
assert(isa<InitListExpr>(Init));
Loc CLLoc = State->getLValue(CL, LCtx);
State = State->bindLoc(CLLoc, V);
if (CL->isGLValue())
V = CLLoc;
}
B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
}
void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
ExplodedNodeSet &Dst) {
// Assumption: The CFG has one DeclStmt per Decl.
const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
if (!VD) {
//TODO:AZ: remove explicit insertion after refactoring is done.
Dst.insert(Pred);
return;
}
// FIXME: all pre/post visits should eventually be handled by ::Visit().
ExplodedNodeSet dstPreVisit;
getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
ExplodedNodeSet dstEvaluated;
StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
I!=E; ++I) {
ExplodedNode *N = *I;
ProgramStateRef state = N->getState();
const LocationContext *LC = N->getLocationContext();
// Decls without InitExpr are not initialized explicitly.
if (const Expr *InitEx = VD->getInit()) {
// Note in the state that the initialization has occurred.
ExplodedNode *UpdatedN = N;
SVal InitVal = state->getSVal(InitEx, LC);
assert(DS->isSingleDecl());
if (auto *CtorExpr = findDirectConstructorForCurrentCFGElement()) {
assert(InitEx->IgnoreImplicit() == CtorExpr);
(void)CtorExpr;
// We constructed the object directly in the variable.
// No need to bind anything.
B.generateNode(DS, UpdatedN, state);
} else {
// We bound the temp obj region to the CXXConstructExpr. Now recover
// the lazy compound value when the variable is not a reference.
if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() &&
!VD->getType()->isReferenceType()) {
if (Optional<loc::MemRegionVal> M =
InitVal.getAs<loc::MemRegionVal>()) {
InitVal = state->getSVal(M->getRegion());
assert(InitVal.getAs<nonloc::LazyCompoundVal>());
}
}
// Recover some path-sensitivity if a scalar value evaluated to
// UnknownVal.
if (InitVal.isUnknown()) {
QualType Ty = InitEx->getType();
if (InitEx->isGLValue()) {
Ty = getContext().getPointerType(Ty);
}
InitVal = svalBuilder.conjureSymbolVal(nullptr, InitEx, LC, Ty,
currBldrCtx->blockCount());
}
B.takeNodes(UpdatedN);
ExplodedNodeSet Dst2;
evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
B.addNodes(Dst2);
}
}
else {
B.generateNode(DS, N, state);
}
}
getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
}
void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
ExplodedNodeSet &Dst) {
assert(B->getOpcode() == BO_LAnd ||
B->getOpcode() == BO_LOr);
StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
ProgramStateRef state = Pred->getState();
ExplodedNode *N = Pred;
while (!N->getLocation().getAs<BlockEntrance>()) {
ProgramPoint P = N->getLocation();
assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
(void) P;
assert(N->pred_size() == 1);
N = *N->pred_begin();
}
assert(N->pred_size() == 1);
N = *N->pred_begin();
BlockEdge BE = N->getLocation().castAs<BlockEdge>();
SVal X;
// Determine the value of the expression by introspecting how we
// got this location in the CFG. This requires looking at the previous
// block we were in and what kind of control-flow transfer was involved.
const CFGBlock *SrcBlock = BE.getSrc();
// The only terminator (if there is one) that makes sense is a logical op.
CFGTerminator T = SrcBlock->getTerminator();
if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
(void) Term;
assert(Term->isLogicalOp());
assert(SrcBlock->succ_size() == 2);
// Did we take the true or false branch?
unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
X = svalBuilder.makeIntVal(constant, B->getType());
}
else {
// If there is no terminator, by construction the last statement
// in SrcBlock is the value of the enclosing expression.
// However, we still need to constrain that value to be 0 or 1.
assert(!SrcBlock->empty());
CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
const Expr *RHS = cast<Expr>(Elem.getStmt());
SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
if (RHSVal.isUndef()) {
X = RHSVal;
} else {
- DefinedOrUnknownSVal DefinedRHS = RHSVal.castAs<DefinedOrUnknownSVal>();
- ProgramStateRef StTrue, StFalse;
- std::tie(StTrue, StFalse) = N->getState()->assume(DefinedRHS);
- if (StTrue) {
- if (StFalse) {
- // We can't constrain the value to 0 or 1.
- // The best we can do is a cast.
- X = getSValBuilder().evalCast(RHSVal, B->getType(), RHS->getType());
- } else {
- // The value is known to be true.
- X = getSValBuilder().makeIntVal(1, B->getType());
- }
- } else {
- // The value is known to be false.
- assert(StFalse && "Infeasible path!");
- X = getSValBuilder().makeIntVal(0, B->getType());
- }
+ // We evaluate "RHSVal != 0" expression which result in 0 if the value is
+ // known to be false, 1 if the value is known to be true and a new symbol
+ // when the assumption is unknown.
+ nonloc::ConcreteInt Zero(getBasicVals().getValue(0, B->getType()));
+ X = evalBinOp(N->getState(), BO_NE,
+ svalBuilder.evalCast(RHSVal, B->getType(), RHS->getType()),
+ Zero, B->getType());
}
}
Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
}
void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
ExplodedNode *Pred,
ExplodedNodeSet &Dst) {
StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
ProgramStateRef state = Pred->getState();
const LocationContext *LCtx = Pred->getLocationContext();
QualType T = getContext().getCanonicalType(IE->getType());
unsigned NumInitElements = IE->getNumInits();
if (!IE->isGLValue() &&
(T->isArrayType() || T->isRecordType() || T->isVectorType() ||
T->isAnyComplexType())) {
llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
// Handle base case where the initializer has no elements.
// e.g: static int* myArray[] = {};
if (NumInitElements == 0) {
SVal V = svalBuilder.makeCompoundVal(T, vals);
B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
return;
}
for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
ei = IE->rend(); it != ei; ++it) {
SVal V = state->getSVal(cast<Expr>(*it), LCtx);
vals = getBasicVals().prependSVal(V, vals);
}
B.generateNode(IE, Pred,
state->BindExpr(IE, LCtx,
svalBuilder.makeCompoundVal(T, vals)));
return;
}
// Handle scalars: int{5} and int{} and GLvalues.
// Note, if the InitListExpr is a GLvalue, it means that there is an address
// representing it, so it must have a single init element.
assert(NumInitElements <= 1);
SVal V;
if (NumInitElements == 0)
V = getSValBuilder().makeZeroVal(T);
else
V = state->getSVal(IE->getInit(0), LCtx);
B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
}
void ExprEngine::VisitGuardedExpr(const Expr *Ex,
const Expr *L,
const Expr *R,
ExplodedNode *Pred,
ExplodedNodeSet &Dst) {
assert(L && R);
StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
ProgramStateRef state = Pred->getState();
const LocationContext *LCtx = Pred->getLocationContext();
const CFGBlock *SrcBlock = nullptr;
// Find the predecessor block.
ProgramStateRef SrcState = state;
for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
ProgramPoint PP = N->getLocation();
if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
assert(N->pred_size() == 1);
continue;
}
SrcBlock = PP.castAs<BlockEdge>().getSrc();
SrcState = N->getState();
break;
}
assert(SrcBlock && "missing function entry");
// Find the last expression in the predecessor block. That is the
// expression that is used for the value of the ternary expression.
bool hasValue = false;
SVal V;
for (CFGElement CE : llvm::reverse(*SrcBlock)) {
if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
const Expr *ValEx = cast<Expr>(CS->getStmt());
ValEx = ValEx->IgnoreParens();
// For GNU extension '?:' operator, the left hand side will be an
// OpaqueValueExpr, so get the underlying expression.
if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
L = OpaqueEx->getSourceExpr();
// If the last expression in the predecessor block matches true or false
// subexpression, get its the value.
if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) {
hasValue = true;
V = SrcState->getSVal(ValEx, LCtx);
}
break;
}
}
if (!hasValue)
V = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
currBldrCtx->blockCount());
// Generate a new node with the binding from the appropriate path.
B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
}
void ExprEngine::
VisitOffsetOfExpr(const OffsetOfExpr *OOE,
ExplodedNode *Pred, ExplodedNodeSet &Dst) {
StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
APSInt IV;
if (OOE->EvaluateAsInt(IV, getContext())) {
assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
assert(OOE->getType()->isBuiltinType());
assert(OOE->getType()->getAs<BuiltinType>()->isInteger());
assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
SVal X = svalBuilder.makeIntVal(IV);
B.generateNode(OOE, Pred,
Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
X));
}
// FIXME: Handle the case where __builtin_offsetof is not a constant.
}
void ExprEngine::
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
ExplodedNode *Pred,
ExplodedNodeSet &Dst) {
// FIXME: Prechecks eventually go in ::Visit().
ExplodedNodeSet CheckedSet;
getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, Ex, *this);
ExplodedNodeSet EvalSet;
StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
QualType T = Ex->getTypeOfArgument();
for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
I != E; ++I) {
if (Ex->getKind() == UETT_SizeOf) {
if (!T->isIncompleteType() && !T->isConstantSizeType()) {
assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
// FIXME: Add support for VLA type arguments and VLA expressions.
// When that happens, we should probably refactor VLASizeChecker's code.
continue;
} else if (T->getAs<ObjCObjectType>()) {
// Some code tries to take the sizeof an ObjCObjectType, relying that
// the compiler has laid out its representation. Just report Unknown
// for these.
continue;
}
}
APSInt Value = Ex->EvaluateKnownConstInt(getContext());
CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
ProgramStateRef state = (*I)->getState();
state = state->BindExpr(Ex, (*I)->getLocationContext(),
svalBuilder.makeIntVal(amt.getQuantity(),
Ex->getType()));
Bldr.generateNode(Ex, *I, state);
}
getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
}
void ExprEngine::handleUOExtension(ExplodedNodeSet::iterator I,
const UnaryOperator *U,
StmtNodeBuilder &Bldr) {
// FIXME: We can probably just have some magic in Environment::getSVal()
// that propagates values, instead of creating a new node here.
//
// Unary "+" is a no-op, similar to a parentheses. We still have places
// where it may be a block-level expression, so we need to
// generate an extra node that just propagates the value of the
// subexpression.
const Expr *Ex = U->getSubExpr()->IgnoreParens();
ProgramStateRef state = (*I)->getState();
const LocationContext *LCtx = (*I)->getLocationContext();
Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
state->getSVal(Ex, LCtx)));
}
void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
ExplodedNodeSet &Dst) {
// FIXME: Prechecks eventually go in ::Visit().
ExplodedNodeSet CheckedSet;
getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
ExplodedNodeSet EvalSet;
StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
I != E; ++I) {
switch (U->getOpcode()) {
default: {
Bldr.takeNodes(*I);
ExplodedNodeSet Tmp;
VisitIncrementDecrementOperator(U, *I, Tmp);
Bldr.addNodes(Tmp);
break;
}
case UO_Real: {
const Expr *Ex = U->getSubExpr()->IgnoreParens();
// FIXME: We don't have complex SValues yet.
if (Ex->getType()->isAnyComplexType()) {
// Just report "Unknown."
break;
}
// For all other types, UO_Real is an identity operation.
assert (U->getType() == Ex->getType());
ProgramStateRef state = (*I)->getState();
const LocationContext *LCtx = (*I)->getLocationContext();
Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
state->getSVal(Ex, LCtx)));
break;
}
case UO_Imag: {
const Expr *Ex = U->getSubExpr()->IgnoreParens();
// FIXME: We don't have complex SValues yet.
if (Ex->getType()->isAnyComplexType()) {
// Just report "Unknown."
break;
}
// For all other types, UO_Imag returns 0.
ProgramStateRef state = (*I)->getState();
const LocationContext *LCtx = (*I)->getLocationContext();
SVal X = svalBuilder.makeZeroVal(Ex->getType());
Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
break;
}
case UO_AddrOf: {
// Process pointer-to-member address operation.
const Expr *Ex = U->getSubExpr()->IgnoreParens();
if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex)) {
const ValueDecl *VD = DRE->getDecl();
if (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD)) {
ProgramStateRef State = (*I)->getState();
const LocationContext *LCtx = (*I)->getLocationContext();
SVal SV = svalBuilder.getMemberPointer(cast<DeclaratorDecl>(VD));
Bldr.generateNode(U, *I, State->BindExpr(U, LCtx, SV));
break;
}
}
// Explicitly proceed with default handler for this case cascade.
handleUOExtension(I, U, Bldr);
break;
}
case UO_Plus:
assert(!U->isGLValue());
// FALL-THROUGH.
case UO_Deref:
case UO_Extension: {
handleUOExtension(I, U, Bldr);
break;
}
case UO_LNot:
case UO_Minus:
case UO_Not: {
assert (!U->isGLValue());
const Expr *Ex = U->getSubExpr()->IgnoreParens();
ProgramStateRef state = (*I)->getState();
const LocationContext *LCtx = (*I)->getLocationContext();
// Get the value of the subexpression.
SVal V = state->getSVal(Ex, LCtx);
if (V.isUnknownOrUndef()) {
Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
break;
}
switch (U->getOpcode()) {
default:
llvm_unreachable("Invalid Opcode.");
case UO_Not:
// FIXME: Do we need to handle promotions?
state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
break;
case UO_Minus:
// FIXME: Do we need to handle promotions?
state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
break;
case UO_LNot:
// C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
//
// Note: technically we do "E == 0", but this is the same in the
// transfer functions as "0 == E".
SVal Result;
if (Optional<Loc> LV = V.getAs<Loc>()) {
Loc X = svalBuilder.makeNull();
Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
}
else if (Ex->getType()->isFloatingType()) {
// FIXME: handle floating point types.
Result = UnknownVal();
} else {
nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
U->getType());
}
state = state->BindExpr(U, LCtx, Result);
break;
}
Bldr.generateNode(U, *I, state);
break;
}
}
}
getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
}
void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
ExplodedNode *Pred,
ExplodedNodeSet &Dst) {
// Handle ++ and -- (both pre- and post-increment).
assert (U->isIncrementDecrementOp());
const Expr *Ex = U->getSubExpr()->IgnoreParens();
const LocationContext *LCtx = Pred->getLocationContext();
ProgramStateRef state = Pred->getState();
SVal loc = state->getSVal(Ex, LCtx);
// Perform a load.
ExplodedNodeSet Tmp;
evalLoad(Tmp, U, Ex, Pred, state, loc);
ExplodedNodeSet Dst2;
StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
state = (*I)->getState();
assert(LCtx == (*I)->getLocationContext());
SVal V2_untested = state->getSVal(Ex, LCtx);
// Propagate unknown and undefined values.
if (V2_untested.isUnknownOrUndef()) {
Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested));
continue;
}
DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
// Handle all other values.
BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
// If the UnaryOperator has non-location type, use its type to create the
// constant value. If the UnaryOperator has location type, create the
// constant with int type and pointer width.
SVal RHS;
if (U->getType()->isAnyPointerType())
RHS = svalBuilder.makeArrayIndex(1);
else if (U->getType()->isIntegralOrEnumerationType())
RHS = svalBuilder.makeIntVal(1, U->getType());
else
RHS = UnknownVal();
SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
// Conjure a new symbol if necessary to recover precision.
if (Result.isUnknown()){
DefinedOrUnknownSVal SymVal =
svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
currBldrCtx->blockCount());
Result = SymVal;
// If the value is a location, ++/-- should always preserve
// non-nullness. Check if the original value was non-null, and if so
// propagate that constraint.
if (Loc::isLocType(U->getType())) {
DefinedOrUnknownSVal Constraint =
svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
if (!state->assume(Constraint, true)) {
// It isn't feasible for the original value to be null.
// Propagate this constraint.
Constraint = svalBuilder.evalEQ(state, SymVal,
svalBuilder.makeZeroVal(U->getType()));
state = state->assume(Constraint, false);
assert(state);
}
}
}
// Since the lvalue-to-rvalue conversion is explicit in the AST,
// we bind an l-value if the operator is prefix and an lvalue (in C++).
if (U->isGLValue())
state = state->BindExpr(U, LCtx, loc);
else
state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
// Perform the store.
Bldr.takeNodes(*I);
ExplodedNodeSet Dst3;
evalStore(Dst3, U, U, *I, state, loc, Result);
Bldr.addNodes(Dst3);
}
Dst.insert(Dst2);
}
Index: cfe/trunk/test/Analysis/misc-ps.c
===================================================================
--- cfe/trunk/test/Analysis/misc-ps.c (revision 290504)
+++ cfe/trunk/test/Analysis/misc-ps.c (revision 290505)
@@ -1,193 +1,203 @@
// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -analyze -disable-free -analyzer-eagerly-assume -analyzer-checker=core,deadcode,debug.ExprInspection -verify %s
void clang_analyzer_eval(int);
int size_rdar9373039 = 1;
int foo_rdar9373039(const char *);
int rdar93730392() {
int x;
int j = 0;
for (int i = 0 ; i < size_rdar9373039 ; ++i)
x = 1;
int extra = (2 + foo_rdar9373039 ("Clang") + ((4 - ((unsigned int) (2 + foo_rdar9373039 ("Clang")) % 4)) % 4)) + (2 + foo_rdar9373039 ("1.0") + ((4 - ((unsigned int) (2 + foo_rdar9373039 ("1.0")) % 4)) % 4)); // expected-warning {{never read}}
for (int i = 0 ; i < size_rdar9373039 ; ++i)
j += x; // expected-warning {{garbage}}
return j;
}
int PR8962 (int *t) {
// This should look through the __extension__ no-op.
if (__extension__ (t)) return 0;
return *t; // expected-warning {{null pointer}}
}
int PR8962_b (int *t) {
// This should still ignore the nested casts
// which aren't handled by a single IgnoreParens()
if (((int)((int)t))) return 0;
return *t; // expected-warning {{null pointer}}
}
int PR8962_c (int *t) {
// If the last element in a StmtExpr was a ParenExpr, it's still live
if (({ (t ? (_Bool)0 : (_Bool)1); })) return 0;
return *t; // no-warning
}
int PR8962_d (int *t) {
// If the last element in a StmtExpr is an __extension__, it's still live
if (({ __extension__(t ? (_Bool)0 : (_Bool)1); })) return 0;
return *t; // no-warning
}
int PR8962_e (int *t) {
// Redundant casts can mess things up!
// Environment used to skip through NoOp casts, but LiveVariables didn't!
if (({ (t ? (int)(int)0L : (int)(int)1L); })) return 0;
return *t; // no-warning
}
int PR8962_f (int *t) {
// The StmtExpr isn't a block-level expression here,
// the __extension__ is. But the value should be attached to the StmtExpr
// anyway. Make sure the block-level check is /before/ IgnoreParens.
if ( __extension__({
_Bool r;
if (t) r = 0;
else r = 1;
r;
}) ) return 0;
return *t; // no-warning
}
// This previously crashed logic in the analyzer engine when evaluating locations.
void rdar10308201_aux(unsigned val);
void rdar10308201 (int valA, void *valB, unsigned valC) {
unsigned actual_base, lines;
if (valC == 0) {
actual_base = (unsigned)valB;
for (;;) {
if (valA & (1<<0))
rdar10308201_aux(actual_base);
}
}
}
typedef struct Struct103 {
unsigned i;
} Struct103;
typedef unsigned int size_t;
void __my_memset_chk(char*, int, size_t);
static int radar10367606(int t) {
Struct103 overall;
((__builtin_object_size ((char *) &overall, 0) != (size_t) -1) ? __builtin___memset_chk ((char *) &overall, 0, sizeof(Struct103), __builtin_object_size ((char *) &overall, 0)) : __my_memset_chk ((char *) &overall, 0, sizeof(Struct103)));
return 0;
}
/* Caching out on a sink node. */
extern int fooR10376675();
extern int* bazR10376675();
extern int nR10376675;
void barR10376675(int *x) {
int *pm;
if (nR10376675 * 2) {
int *pk = bazR10376675();
pm = pk; //expected-warning {{never read}}
}
do {
*x = fooR10376675();
} while (0);
}
// Test accesses to wide character strings doesn't break the analyzer.
typedef int wchar_t;
struct rdar10385775 {
wchar_t *name;
};
void RDar10385775(struct rdar10385775* p) {
p->name = L"a";
}
// Test double loop of array and array literals. Previously this
// resulted in a false positive uninitailized value warning.
void rdar10686586() {
int array1[] = { 1, 2, 3, 0 };
int array2[] = { 1, 2, 3, 0 };
int *array[] = { array1, array2 };
int sum = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
sum += array[i][j]; // no-warning
}
}
}
// This example tests CFG handling of '||' nested in a ternary expression,
// and seeing that the analyzer doesn't crash.
int isctype(char c, unsigned long f)
{
return (c < 1 || c > 10) ? 0 : !!(c & f);
}
// Test that symbolic array offsets are modeled conservatively.
// This was triggering a false "use of uninitialized value" warning.
void rdar_12075238__aux(unsigned long y);
int rdar_12075238_(unsigned long count) {
if ((count < 3) || (count > 6))
return 0;
unsigned long array[6];
unsigned long i = 0;
for (; i <= count - 2; i++)
{
array[i] = i;
}
array[count - 1] = i;
rdar_12075238__aux(array[2]); // no-warning
return 0;
}
// Test that we handle an uninitialized value within a logical expression.
void PR14635(int *p) {
int a = 0, b;
*p = a || b; // expected-warning {{Assigned value is garbage or undefined}}
}
// Test handling floating point values with unary '!'.
int PR14634(int x) {
double y = (double)x;
return !y;
}
// PR15684: If a checker generates a sink node after generating a regular node
// and no state changes between the two, graph trimming would consider the two
// the same node, forming a loop.
struct PR15684 {
void (*callback)(int);
};
void sinkAfterRegularNode(struct PR15684 *context) {
int uninitialized;
context->callback(uninitialized); // expected-warning {{uninitialized}}
}
// PR16131: C permits variables to be declared extern void.
static void PR16131(int x) {
extern void v;
int *ip = (int *)&v;
char *cp = (char *)&v;
clang_analyzer_eval(ip == cp); // expected-warning{{TRUE}}
// expected-warning@-1 {{comparison of distinct pointer types}}
*ip = 42;
clang_analyzer_eval(*ip == 42); // expected-warning{{TRUE}}
clang_analyzer_eval(*(int *)&v == 42); // expected-warning{{TRUE}}
}
+
+// PR15623: Currently the analyzer doesn't handle symbolic expressions of the
+// form "(exp comparison_op expr) != 0" very well. We perform a simplification
+// translating an assume of a constraint of the form "(exp comparison_op expr)
+// != 0" to true into an assume of "exp comparison_op expr" to true.
+void PR15623(int n) {
+ if ((n == 0) != 0) {
+ clang_analyzer_eval(n == 0); // expected-warning{{TRUE}}
+ }
+}
Index: cfe/trunk/test/Analysis/malloc.c
===================================================================
--- cfe/trunk/test/Analysis/malloc.c (revision 290504)
+++ cfe/trunk/test/Analysis/malloc.c (revision 290505)
@@ -1,1790 +1,1801 @@
// RUN: %clang_cc1 -analyze -analyzer-checker=core,alpha.deadcode.UnreachableCode,alpha.core.CastSize,unix.Malloc,debug.ExprInspection -analyzer-store=region -verify %s
#include "Inputs/system-header-simulator.h"
void clang_analyzer_eval(int);
// Without -fms-compatibility, wchar_t isn't a builtin type. MSVC defines
// _WCHAR_T_DEFINED if wchar_t is available. Microsoft recommends that you use
// the builtin type: "Using the typedef version can cause portability
// problems", but we're ok here because we're not actually running anything.
// Also of note is this cryptic warning: "The wchar_t type is not supported
// when you compile C code".
//
// See the docs for more:
// https://msdn.microsoft.com/en-us/library/dh8che7s.aspx
#if !defined(_WCHAR_T_DEFINED)
// "Microsoft implements wchar_t as a two-byte unsigned value"
typedef unsigned short wchar_t;
#define _WCHAR_T_DEFINED
#endif // !defined(_WCHAR_T_DEFINED)
typedef __typeof(sizeof(int)) size_t;
void *malloc(size_t);
void *alloca(size_t);
void *valloc(size_t);
void free(void *);
void *realloc(void *ptr, size_t size);
void *reallocf(void *ptr, size_t size);
void *calloc(size_t nmemb, size_t size);
char *strdup(const char *s);
wchar_t *wcsdup(const wchar_t *s);
char *strndup(const char *s, size_t n);
int memcmp(const void *s1, const void *s2, size_t n);
// Windows variants
char *_strdup(const char *strSource);
wchar_t *_wcsdup(const wchar_t *strSource);
void *_alloca(size_t size);
void myfoo(int *p);
void myfooint(int p);
char *fooRetPtr();
void f1() {
int *p = malloc(12);
return; // expected-warning{{Potential leak of memory pointed to by 'p'}}
}
void f2() {
int *p = malloc(12);
free(p);
free(p); // expected-warning{{Attempt to free released memory}}
}
void f2_realloc_0() {
int *p = malloc(12);
realloc(p,0);
realloc(p,0); // expected-warning{{Attempt to free released memory}}
}
void f2_realloc_1() {
int *p = malloc(12);
int *q = realloc(p,0); // no-warning
}
void reallocNotNullPtr(unsigned sizeIn) {
unsigned size = 12;
char *p = (char*)malloc(size);
if (p) {
char *q = (char*)realloc(p, sizeIn);
char x = *q; // expected-warning {{Potential leak of memory pointed to by 'q'}}
}
}
void allocaTest() {
int *p = alloca(sizeof(int));
} // no warn
void winAllocaTest() {
int *p = _alloca(sizeof(int));
} // no warn
void allocaBuiltinTest() {
int *p = __builtin_alloca(sizeof(int));
} // no warn
int *realloctest1() {
int *q = malloc(12);
q = realloc(q, 20);
return q; // no warning - returning the allocated value
}
// p should be freed if realloc fails.
void reallocFails() {
char *p = malloc(12);
char *r = realloc(p, 12+1);
if (!r) {
free(p);
} else {
free(r);
}
}
void reallocSizeZero1() {
char *p = malloc(12);
char *r = realloc(p, 0);
if (!r) {
free(p); // expected-warning {{Attempt to free released memory}}
} else {
free(r);
}
}
void reallocSizeZero2() {
char *p = malloc(12);
char *r = realloc(p, 0);
if (!r) {
free(p); // expected-warning {{Attempt to free released memory}}
} else {
free(r);
}
free(p); // expected-warning {{Attempt to free released memory}}
}
void reallocSizeZero3() {
char *p = malloc(12);
char *r = realloc(p, 0);
free(r);
}
void reallocSizeZero4() {
char *r = realloc(0, 0);
free(r);
}
void reallocSizeZero5() {
char *r = realloc(0, 0);
}
void reallocPtrZero1() {
char *r = realloc(0, 12);
} // expected-warning {{Potential leak of memory pointed to by 'r'}}
void reallocPtrZero2() {
char *r = realloc(0, 12);
if (r)
free(r);
}
void reallocPtrZero3() {
char *r = realloc(0, 12);
free(r);
}
void reallocRadar6337483_1() {
char *buf = malloc(100);
buf = (char*)realloc(buf, 0x1000000);
if (!buf) {
return;// expected-warning {{Potential leak of memory pointed to by}}
}
free(buf);
}
void reallocRadar6337483_2() {
char *buf = malloc(100);
char *buf2 = (char*)realloc(buf, 0x1000000);
if (!buf2) {
;
} else {
free(buf2);
}
} // expected-warning {{Potential leak of memory pointed to by}}
void reallocRadar6337483_3() {
char * buf = malloc(100);
char * tmp;
tmp = (char*)realloc(buf, 0x1000000);
if (!tmp) {
free(buf);
return;
}
buf = tmp;
free(buf);
}
void reallocRadar6337483_4() {
char *buf = malloc(100);
char *buf2 = (char*)realloc(buf, 0x1000000);
if (!buf2) {
return; // expected-warning {{Potential leak of memory pointed to by}}
} else {
free(buf2);
}
}
int *reallocfTest1() {
int *q = malloc(12);
q = reallocf(q, 20);
return q; // no warning - returning the allocated value
}
void reallocfRadar6337483_4() {
char *buf = malloc(100);
char *buf2 = (char*)reallocf(buf, 0x1000000);
if (!buf2) {
return; // no warning - reallocf frees even on failure
} else {
free(buf2);
}
}
void reallocfRadar6337483_3() {
char * buf = malloc(100);
char * tmp;
tmp = (char*)reallocf(buf, 0x1000000);
if (!tmp) {
free(buf); // expected-warning {{Attempt to free released memory}}
return;
}
buf = tmp;
free(buf);
}
void reallocfPtrZero1() {
char *r = reallocf(0, 12);
} // expected-warning {{Potential leak of memory pointed to by}}
//------------------- Check usage of zero-allocated memory ---------------------
void CheckUseZeroAllocatedNoWarn1() {
int *p = malloc(0);
free(p); // no warning
}
void CheckUseZeroAllocatedNoWarn2() {
int *p = alloca(0); // no warning
}
void CheckUseZeroWinAllocatedNoWarn2() {
int *p = _alloca(0); // no warning
}
void CheckUseZeroAllocatedNoWarn3() {
int *p = malloc(0);
int *q = realloc(p, 8); // no warning
free(q);
}
void CheckUseZeroAllocatedNoWarn4() {
int *p = realloc(0, 8);
*p = 1; // no warning
free(p);
}
void CheckUseZeroAllocated1() {
int *p = malloc(0);
*p = 1; // expected-warning {{Use of zero-allocated memory}}
free(p);
}
char CheckUseZeroAllocated2() {
char *p = alloca(0);
return *p; // expected-warning {{Use of zero-allocated memory}}
}
char CheckUseZeroWinAllocated2() {
char *p = _alloca(0);
return *p; // expected-warning {{Use of zero-allocated memory}}
}
void UseZeroAllocated(int *p) {
if (p)
*p = 7; // expected-warning {{Use of zero-allocated memory}}
}
void CheckUseZeroAllocated3() {
int *p = malloc(0);
UseZeroAllocated(p);
}
void f(char);
void CheckUseZeroAllocated4() {
char *p = valloc(0);
f(*p); // expected-warning {{Use of zero-allocated memory}}
free(p);
}
void CheckUseZeroAllocated5() {
int *p = calloc(0, 2);
*p = 1; // expected-warning {{Use of zero-allocated memory}}
free(p);
}
void CheckUseZeroAllocated6() {
int *p = calloc(2, 0);
*p = 1; // expected-warning {{Use of zero-allocated memory}}
free(p);
}
void CheckUseZeroAllocated7() {
int *p = realloc(0, 0);
*p = 1; // expected-warning {{Use of zero-allocated memory}}
free(p);
}
void CheckUseZeroAllocated8() {
int *p = malloc(8);
int *q = realloc(p, 0);
*q = 1; // expected-warning {{Use of zero-allocated memory}}
free(q);
}
void CheckUseZeroAllocated9() {
int *p = realloc(0, 0);
int *q = realloc(p, 0);
*q = 1; // expected-warning {{Use of zero-allocated memory}}
free(q);
}
void CheckUseZeroAllocatedPathNoWarn(_Bool b) {
int s = 0;
if (b)
s= 10;
char *p = malloc(s);
if (b)
*p = 1; // no warning
free(p);
}
void CheckUseZeroAllocatedPathWarn(_Bool b) {
int s = 10;
if (b)
s= 0;
char *p = malloc(s);
if (b)
*p = 1; // expected-warning {{Use of zero-allocated memory}}
free(p);
}
void CheckUseZeroReallocatedPathNoWarn(_Bool b) {
int s = 0;
if (b)
s= 10;
char *p = malloc(8);
char *q = realloc(p, s);
if (b)
*q = 1; // no warning
free(q);
}
void CheckUseZeroReallocatedPathWarn(_Bool b) {
int s = 10;
if (b)
s= 0;
char *p = malloc(8);
char *q = realloc(p, s);
if (b)
*q = 1; // expected-warning {{Use of zero-allocated memory}}
free(q);
}
// This case tests that storing malloc'ed memory to a static variable which is
// then returned is not leaked. In the absence of known contracts for functions
// or inter-procedural analysis, this is a conservative answer.
int *f3() {
static int *p = 0;
p = malloc(12);
return p; // no-warning
}
// This case tests that storing malloc'ed memory to a static global variable
// which is then returned is not leaked. In the absence of known contracts for
// functions or inter-procedural analysis, this is a conservative answer.
static int *p_f4 = 0;
int *f4() {
p_f4 = malloc(12);
return p_f4; // no-warning
}
int *f5() {
int *q = malloc(12);
q = realloc(q, 20);
return q; // no-warning
}
void f6() {
int *p = malloc(12);
if (!p)
return; // no-warning
else
free(p);
}
void f6_realloc() {
int *p = malloc(12);
if (!p)
return; // no-warning
else
realloc(p,0);
}
char *doit2();
void pr6069() {
char *buf = doit2();
free(buf);
}
void pr6293() {
free(0);
}
void f7() {
char *x = (char*) malloc(4);
free(x);
x[0] = 'a'; // expected-warning{{Use of memory after it is freed}}
}
void f8() {
char *x = (char*) malloc(4);
free(x);
char *y = strndup(x, 4); // expected-warning{{Use of memory after it is freed}}
}
void f7_realloc() {
char *x = (char*) malloc(4);
realloc(x,0);
x[0] = 'a'; // expected-warning{{Use of memory after it is freed}}
}
void PR6123() {
int *x = malloc(11); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
}
void PR7217() {
int *buf = malloc(2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
buf[1] = 'c'; // not crash
}
void cast_emtpy_struct() {
struct st {
};
struct st *s = malloc(sizeof(struct st)); // no-warning
free(s);
}
void cast_struct_1() {
struct st {
int i[100];
char j[];
};
struct st *s = malloc(sizeof(struct st)); // no-warning
free(s);
}
void cast_struct_2() {
struct st {
int i[100];
char j[0];
};
struct st *s = malloc(sizeof(struct st)); // no-warning
free(s);
}
void cast_struct_3() {
struct st {
int i[100];
char j[1];
};
struct st *s = malloc(sizeof(struct st)); // no-warning
free(s);
}
void cast_struct_4() {
struct st {
int i[100];
char j[2];
};
struct st *s = malloc(sizeof(struct st)); // no-warning
free(s);
}
void cast_struct_5() {
struct st {
char i[200];
char j[1];
};
struct st *s = malloc(sizeof(struct st) - sizeof(char)); // no-warning
free(s);
}
void cast_struct_warn_1() {
struct st {
int i[100];
char j[2];
};
struct st *s = malloc(sizeof(struct st) + 2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
free(s);
}
void cast_struct_warn_2() {
struct st {
int i[100];
char j[2];
};
struct st *s = malloc(2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
free(s);
}
void cast_struct_flex_array_1() {
struct st {
int i[100];
char j[];
};
struct st *s = malloc(sizeof(struct st) + 3); // no-warning
free(s);
}
void cast_struct_flex_array_2() {
struct st {
int i[100];
char j[0];
};
struct st *s = malloc(sizeof(struct st) + 3); // no-warning
free(s);
}
void cast_struct_flex_array_3() {
struct st {
int i[100];
char j[1];
};
struct st *s = malloc(sizeof(struct st) + 3); // no-warning
free(s);
}
void cast_struct_flex_array_4() {
struct foo {
char f[32];
};
struct st {
char i[100];
struct foo data[];
};
struct st *s = malloc(sizeof(struct st) + 3 * sizeof(struct foo)); // no-warning
free(s);
}
void cast_struct_flex_array_5() {
struct foo {
char f[32];
};
struct st {
char i[100];
struct foo data[0];
};
struct st *s = malloc(sizeof(struct st) + 3 * sizeof(struct foo)); // no-warning
free(s);
}
void cast_struct_flex_array_6() {
struct foo {
char f[32];
};
struct st {
char i[100];
struct foo data[1];
};
struct st *s = malloc(sizeof(struct st) + 3 * sizeof(struct foo)); // no-warning
free(s);
}
void cast_struct_flex_array_warn_1() {
struct foo {
char f[32];
};
struct st {
char i[100];
struct foo data[];
};
struct st *s = malloc(3 * sizeof(struct st) + 3 * sizeof(struct foo)); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
free(s);
}
void cast_struct_flex_array_warn_2() {
struct foo {
char f[32];
};
struct st {
char i[100];
struct foo data[0];
};
struct st *s = malloc(3 * sizeof(struct st) + 3 * sizeof(struct foo)); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
free(s);
}
void cast_struct_flex_array_warn_3() {
struct foo {
char f[32];
};
struct st {
char i[100];
struct foo data[1];
};
struct st *s = malloc(3 * sizeof(struct st) + 3 * sizeof(struct foo)); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
free(s);
}
void cast_struct_flex_array_warn_4() {
struct st {
int i[100];
int j[];
};
struct st *s = malloc(sizeof(struct st) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
free(s);
}
void cast_struct_flex_array_warn_5() {
struct st {
int i[100];
int j[0];
};
struct st *s = malloc(sizeof(struct st) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
free(s);
}
void cast_struct_flex_array_warn_6() {
struct st {
int i[100];
int j[1];
};
struct st *s = malloc(sizeof(struct st) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
free(s);
}
void mallocCastToVoid() {
void *p = malloc(2);
const void *cp = p; // not crash
free(p);
}
void mallocCastToFP() {
void *p = malloc(2);
void (*fp)() = p; // not crash
free(p);
}
// This tests that malloc() buffers are undefined by default
char mallocGarbage () {
char *buf = malloc(2);
char result = buf[1]; // expected-warning{{undefined}}
free(buf);
return result;
}
// This tests that calloc() buffers need to be freed
void callocNoFree () {
char *buf = calloc(2,2);
return; // expected-warning{{Potential leak of memory pointed to by 'buf'}}
}
// These test that calloc() buffers are zeroed by default
char callocZeroesGood () {
char *buf = calloc(2,2);
char result = buf[3]; // no-warning
if (buf[1] == 0) {
free(buf);
}
return result; // no-warning
}
char callocZeroesBad () {
char *buf = calloc(2,2);
char result = buf[3]; // no-warning
if (buf[1] != 0) {
free(buf); // expected-warning{{never executed}}
}
return result; // expected-warning{{Potential leak of memory pointed to by 'buf'}}
}
void nullFree() {
int *p = 0;
free(p); // no warning - a nop
}
void paramFree(int *p) {
myfoo(p);
free(p); // no warning
myfoo(p); // expected-warning {{Use of memory after it is freed}}
}
int* mallocEscapeRet() {
int *p = malloc(12);
return p; // no warning
}
void mallocEscapeFoo() {
int *p = malloc(12);
myfoo(p);
return; // no warning
}
void mallocEscapeFree() {
int *p = malloc(12);
myfoo(p);
free(p);
}
void mallocEscapeFreeFree() {
int *p = malloc(12);
myfoo(p);
free(p);
free(p); // expected-warning{{Attempt to free released memory}}
}
void mallocEscapeFreeUse() {
int *p = malloc(12);
myfoo(p);
free(p);
myfoo(p); // expected-warning{{Use of memory after it is freed}}
}
int *myalloc();
void myalloc2(int **p);
void mallocEscapeFreeCustomAlloc() {
int *p = malloc(12);
myfoo(p);
free(p);
p = myalloc();
free(p); // no warning
}
void mallocEscapeFreeCustomAlloc2() {
int *p = malloc(12);
myfoo(p);
free(p);
myalloc2(&p);
free(p); // no warning
}
void mallocBindFreeUse() {
int *x = malloc(12);
int *y = x;
free(y);
myfoo(x); // expected-warning{{Use of memory after it is freed}}
}
void mallocEscapeMalloc() {
int *p = malloc(12);
myfoo(p);
p = malloc(12);
} // expected-warning{{Potential leak of memory pointed to by}}
void mallocMalloc() {
int *p = malloc(12);
p = malloc(12);
} // expected-warning {{Potential leak of memory pointed to by}}
void mallocFreeMalloc() {
int *p = malloc(12);
free(p);
p = malloc(12);
free(p);
}
void mallocFreeUse_params() {
int *p = malloc(12);
free(p);
myfoo(p); //expected-warning{{Use of memory after it is freed}}
}
void mallocFreeUse_params2() {
int *p = malloc(12);
free(p);
myfooint(*p); //expected-warning{{Use of memory after it is freed}}
}
void mallocFailedOrNot() {
int *p = malloc(12);
if (!p)
free(p);
else
free(p);
}
struct StructWithInt {
int g;
};
int *mallocReturnFreed() {
int *p = malloc(12);
free(p);
return p; // expected-warning {{Use of memory after it is freed}}
}
int useAfterFreeStruct() {
struct StructWithInt *px= malloc(sizeof(struct StructWithInt));
px->g = 5;
free(px);
return px->g; // expected-warning {{Use of memory after it is freed}}
}
void nonSymbolAsFirstArg(int *pp, struct StructWithInt *p);
void mallocEscapeFooNonSymbolArg() {
struct StructWithInt *p = malloc(sizeof(struct StructWithInt));
nonSymbolAsFirstArg(&p->g, p);
return; // no warning
}
void mallocFailedOrNotLeak() {
int *p = malloc(12);
if (p == 0)
return; // no warning
else
return; // expected-warning {{Potential leak of memory pointed to by}}
}
void mallocAssignment() {
char *p = malloc(12);
p = fooRetPtr();
} // expected-warning {{leak}}
int vallocTest() {
char *mem = valloc(12);
return 0; // expected-warning {{Potential leak of memory pointed to by}}
}
void vallocEscapeFreeUse() {
int *p = valloc(12);
myfoo(p);
free(p);
myfoo(p); // expected-warning{{Use of memory after it is freed}}
}
int *Gl;
struct GlStTy {
int *x;
};
struct GlStTy GlS = {0};
void GlobalFree() {
free(Gl);
}
void GlobalMalloc() {
Gl = malloc(12);
}
void GlobalStructMalloc() {
int *a = malloc(12);
GlS.x = a;
}
void GlobalStructMallocFree() {
int *a = malloc(12);
GlS.x = a;
free(GlS.x);
}
char *ArrayG[12];
void globalArrayTest() {
char *p = (char*)malloc(12);
ArrayG[0] = p;
}
// Make sure that we properly handle a pointer stored into a local struct/array.
typedef struct _StructWithPtr {
int *memP;
} StructWithPtr;
static StructWithPtr arrOfStructs[10];
void testMalloc() {
int *x = malloc(12);
StructWithPtr St;
St.memP = x;
arrOfStructs[0] = St; // no-warning
}
StructWithPtr testMalloc2() {
int *x = malloc(12);
StructWithPtr St;
St.memP = x;
return St; // no-warning
}
int *testMalloc3() {
int *x = malloc(12);
int *y = x;
return y; // no-warning
}
void testStructLeak() {
StructWithPtr St;
St.memP = malloc(12);
return; // expected-warning {{Potential leak of memory pointed to by 'St.memP'}}
}
void testElemRegion1() {
char *x = (void*)malloc(2);
int *ix = (int*)x;
free(&(x[0]));
}
void testElemRegion2(int **pp) {
int *p = malloc(12);
*pp = p;
free(pp[0]);
}
void testElemRegion3(int **pp) {
int *p = malloc(12);
*pp = p;
free(*pp);
}
// Region escape testing.
unsigned takePtrToPtr(int **p);
void PassTheAddrOfAllocatedData(int f) {
int *p = malloc(12);
// We don't know what happens after the call. Should stop tracking here.
if (takePtrToPtr(&p))
f++;
free(p); // no warning
}
struct X {
int *p;
};
unsigned takePtrToStruct(struct X *s);
int ** foo2(int *g, int f) {
int *p = malloc(12);
struct X *px= malloc(sizeof(struct X));
px->p = p;
// We don't know what happens after this call. Should not track px nor p.
if (takePtrToStruct(px))
f++;
free(p);
return 0;
}
struct X* RegInvalidationDetect1(struct X *s2) {
struct X *px= malloc(sizeof(struct X));
px->p = 0;
px = s2;
return px; // expected-warning {{Potential leak of memory pointed to by}}
}
struct X* RegInvalidationGiveUp1() {
int *p = malloc(12);
struct X *px= malloc(sizeof(struct X));
px->p = p;
return px;
}
int **RegInvalidationDetect2(int **pp) {
int *p = malloc(12);
pp = &p;
pp++;
return 0;// expected-warning {{Potential leak of memory pointed to by}}
}
extern void exit(int) __attribute__ ((__noreturn__));
void mallocExit(int *g) {
struct xx *p = malloc(12);
if (g != 0)
exit(1);
free(p);
return;
}
extern void __assert_fail (__const char *__assertion, __const char *__file,
unsigned int __line, __const char *__function)
__attribute__ ((__noreturn__));
#define assert(expr) \
((expr) ? (void)(0) : __assert_fail (#expr, __FILE__, __LINE__, __func__))
void mallocAssert(int *g) {
struct xx *p = malloc(12);
assert(g != 0);
free(p);
return;
}
void doNotInvalidateWhenPassedToSystemCalls(char *s) {
char *p = malloc(12);
strlen(p);
strcpy(p, s);
strcpy(s, p);
strcpy(p, p);
memcpy(p, s, 1);
memcpy(s, p, 1);
memcpy(p, p, 1);
} // expected-warning {{leak}}
// Treat source buffer contents as escaped.
void escapeSourceContents(char *s) {
char *p = malloc(12);
memcpy(s, &p, 12); // no warning
void *p1 = malloc(7);
char *a;
memcpy(&a, &p1, sizeof a);
// FIXME: No warning due to limitations imposed by current modelling of
// 'memcpy' (regions metadata is not copied).
int *ptrs[2];
int *allocated = (int *)malloc(4);
memcpy(&ptrs[0], &allocated, sizeof(int *));
// FIXME: No warning due to limitations imposed by current modelling of
// 'memcpy' (regions metadata is not copied).
}
void invalidateDestinationContents() {
int *null = 0;
int *p = (int *)malloc(4);
memcpy(&p, &null, sizeof(int *));
int *ptrs1[2]; // expected-warning {{Potential leak of memory pointed to by}}
ptrs1[0] = (int *)malloc(4);
memcpy(ptrs1, &null, sizeof(int *));
int *ptrs2[2]; // expected-warning {{Potential memory leak}}
ptrs2[0] = (int *)malloc(4);
memcpy(&ptrs2[1], &null, sizeof(int *));
int *ptrs3[2]; // expected-warning {{Potential memory leak}}
ptrs3[0] = (int *)malloc(4);
memcpy(&ptrs3[0], &null, sizeof(int *));
} // expected-warning {{Potential memory leak}}
// Rely on the CString checker evaluation of the strcpy API to convey that the result of strcpy is equal to p.
void symbolLostWithStrcpy(char *s) {
char *p = malloc(12);
p = strcpy(p, s);
free(p);
}
// The same test as the one above, but with what is actually generated on a mac.
static __inline char *
__inline_strcpy_chk (char *restrict __dest, const char *restrict __src)
{
return __builtin___strcpy_chk (__dest, __src, __builtin_object_size (__dest, 2 > 1));
}
void symbolLostWithStrcpy_InlineStrcpyVersion(char *s) {
char *p = malloc(12);
p = ((__builtin_object_size (p, 0) != (size_t) -1) ? __builtin___strcpy_chk (p, s, __builtin_object_size (p, 2 > 1)) : __inline_strcpy_chk (p, s));
free(p);
}
// Here we are returning a pointer one past the allocated value. An idiom which
// can be used for implementing special malloc. The correct uses of this might
// be rare enough so that we could keep this as a warning.
static void *specialMalloc(int n){
int *p;
p = malloc( n+8 );
if( p ){
p[0] = n;
p++;
}
return p;
}
// Potentially, the user could free the struct by performing pointer arithmetic on the return value.
// This is a variation of the specialMalloc issue, though probably would be more rare in correct code.
int *specialMallocWithStruct() {
struct StructWithInt *px= malloc(sizeof(struct StructWithInt));
return &(px->g);
}
// Test various allocation/deallocation functions.
void testStrdup(const char *s, unsigned validIndex) {
char *s2 = strdup(s);
s2[validIndex + 1] = 'b';
} // expected-warning {{Potential leak of memory pointed to by}}
void testWinStrdup(const char *s, unsigned validIndex) {
char *s2 = _strdup(s);
s2[validIndex + 1] = 'b';
} // expected-warning {{Potential leak of memory pointed to by}}
void testWcsdup(const wchar_t *s, unsigned validIndex) {
wchar_t *s2 = wcsdup(s);
s2[validIndex + 1] = 'b';
} // expected-warning {{Potential leak of memory pointed to by}}
void testWinWcsdup(const wchar_t *s, unsigned validIndex) {
wchar_t *s2 = _wcsdup(s);
s2[validIndex + 1] = 'b';
} // expected-warning {{Potential leak of memory pointed to by}}
int testStrndup(const char *s, unsigned validIndex, unsigned size) {
char *s2 = strndup(s, size);
s2 [validIndex + 1] = 'b';
if (s2[validIndex] != 'a')
return 0;
else
return 1;// expected-warning {{Potential leak of memory pointed to by}}
}
void testStrdupContentIsDefined(const char *s, unsigned validIndex) {
char *s2 = strdup(s);
char result = s2[1];// no warning
free(s2);
}
void testWinStrdupContentIsDefined(const char *s, unsigned validIndex) {
char *s2 = _strdup(s);
char result = s2[1];// no warning
free(s2);
}
void testWcsdupContentIsDefined(const wchar_t *s, unsigned validIndex) {
wchar_t *s2 = wcsdup(s);
wchar_t result = s2[1];// no warning
free(s2);
}
void testWinWcsdupContentIsDefined(const wchar_t *s, unsigned validIndex) {
wchar_t *s2 = _wcsdup(s);
wchar_t result = s2[1];// no warning
free(s2);
}
// ----------------------------------------------------------------------------
// Test the system library functions to which the pointer can escape.
// This tests false positive suppression.
// For now, we assume memory passed to pthread_specific escapes.
// TODO: We could check that if a new pthread binding is set, the existing
// binding must be freed; otherwise, a memory leak can occur.
void testPthereadSpecificEscape(pthread_key_t key) {
void *buf = malloc(12);
pthread_setspecific(key, buf); // no warning
}
// PR12101: Test funopen().
static int releasePtr(void *_ctx) {
free(_ctx);
return 0;
}
FILE *useFunOpen() {
void *ctx = malloc(sizeof(int));
FILE *f = funopen(ctx, 0, 0, 0, releasePtr); // no warning
if (f == 0) {
free(ctx);
}
return f;
}
FILE *useFunOpenNoReleaseFunction() {
void *ctx = malloc(sizeof(int));
FILE *f = funopen(ctx, 0, 0, 0, 0);
if (f == 0) {
free(ctx);
}
return f; // expected-warning{{leak}}
}
static int readNothing(void *_ctx, char *buf, int size) {
return 0;
}
FILE *useFunOpenReadNoRelease() {
void *ctx = malloc(sizeof(int));
FILE *f = funopen(ctx, readNothing, 0, 0, 0);
if (f == 0) {
free(ctx);
}
return f; // expected-warning{{leak}}
}
// Test setbuf, setvbuf.
int my_main_no_warning() {
char *p = malloc(100);
setvbuf(stdout, p, 0, 100);
return 0;
}
int my_main_no_warning2() {
char *p = malloc(100);
setbuf(__stdoutp, p);
return 0;
}
int my_main_warn(FILE *f) {
char *p = malloc(100);
setvbuf(f, p, 0, 100);
return 0;// expected-warning {{leak}}
}
// <rdar://problem/10978247>.
// some people use stack allocated memory as an optimization to avoid
// a heap allocation for small work sizes. This tests the analyzer's
// understanding that the malloc'ed memory is not the same as stackBuffer.
void radar10978247(int myValueSize) {
char stackBuffer[128];
char *buffer;
if (myValueSize <= sizeof(stackBuffer))
buffer = stackBuffer;
else
buffer = malloc(myValueSize);
// do stuff with the buffer
if (buffer != stackBuffer)
free(buffer);
}
void radar10978247_positive(int myValueSize) {
char stackBuffer[128];
char *buffer;
if (myValueSize <= sizeof(stackBuffer))
buffer = stackBuffer;
else
buffer = malloc(myValueSize);
// do stuff with the buffer
if (buffer == stackBuffer)
return;
else
return; // expected-warning {{leak}}
}
// <rdar://problem/11269741> Previously this triggered a false positive
// because malloc() is known to return uninitialized memory and the binding
// of 'o' to 'p->n' was not getting propertly handled. Now we report a leak.
struct rdar11269741_a_t {
struct rdar11269741_b_t {
int m;
} n;
};
int rdar11269741(struct rdar11269741_b_t o)
{
struct rdar11269741_a_t *p = (struct rdar11269741_a_t *) malloc(sizeof(*p));
p->n = o;
return p->n.m; // expected-warning {{leak}}
}
// Pointer arithmetic, returning an ElementRegion.
void *radar11329382(unsigned bl) {
void *ptr = malloc (16);
ptr = ptr + (2 - bl);
return ptr; // no warning
}
void __assert_rtn(const char *, const char *, int, const char *) __attribute__((__noreturn__));
int strcmp(const char *, const char *);
char *a (void);
void radar11270219(void) {
char *x = a(), *y = a();
(__builtin_expect(!(x && y), 0) ? __assert_rtn(__func__, "/Users/zaks/tmp/ex.c", 24, "x && y") : (void)0);
strcmp(x, y); // no warning
}
void radar_11358224_test_double_assign_ints_positive_2()
{
void *ptr = malloc(16);
ptr = ptr;
} // expected-warning {{leak}}
// Assume that functions which take a function pointer can free memory even if
// they are defined in system headers and take the const pointer to the
// allocated memory. (radar://11160612)
int const_ptr_and_callback(int, const char*, int n, void(*)(void*));
void r11160612_1() {
char *x = malloc(12);
const_ptr_and_callback(0, x, 12, free); // no - warning
}
// Null is passed as callback.
void r11160612_2() {
char *x = malloc(12);
const_ptr_and_callback(0, x, 12, 0);
} // expected-warning {{leak}}
// Callback is passed to a function defined in a system header.
void r11160612_4() {
char *x = malloc(12);
sqlite3_bind_text_my(0, x, 12, free); // no - warning
}
// Passing callbacks in a struct.
void r11160612_5(StWithCallback St) {
void *x = malloc(12);
dealocateMemWhenDoneByVal(x, St);
}
void r11160612_6(StWithCallback St) {
void *x = malloc(12);
dealocateMemWhenDoneByRef(&St, x);
}
int mySub(int, int);
int myAdd(int, int);
int fPtr(unsigned cond, int x) {
return (cond ? mySub : myAdd)(x, x);
}
// Test anti-aliasing.
void dependsOnValueOfPtr(int *g, unsigned f) {
int *p;
if (f) {
p = g;
} else {
p = malloc(12);
}
if (p != g)
free(p);
else
return; // no warning
return;
}
int CMPRegionHeapToStack() {
int x = 0;
int *x1 = malloc(8);
int *x2 = &x;
clang_analyzer_eval(x1 == x2); // expected-warning{{FALSE}}
free(x1);
return x;
}
int CMPRegionHeapToHeap2() {
int x = 0;
int *x1 = malloc(8);
int *x2 = malloc(8);
int *x4 = x1;
int *x5 = x2;
clang_analyzer_eval(x4 == x5); // expected-warning{{FALSE}}
free(x1);
free(x2);
return x;
}
int CMPRegionHeapToHeap() {
int x = 0;
int *x1 = malloc(8);
int *x4 = x1;
if (x1 == x4) {
free(x1);
return 5/x; // expected-warning{{Division by zero}}
}
return x;// expected-warning{{This statement is never executed}}
}
int HeapAssignment() {
int m = 0;
int *x = malloc(4);
int *y = x;
*x = 5;
clang_analyzer_eval(*x != *y); // expected-warning{{FALSE}}
free(x);
return 0;
}
int *retPtr();
int *retPtrMightAlias(int *x);
int cmpHeapAllocationToUnknown() {
int zero = 0;
int *yBefore = retPtr();
int *m = malloc(8);
int *yAfter = retPtrMightAlias(m);
clang_analyzer_eval(yBefore == m); // expected-warning{{FALSE}}
clang_analyzer_eval(yAfter == m); // expected-warning{{FALSE}}
free(m);
return 0;
}
void localArrayTest() {
char *p = (char*)malloc(12);
char *ArrayL[12];
ArrayL[0] = p;
} // expected-warning {{leak}}
void localStructTest() {
StructWithPtr St;
StructWithPtr *pSt = &St;
pSt->memP = malloc(12);
} // expected-warning{{Potential leak of memory pointed to by}}
#ifdef __INTPTR_TYPE__
// Test double assignment through integers.
typedef __INTPTR_TYPE__ intptr_t;
typedef unsigned __INTPTR_TYPE__ uintptr_t;
static intptr_t glob;
void test_double_assign_ints()
{
void *ptr = malloc (16); // no-warning
glob = (intptr_t)(uintptr_t)ptr;
}
void test_double_assign_ints_positive()
{
void *ptr = malloc(16);
(void*)(intptr_t)(uintptr_t)ptr; // expected-warning {{unused}}
} // expected-warning {{leak}}
#endif
void testCGContextNoLeak()
{
void *ptr = malloc(16);
CGContextRef context = CGBitmapContextCreate(ptr);
// Because you can get the data back out like this, even much later,
// CGBitmapContextCreate is one of our "stop-tracking" exceptions.
free(CGBitmapContextGetData(context));
}
void testCGContextLeak()
{
void *ptr = malloc(16);
CGContextRef context = CGBitmapContextCreate(ptr);
// However, this time we're just leaking the data, because the context
// object doesn't escape and it hasn't been freed in this function.
}
// Allow xpc context to escape. radar://11635258
// TODO: Would be great if we checked that the finalize_connection_context actually releases it.
static void finalize_connection_context(void *ctx) {
int *context = ctx;
free(context);
}
void foo (xpc_connection_t peer) {
int *ctx = calloc(1, sizeof(int));
xpc_connection_set_context(peer, ctx);
xpc_connection_set_finalizer_f(peer, finalize_connection_context);
xpc_connection_resume(peer);
}
// Make sure we catch errors when we free in a function which does not allocate memory.
void freeButNoMalloc(int *p, int x){
if (x) {
free(p);
//user forgot a return here.
}
free(p); // expected-warning {{Attempt to free released memory}}
}
struct HasPtr {
char *p;
};
char* reallocButNoMalloc(struct HasPtr *a, int c, int size) {
int *s;
char *b = realloc(a->p, size);
char *m = realloc(a->p, size); // expected-warning {{Attempt to free released memory}}
// We don't expect a use-after-free for a->P here because the warning above
// is a sink.
return a->p; // no-warning
}
// We should not warn in this case since the caller will presumably free a->p in all cases.
int reallocButNoMallocPR13674(struct HasPtr *a, int c, int size) {
int *s;
char *b = realloc(a->p, size);
if (b == 0)
return -1;
a->p = b;
return 0;
}
// Test realloc with no visible malloc.
void *test(void *ptr) {
void *newPtr = realloc(ptr, 4);
if (newPtr == 0) {
if (ptr)
free(ptr); // no-warning
}
return newPtr;
}
char *testLeakWithinReturn(char *str) {
return strdup(strdup(str)); // expected-warning{{leak}}
}
char *testWinLeakWithinReturn(char *str) {
return _strdup(_strdup(str)); // expected-warning{{leak}}
}
wchar_t *testWinWideLeakWithinReturn(wchar_t *str) {
return _wcsdup(_wcsdup(str)); // expected-warning{{leak}}
}
void passConstPtr(const char * ptr);
void testPassConstPointer() {
char * string = malloc(sizeof(char)*10);
passConstPtr(string);
return; // expected-warning {{leak}}
}
void testPassConstPointerIndirectly() {
char *p = malloc(1);
p++;
memcmp(p, p, sizeof(&p));
return; // expected-warning {{leak}}
}
void testPassConstPointerIndirectlyStruct() {
struct HasPtr hp;
hp.p = malloc(10);
memcmp(&hp, &hp, sizeof(hp));
return; // expected-warning {{Potential leak of memory pointed to by 'hp.p'}}
}
void testPassToSystemHeaderFunctionIndirectlyStruct() {
SomeStruct ss;
ss.p = malloc(1);
fakeSystemHeaderCall(&ss); // invalidates ss, making ss.p unreachable
// Technically a false negative here -- we know the system function won't free
// ss.p, but nothing else will either!
} // no-warning
void testPassToSystemHeaderFunctionIndirectlyStructFree() {
SomeStruct ss;
ss.p = malloc(1);
fakeSystemHeaderCall(&ss); // invalidates ss, making ss.p unreachable
free(ss.p);
} // no-warning
void testPassToSystemHeaderFunctionIndirectlyArray() {
int *p[1];
p[0] = malloc(sizeof(int));
fakeSystemHeaderCallIntPtr(p); // invalidates p, making p[0] unreachable
// Technically a false negative here -- we know the system function won't free
// p[0], but nothing else will either!
} // no-warning
void testPassToSystemHeaderFunctionIndirectlyArrayFree() {
int *p[1];
p[0] = malloc(sizeof(int));
fakeSystemHeaderCallIntPtr(p); // invalidates p, making p[0] unreachable
free(p[0]);
} // no-warning
int *testOffsetAllocate(size_t size) {
int *memoryBlock = (int *)malloc(size + sizeof(int));
return &memoryBlock[1]; // no-warning
}
void testOffsetDeallocate(int *memoryBlock) {
free(&memoryBlock[-1]); // no-warning
}
void testOffsetOfRegionFreed() {
__int64_t * array = malloc(sizeof(__int64_t)*2);
array += 1;
free(&array[0]); // expected-warning{{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
}
void testOffsetOfRegionFreed2() {
__int64_t *p = malloc(sizeof(__int64_t)*2);
p += 1;
free(p); // expected-warning{{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
}
void testOffsetOfRegionFreed3() {
char *r = malloc(sizeof(char));
r = r - 10;
free(r); // expected-warning {{Argument to free() is offset by -10 bytes from the start of memory allocated by malloc()}}
}
void testOffsetOfRegionFreedAfterFunctionCall() {
int *p = malloc(sizeof(int)*2);
p += 1;
myfoo(p);
free(p); // expected-warning{{Argument to free() is offset by 4 bytes from the start of memory allocated by malloc()}}
}
void testFixManipulatedPointerBeforeFree() {
int * array = malloc(sizeof(int)*2);
array += 1;
free(&array[-1]); // no-warning
}
void testFixManipulatedPointerBeforeFree2() {
char *r = malloc(sizeof(char));
r = r + 10;
free(r-10); // no-warning
}
void freeOffsetPointerPassedToFunction() {
__int64_t *p = malloc(sizeof(__int64_t)*2);
p[1] = 0;
p += 1;
myfooint(*p); // not passing the pointer, only a value pointed by pointer
free(p); // expected-warning {{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
}
int arbitraryInt();
void freeUnknownOffsetPointer() {
char *r = malloc(sizeof(char));
r = r + arbitraryInt(); // unable to reason about what the offset might be
free(r); // no-warning
}
void testFreeNonMallocPointerWithNoOffset() {
char c;
char *r = &c;
r = r + 10;
free(r-10); // expected-warning {{Argument to free() is the address of the local variable 'c', which is not memory allocated by malloc()}}
}
void testFreeNonMallocPointerWithOffset() {
char c;
char *r = &c;
free(r+1); // expected-warning {{Argument to free() is the address of the local variable 'c', which is not memory allocated by malloc()}}
}
void testOffsetZeroDoubleFree() {
int *array = malloc(sizeof(int)*2);
int *p = &array[0];
free(p);
free(&array[0]); // expected-warning{{Attempt to free released memory}}
}
void testOffsetPassedToStrlen() {
char * string = malloc(sizeof(char)*10);
string += 1;
int length = strlen(string); // expected-warning {{Potential leak of memory pointed to by 'string'}}
}
void testOffsetPassedToStrlenThenFree() {
char * string = malloc(sizeof(char)*10);
string += 1;
int length = strlen(string);
free(string); // expected-warning {{Argument to free() is offset by 1 byte from the start of memory allocated by malloc()}}
}
void testOffsetPassedAsConst() {
char * string = malloc(sizeof(char)*10);
string += 1;
passConstPtr(string);
free(string); // expected-warning {{Argument to free() is offset by 1 byte from the start of memory allocated by malloc()}}
}
char **_vectorSegments;
int _nVectorSegments;
void poolFreeC(void* s) {
free(s); // no-warning
}
void freeMemory() {
while (_nVectorSegments) {
poolFreeC(_vectorSegments[_nVectorSegments++]);
}
}
// PR16730
void testReallocEscaped(void **memory) {
*memory = malloc(47);
char *new_memory = realloc(*memory, 47);
if (new_memory != 0) {
*memory = new_memory;
}
}
// PR16558
void *smallocNoWarn(size_t size) {
if (size == 0) {
return malloc(1); // this branch is never called
}
else {
return malloc(size);
}
}
char *dupstrNoWarn(const char *s) {
const int len = strlen(s);
char *p = (char*) smallocNoWarn(len + 1);
strcpy(p, s); // no-warning
return p;
}
void *smallocWarn(size_t size) {
if (size == 2) {
return malloc(1);
}
else {
return malloc(size);
}
}
char *dupstrWarn(const char *s) {
const int len = strlen(s);
char *p = (char*) smallocWarn(len + 1);
strcpy(p, s); // expected-warning{{String copy function overflows destination buffer}}
return p;
}
int *radar15580979() {
int *data = (int *)malloc(32);
int *p = data ?: (int*)malloc(32); // no warning
return p;
}
// Some data structures may hold onto the pointer and free it later.
void testEscapeThroughSystemCallTakingVoidPointer1(void *queue) {
int *data = (int *)malloc(32);
fake_insque(queue, data); // no warning
}
void testEscapeThroughSystemCallTakingVoidPointer2(fake_rb_tree_t *rbt) {
int *data = (int *)malloc(32);
fake_rb_tree_init(rbt, data);
} //expected-warning{{Potential leak}}
void testEscapeThroughSystemCallTakingVoidPointer3(fake_rb_tree_t *rbt) {
int *data = (int *)malloc(32);
fake_rb_tree_init(rbt, data);
fake_rb_tree_insert_node(rbt, data); // no warning
}
struct IntAndPtr {
int x;
int *p;
};
void constEscape(const void *ptr);
void testConstEscapeThroughAnotherField() {
struct IntAndPtr s;
s.p = malloc(sizeof(int));
constEscape(&(s.x)); // could free s->p!
} // no-warning
+// PR15623
+int testNoCheckerDataPropogationFromLogicalOpOperandToOpResult(void) {
+ char *param = malloc(10);
+ char *value = malloc(10);
+ int ok = (param && value);
+ free(param);
+ free(value);
+ // Previously we ended up with 'Use of memory after it is freed' on return.
+ return ok; // no warning
+}
+
// ----------------------------------------------------------------------------
// False negatives.
void testMallocWithParam(int **p) {
*p = (int*) malloc(sizeof(int));
*p = 0; // FIXME: should warn here
}
void testMallocWithParam_2(int **p) {
*p = (int*) malloc(sizeof(int)); // no-warning
}
void testPassToSystemHeaderFunctionIndirectly() {
int *p = malloc(4);
p++;
fakeSystemHeaderCallInt(p);
// FIXME: This is a leak: if we think a system function won't free p, it
// won't free (p-1) either.
}
void testMallocIntoMalloc() {
StructWithPtr *s = malloc(sizeof(StructWithPtr));
s->memP = malloc(sizeof(int));
free(s);
} // FIXME: should warn here

Event Timeline