Newer
Older
//= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This defines CStringChecker, which is an assortment of checks on calls
// to functions in <string.h>.
//
//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis
committed
#include "ClangSACheckers.h"
#include "InterCheckerAPI.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek
committed
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Ted Kremenek
committed
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Benjamin Kramer
committed
#include "llvm/ADT/SmallString.h"
Benjamin Kramer
committed
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringSwitch.h"
using namespace clang;
namespace {
class CStringChecker : public Checker< eval::Call,
check::PreStmt<DeclStmt>,
check::LiveSymbols,
check::DeadSymbols,
check::RegionChanges
> {
mutable OwningPtr<BugType> BT_Null,
BT_Bounds,
BT_Overlap,
BT_NotCString,
BT_AdditionOverflow;
Jordy Rose
committed
mutable const char *CurrentFunctionDescription;
public:
/// The filter is used to filter out the diagnostics which are not enabled by
/// the user.
struct CStringChecksFilter {
DefaultBool CheckCStringNullArg;
DefaultBool CheckCStringOutOfBounds;
DefaultBool CheckCStringBufferOverlap;
DefaultBool CheckCStringNotNullTerm;
};
CStringChecksFilter Filter;
static void *getTag() { static int tag; return &tag; }
bool evalCall(const CallExpr *CE, CheckerContext &C) const;
void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
bool wantsRegionChangeUpdate(ProgramStateRef state) const;
Jordy Rose
committed
ProgramStateRef
checkRegionChanges(ProgramStateRef state,
Ted Kremenek
committed
const StoreManager::InvalidatedSymbols *,
ArrayRef<const MemRegion *> ExplicitRegions,
ArrayRef<const MemRegion *> Regions,
const CallOrObjCMessage *Call) const;
typedef void (CStringChecker::*FnCheck)(CheckerContext &,
const CallExpr *) const;
void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
ProgramStateRef state,
Ted Kremenek
committed
const Expr *Size,
const Expr *Source,
const Expr *Dest,
bool Restricted = false,
bool IsMempcpy = false) const;
Jordy Rose
committed
void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek
committed
void evalstrLengthCommon(CheckerContext &C,
const CallExpr *CE,
bool IsStrnlen = false) const;
Jordy Rose
committed
void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek
committed
void evalStrcpyCommon(CheckerContext &C,
const CallExpr *CE,
bool returnEnd,
bool isBounded,
bool isAppending) const;
void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani
committed
void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani
committed
void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani
committed
void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek
committed
void evalStrcmpCommon(CheckerContext &C,
const CallExpr *CE,
bool isBounded = false,
bool ignoreCase = false) const;
Lenny Maiorani
committed
// Utility methods
std::pair<ProgramStateRef , ProgramStateRef >
static assumeZero(CheckerContext &C,
ProgramStateRef state, SVal V, QualType Ty);
static ProgramStateRef setCStringLength(ProgramStateRef state,
Ted Kremenek
committed
const MemRegion *MR,
SVal strLength);
static SVal getCStringLengthForRegion(CheckerContext &C,
ProgramStateRef &state,
Ted Kremenek
committed
const Expr *Ex,
const MemRegion *MR,
bool hypothetical);
Ted Kremenek
committed
SVal getCStringLength(CheckerContext &C,
ProgramStateRef &state,
Ted Kremenek
committed
const Expr *Ex,
SVal Buf,
bool hypothetical = false) const;
Jordy Rose
committed
Lenny Maiorani
committed
const StringLiteral *getCStringLiteral(CheckerContext &C,
ProgramStateRef &state,
Lenny Maiorani
committed
const Expr *expr,
SVal val) const;
static ProgramStateRef InvalidateBuffer(CheckerContext &C,
ProgramStateRef state,
Ted Kremenek
committed
const Expr *Ex, SVal V);
Ted Kremenek
committed
static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
const MemRegion *MR);
Jordy Rose
committed
// Re-usable checks
ProgramStateRef checkNonNull(CheckerContext &C,
ProgramStateRef state,
Ted Kremenek
committed
const Expr *S,
SVal l) const;
ProgramStateRef CheckLocation(CheckerContext &C,
ProgramStateRef state,
Ted Kremenek
committed
const Expr *S,
SVal l,
const char *message = NULL) const;
ProgramStateRef CheckBufferAccess(CheckerContext &C,
ProgramStateRef state,
Ted Kremenek
committed
const Expr *Size,
const Expr *FirstBuf,
const Expr *SecondBuf,
const char *firstMessage = NULL,
const char *secondMessage = NULL,
bool WarnAboutSize = false) const;
ProgramStateRef CheckBufferAccess(CheckerContext &C,
ProgramStateRef state,
Ted Kremenek
committed
const Expr *Size,
const Expr *Buf,
const char *message = NULL,
bool WarnAboutSize = false) const {
Jordy Rose
committed
// This is a convenience override.
Jordy Rose
committed
return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
WarnAboutSize);
Jordy Rose
committed
}
ProgramStateRef CheckOverlap(CheckerContext &C,
ProgramStateRef state,
Ted Kremenek
committed
const Expr *Size,
const Expr *First,
const Expr *Second) const;
void emitOverlapBug(CheckerContext &C,
ProgramStateRef state,
Ted Kremenek
committed
const Stmt *First,
const Stmt *Second) const;
ProgramStateRef checkAdditionOverflow(CheckerContext &C,
ProgramStateRef state,
Ted Kremenek
committed
NonLoc left,
NonLoc right) const;
};
Jordy Rose
committed
class CStringLength {
public:
typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
};
} //end anonymous namespace
Jordy Rose
committed
namespace clang {
Jordy Rose
committed
template <>
Ted Kremenek
committed
struct ProgramStateTrait<CStringLength>
: public ProgramStatePartialTrait<CStringLength::EntryMap> {
Jordy Rose
committed
static void *GDMIndex() { return CStringChecker::getTag(); }
};
}
Jordy Rose
committed
Jordy Rose
committed
//===----------------------------------------------------------------------===//
// Individual checks and utility methods.
//===----------------------------------------------------------------------===//
std::pair<ProgramStateRef , ProgramStateRef >
CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
Jordy Rose
committed
QualType Ty) {
DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
if (!val)
return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
SValBuilder &svalBuilder = C.getSValBuilder();
DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rose
committed
}
ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
ProgramStateRef state,
const Expr *S, SVal l) const {
Jordy Rose
committed
// If a previous check has failed, propagate the failure.
if (!state)
return NULL;
ProgramStateRef stateNull, stateNonNull;
llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rose
committed
if (stateNull && !stateNonNull) {
if (!Filter.CheckCStringNullArg)
return NULL;
ExplodedNode *N = C.generateSink(stateNull);
if (!N)
return NULL;
Jordy Rose
committed
if (!BT_Null)
BT_Null.reset(new BuiltinBug("Unix API",
"Null pointer argument in call to byte string function"));
SmallString<80> buf;
Jordy Rose
committed
llvm::raw_svector_ostream os(buf);
assert(CurrentFunctionDescription);
os << "Null pointer argument in call to " << CurrentFunctionDescription;
// Generate a report for this bug.
BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
BugReport *report = new BugReport(*BT, os.str(), N);
report->addRange(S->getSourceRange());
Ted Kremenek
committed
report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, S,
report));
C.EmitReport(report);
return NULL;
}
// From here on, assume that the value is non-null.
Jordy Rose
committed
assert(stateNonNull);
return stateNonNull;
}
// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
ProgramStateRef state,
const Expr *S, SVal l,
Jordy Rose
committed
const char *warningMsg) const {
Jordy Rose
committed
// If a previous check has failed, propagate the failure.
if (!state)
return NULL;
// Check for out of bound array element access.
const MemRegion *R = l.getAsRegion();
if (!R)
return state;
const ElementRegion *ER = dyn_cast<ElementRegion>(R);
if (!ER)
return state;
assert(ER->getValueType() == C.getASTContext().CharTy &&
"CheckLocation should only be called with char* ElementRegions");
// Get the size of the array.
const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
SValBuilder &svalBuilder = C.getSValBuilder();
SVal Extent =
svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
// Get the index of the accessed element.
DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
if (StOutBound && !StInBound) {
ExplodedNode *N = C.generateSink(StOutBound);
if (!N)
return NULL;
Jordy Rose
committed
if (!BT_Bounds) {
BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
"Byte string function accesses out-of-bound array element"));
}
BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
// Generate a report for this bug.
BugReport *report;
Jordy Rose
committed
if (warningMsg) {
report = new BugReport(*BT, warningMsg, N);
} else {
Jordy Rose
committed
assert(CurrentFunctionDescription);
assert(CurrentFunctionDescription[0] != '\0');
SmallString<80> buf;
Jordy Rose
committed
llvm::raw_svector_ostream os(buf);
os << (char)toupper(CurrentFunctionDescription[0])
<< &CurrentFunctionDescription[1]
<< " accesses out-of-bound array element";
report = new BugReport(*BT, os.str(), N);
}
// FIXME: It would be nice to eventually make this diagnostic more clear,
// e.g., by referencing the original declaration or by saying *why* this
// reference is outside the range.
report->addRange(S->getSourceRange());
C.EmitReport(report);
return NULL;
}
// Array bound check succeeded. From this point forward the array bound
// should always succeed.
return StInBound;
}
ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
ProgramStateRef state,
const Expr *Size,
const Expr *FirstBuf,
const Expr *SecondBuf,
Jordy Rose
committed
const char *firstMessage,
Jordy Rose
committed
const char *secondMessage,
bool WarnAboutSize) const {
Jordy Rose
committed
// If a previous check has failed, propagate the failure.
if (!state)
return NULL;
SValBuilder &svalBuilder = C.getSValBuilder();
ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek
committed
const LocationContext *LCtx = C.getLocationContext();
QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
// Check that the first buffer is non-null.
Ted Kremenek
committed
SVal BufVal = state->getSVal(FirstBuf, LCtx);
state = checkNonNull(C, state, FirstBuf, BufVal);
if (!state)
return NULL;
// If out-of-bounds checking is turned off, skip the rest.
if (!Filter.CheckCStringOutOfBounds)
return state;
Jordy Rose
committed
// Get the access length and make sure it is known.
Jordy Rose
committed
// FIXME: This assumes the caller has already checked that the access length
// is positive. And that it's unsigned.
Ted Kremenek
committed
SVal LengthVal = state->getSVal(Size, LCtx);
Jordy Rose
committed
NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
if (!Length)
return state;
// Compute the offset of the last element to be accessed: size-1.
NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
*Length, One, sizeTy));
// Check that the first buffer is sufficiently long.
SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Jordy Rose
committed
const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
LastOffset, PtrTy);
Jordy Rose
committed
state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
// If the buffer isn't large enough, abort.
if (!state)
return NULL;
}
// If there's a second buffer, check it as well.
if (SecondBuf) {
Ted Kremenek
committed
BufVal = state->getSVal(SecondBuf, LCtx);
state = checkNonNull(C, state, SecondBuf, BufVal);
if (!state)
return NULL;
BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Jordy Rose
committed
const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
LastOffset, PtrTy);
Jordy Rose
committed
state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
}
}
// Large enough or not, return this state!
return state;
}
ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
ProgramStateRef state,
Jordy Rose
committed
const Expr *Size,
const Expr *First,
const Expr *Second) const {
if (!Filter.CheckCStringBufferOverlap)
return state;
// Do a simple check for overlap: if the two arguments are from the same
// buffer, see if the end of the first is greater than the start of the second
// or vice versa.
Jordy Rose
committed
// If a previous check has failed, propagate the failure.
if (!state)
return NULL;
ProgramStateRef stateTrue, stateFalse;
// Get the buffer values and make sure they're known locations.
Ted Kremenek
committed
const LocationContext *LCtx = C.getLocationContext();
SVal firstVal = state->getSVal(First, LCtx);
SVal secondVal = state->getSVal(Second, LCtx);
Loc *firstLoc = dyn_cast<Loc>(&firstVal);
if (!firstLoc)
return state;
Loc *secondLoc = dyn_cast<Loc>(&secondVal);
if (!secondLoc)
return state;
// Are the two values the same?
SValBuilder &svalBuilder = C.getSValBuilder();
llvm::tie(stateTrue, stateFalse) =
state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
if (stateTrue && !stateFalse) {
// If the values are known to be equal, that's automatically an overlap.
emitOverlapBug(C, stateTrue, First, Second);
return NULL;
}
// assume the two expressions are not equal.
assert(stateFalse);
state = stateFalse;
// Which value comes first?
QualType cmpTy = svalBuilder.getConditionType();
SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
*firstLoc, *secondLoc, cmpTy);
DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
if (!reverseTest)
return state;
llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
if (stateTrue) {
if (stateFalse) {
// If we don't know which one comes first, we can't perform this test.
return state;
} else {
// Switch the values so that firstVal is before secondVal.
Loc *tmpLoc = firstLoc;
firstLoc = secondLoc;
secondLoc = tmpLoc;
// Switch the Exprs as well, so that they still correspond.
const Expr *tmpExpr = First;
First = Second;
Second = tmpExpr;
}
}
// Get the length, and make sure it too is known.
Ted Kremenek
committed
SVal LengthVal = state->getSVal(Size, LCtx);
NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
if (!Length)
return state;
// Convert the first buffer's start address to char*.
// Bail out if the cast fails.
ASTContext &Ctx = svalBuilder.getContext();
QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
First->getType());
Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
if (!FirstStartLoc)
return state;
// Compute the end of the first buffer. Bail out if THAT fails.
SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
*FirstStartLoc, *Length, CharPtrTy);
Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
if (!FirstEndLoc)
return state;
// Is the end of the first buffer past the start of the second buffer?
SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
*FirstEndLoc, *secondLoc, cmpTy);
DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
if (!OverlapTest)
return state;
llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
if (stateTrue && !stateFalse) {
// Overlap!
emitOverlapBug(C, stateTrue, First, Second);
return NULL;
}
// assume the two expressions don't overlap.
assert(stateFalse);
return stateFalse;
}
void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
const Stmt *First, const Stmt *Second) const {
ExplodedNode *N = C.generateSink(state);
if (!N)
return;
if (!BT_Overlap)
BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
// Generate a report for this bug.
BugReport *report =
new BugReport(*BT_Overlap,
"Arguments must not be overlapping buffers", N);
report->addRange(First->getSourceRange());
report->addRange(Second->getSourceRange());
C.EmitReport(report);
}
ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
ProgramStateRef state,
NonLoc left,
NonLoc right) const {
// If out-of-bounds checking is turned off, skip the rest.
if (!Filter.CheckCStringOutOfBounds)
return state;
// If a previous check has failed, propagate the failure.
if (!state)
return NULL;
SValBuilder &svalBuilder = C.getSValBuilder();
BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
QualType sizeTy = svalBuilder.getContext().getSizeType();
const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
SVal maxMinusRight;
if (isa<nonloc::ConcreteInt>(right)) {
maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
sizeTy);
} else {
// Try switching the operands. (The order of these two assignments is
// important!)
maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
sizeTy);
left = right;
}
if (NonLoc *maxMinusRightNL = dyn_cast<NonLoc>(&maxMinusRight)) {
QualType cmpTy = svalBuilder.getConditionType();
// If left > max - right, we have an overflow.
SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
*maxMinusRightNL, cmpTy);
ProgramStateRef stateOverflow, stateOkay;
llvm::tie(stateOverflow, stateOkay) =
state->assume(cast<DefinedOrUnknownSVal>(willOverflow));
if (stateOverflow && !stateOkay) {
// We have an overflow. Emit a bug report.
ExplodedNode *N = C.generateSink(stateOverflow);
if (!N)
return NULL;
if (!BT_AdditionOverflow)
BT_AdditionOverflow.reset(new BuiltinBug("API",
"Sum of expressions causes overflow"));
// This isn't a great error message, but this should never occur in real
// code anyway -- you'd have to create a buffer longer than a size_t can
// represent, which is sort of a contradiction.
Jordy Rose
committed
const char *warning =
"This expression will create a string whose length is too big to "
"be represented as a size_t";
// Generate a report for this bug.
Jordy Rose
committed
BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
C.EmitReport(report);
return NULL;
}
// From now on, assume an overflow didn't occur.
assert(stateOkay);
state = stateOkay;
}
return state;
}
ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
const MemRegion *MR,
SVal strLength) {
assert(!strLength.isUndef() && "Attempt to set an undefined string length");
MR = MR->StripCasts();
switch (MR->getKind()) {
case MemRegion::StringRegionKind:
// FIXME: This can happen if we strcpy() into a string region. This is
// undefined [C99 6.4.5p6], but we should still warn about it.
return state;
case MemRegion::SymbolicRegionKind:
case MemRegion::AllocaRegionKind:
case MemRegion::VarRegionKind:
case MemRegion::FieldRegionKind:
case MemRegion::ObjCIvarRegionKind:
// These are the types we can currently track string lengths for.
break;
case MemRegion::ElementRegionKind:
// FIXME: Handle element regions by upper-bounding the parent region's
// string length.
return state;
default:
// Other regions (mostly non-data) can't have a reliable C string length.
// For now, just ignore the change.
// FIXME: These are rare but not impossible. We should output some kind of
// warning for things like strcpy((char[]){'a', 0}, "b");
return state;
}
if (strLength.isUnknown())
return state->remove<CStringLength>(MR);
return state->set<CStringLength>(MR, strLength);
}
SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
ProgramStateRef &state,
Jordy Rose
committed
const Expr *Ex,
const MemRegion *MR,
bool hypothetical) {
if (!hypothetical) {
// If there's a recorded length, go ahead and return it.
const SVal *Recorded = state->get<CStringLength>(MR);
if (Recorded)
return *Recorded;
}
Jordy Rose
committed
// Otherwise, get a new symbol and update the state.
unsigned Count = C.getCurrentBlockCount();
SValBuilder &svalBuilder = C.getSValBuilder();
QualType sizeTy = svalBuilder.getContext().getSizeType();
SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
MR, Ex, sizeTy, Count);
if (!hypothetical)
state = state->set<CStringLength>(MR, strLength);
Jordy Rose
committed
}
SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
const Expr *Ex, SVal Buf,
bool hypothetical) const {
Jordy Rose
committed
const MemRegion *MR = Buf.getAsRegion();
if (!MR) {
// If we can't get a region, see if it's something we /know/ isn't a
// C string. In the context of locations, the only time we can issue such
// a warning is for labels.
if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
if (!Filter.CheckCStringNotNullTerm)
return UndefinedVal();
if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose
committed
if (!BT_NotCString)
BT_NotCString.reset(new BuiltinBug("Unix API",
"Argument is not a null-terminated string."));
Jordy Rose
committed
SmallString<120> buf;
Jordy Rose
committed
llvm::raw_svector_ostream os(buf);
Jordy Rose
committed
assert(CurrentFunctionDescription);
os << "Argument to " << CurrentFunctionDescription
<< " is the address of the label '" << Label->getLabel()->getName()
Jordy Rose
committed
<< "', which is not a null-terminated string";
// Generate a report for this bug.
BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose
committed
os.str(), N);
report->addRange(Ex->getSourceRange());
C.EmitReport(report);
}
return UndefinedVal();
Jordy Rose
committed
}
Jordy Rose
committed
// If it's not a region and not a label, give up.
return UnknownVal();
}
Jordy Rose
committed
Jordy Rose
committed
// If we have a region, strip casts from it and see if we can figure out
// its length. For anything we can't figure out, just return UnknownVal.
MR = MR->StripCasts();
switch (MR->getKind()) {
case MemRegion::StringRegionKind: {
// Modifying the contents of string regions is undefined [C99 6.4.5p6],
// so we can assume that the byte length is the correct C string length.
SValBuilder &svalBuilder = C.getSValBuilder();
QualType sizeTy = svalBuilder.getContext().getSizeType();
const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rose
committed
}
case MemRegion::SymbolicRegionKind:
case MemRegion::AllocaRegionKind:
case MemRegion::VarRegionKind:
case MemRegion::FieldRegionKind:
case MemRegion::ObjCIvarRegionKind:
return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rose
committed
case MemRegion::CompoundLiteralRegionKind:
// FIXME: Can we track this? Is it necessary?
return UnknownVal();
case MemRegion::ElementRegionKind:
// FIXME: How can we handle this? It's not good enough to subtract the
// offset from the base string length; consider "123\x00567" and &a[5].
return UnknownVal();
default:
// Other regions (mostly non-data) can't have a reliable C string length.
// In this case, an error is emitted and UndefinedVal is returned.
// The caller should always be prepared to handle this case.
if (!Filter.CheckCStringNotNullTerm)
return UndefinedVal();
if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose
committed
if (!BT_NotCString)
BT_NotCString.reset(new BuiltinBug("Unix API",
"Argument is not a null-terminated string."));
Jordy Rose
committed
SmallString<120> buf;
Jordy Rose
committed
llvm::raw_svector_ostream os(buf);
Jordy Rose
committed
assert(CurrentFunctionDescription);
os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rose
committed
if (SummarizeRegion(os, C.getASTContext(), MR))
os << ", which is not a null-terminated string";
else
os << "not a null-terminated string";
// Generate a report for this bug.
BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose
committed
os.str(), N);
report->addRange(Ex->getSourceRange());
C.EmitReport(report);
Jordy Rose
committed
}
Jordy Rose
committed
return UndefinedVal();
Jordy Rose
committed
}
}
Lenny Maiorani
committed
const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maiorani
committed
// Get the memory region pointed to by the val.
const MemRegion *bufRegion = val.getAsRegion();
if (!bufRegion)
return NULL;
// Strip casts off the memory region.
bufRegion = bufRegion->StripCasts();
// Cast the memory region to a string region.
const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
if (!strRegion)
return NULL;
// Return the actual string in the string region.
return strRegion->getStringLiteral();
}
ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
ProgramStateRef state,
const Expr *E, SVal V) {
Loc *L = dyn_cast<Loc>(&V);
if (!L)
return state;
// FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
// some assumptions about the value that CFRefCount can't. Even so, it should
// probably be refactored.
if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
const MemRegion *R = MR->getRegion()->StripCasts();
// Are we dealing with an ElementRegion? If so, we should be invalidating
// the super-region.
if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
R = ER->getSuperRegion();
// FIXME: What about layers of ElementRegions?
}
// Invalidate this region.
unsigned Count = C.getCurrentBlockCount();
Ted Kremenek
committed
const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
return state->invalidateRegions(R, E, Count, LCtx);
}
// If we have a non-region value by chance, just remove the binding.
// FIXME: is this necessary or correct? This handles the non-Region
// cases. Is it ever valid to store to these?
return state->unbindLoc(*L);
}
Ted Kremenek
committed
bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Rose
committed
const MemRegion *MR) {
const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Rose
committed
Jordy Rose
committed
switch (MR->getKind()) {
Jordy Rose
committed
case MemRegion::FunctionTextRegionKind: {
Jordy Rose
committed
const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose
committed
if (FD)
Benjamin Kramer
committed
os << "the address of the function '" << *FD << '\'';
Jordy Rose
committed
else
os << "the address of a function";
return true;
}
case MemRegion::BlockTextRegionKind:
os << "block text";
return true;
case MemRegion::BlockDataRegionKind:
os << "a block";
return true;
case MemRegion::CXXThisRegionKind:
case MemRegion::CXXTempObjectRegionKind:
os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Rose
committed
return true;
case MemRegion::VarRegionKind:
os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Rose
committed
return true;
case MemRegion::FieldRegionKind:
os << "a field of type " << TVR->getValueType().getAsString();
Jordy Rose
committed
return true;
case MemRegion::ObjCIvarRegionKind:
os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Rose
committed
return true;
default:
return false;
}
}
Jordy Rose
committed
//===----------------------------------------------------------------------===//
// evaluation of individual function calls.
Jordy Rose
committed
//===----------------------------------------------------------------------===//
void CStringChecker::evalCopyCommon(CheckerContext &C,
const CallExpr *CE,
ProgramStateRef state,
Jordy Rose
committed
const Expr *Size, const Expr *Dest,
const Expr *Source, bool Restricted,
bool IsMempcpy) const {
Jordy Rose
committed
CurrentFunctionDescription = "memory copy function";
Jordy Rose
committed
// See if the size argument is zero.
Ted Kremenek
committed
const LocationContext *LCtx = C.getLocationContext();
SVal sizeVal = state->getSVal(Size, LCtx);
Jordy Rose
committed
ProgramStateRef stateZeroSize, stateNonZeroSize;
llvm::tie(stateZeroSize, stateNonZeroSize) =
assumeZero(C, state, sizeVal, sizeTy);
Jordy Rose
committed
// Get the value of the Dest.
Ted Kremenek
committed
SVal destVal = state->getSVal(Dest, LCtx);
// If the size is zero, there won't be any actual memory access, so
// just bind the return value to the destination buffer and return.
if (stateZeroSize) {
Ted Kremenek
committed
stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
C.addTransition(stateZeroSize);
Jordy Rose
committed
// If the size can be nonzero, we have to check the other arguments.
state = stateNonZeroSize;
// Ensure the destination is not null. If it is NULL there will be a
// NULL pointer dereference.
state = checkNonNull(C, state, Dest, destVal);
if (!state)
return;
// Get the value of the Src.
Ted Kremenek
committed
SVal srcVal = state->getSVal(Source, LCtx);
// Ensure the source is not null. If it is NULL there will be a
// NULL pointer dereference.
state = checkNonNull(C, state, Source, srcVal);
if (!state)
return;
// Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rose
committed
const char * const writeWarning =
"Memory copy function overflows destination buffer";
state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rose
committed
writeWarning, /* sourceWarning = */ NULL);
Jordy Rose
committed
if (Restricted)
state = CheckOverlap(C, state, Size, Dest, Source);
if (!state)
return;
Jordy Rose
committed
// If this is mempcpy, get the byte after the last byte copied and
// bind the expr.
if (IsMempcpy) {
loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
assert(destRegVal && "Destination should be a known MemRegionVal here");
// Get the length to copy.
NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&sizeVal);
if (lenValNonLoc) {
// Get the byte after the last byte copied.
SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
*destRegVal,
*lenValNonLoc,
Dest->getType());
// The byte after the last byte copied is the return value.
Ted Kremenek
committed
state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose
committed
} else {
// If we don't know how much we copied, we can at least
// conjure a return value for later.
unsigned Count = C.getCurrentBlockCount();
SVal result =
Ted Kremenek
committed
C.getSValBuilder().getConjuredSymbolVal(NULL, CE, LCtx, Count);
Ted Kremenek
committed
state = state->BindExpr(CE, LCtx, result);
} else {
// All other copies return the destination buffer.
// (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek
committed
state = state->BindExpr(CE, LCtx, destVal);
}
// Invalidate the destination.
// FIXME: Even if we can't perfectly model the copy, we should see if we
// can use LazyCompoundVals to copy the source values into the destination.
// This would probably remove any existing bindings past the end of the
// copied region, but that's still an improvement over blank invalidation.
Ted Kremenek
committed
state = InvalidateBuffer(C, state, Dest,
state->getSVal(Dest, C.getLocationContext()));
C.addTransition(state);
Jordy Rose
committed
}
}
void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose
committed
// void *memcpy(void *restrict dst, const void *restrict src, size_t n);
// The return value is the address of the destination buffer.
const Expr *Dest = CE->getArg(0);
ProgramStateRef state = C.getState();
Jordy Rose
committed
evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
}
void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
// void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
// The return value is a pointer to the byte following the last written byte.
const Expr *Dest = CE->getArg(0);
ProgramStateRef state = C.getState();
evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);