本文整理汇总了C++中CheckerContext类的典型用法代码示例。如果您正苦于以下问题:C++ CheckerContext类的具体用法?C++ CheckerContext怎么用?C++ CheckerContext使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CheckerContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1:
/// Returns the released value if M is a call a setter that releases
/// and nils out its underlying instance variable.
SymbolRef
ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M,
CheckerContext &C) const {
SVal ReceiverVal = M.getReceiverSVal();
if (!ReceiverVal.isValid())
return nullptr;
if (M.getNumArgs() == 0)
return nullptr;
if (!M.getArgExpr(0)->getType()->isObjCRetainableType())
return nullptr;
// Is the first argument nil?
SVal Arg = M.getArgSVal(0);
ProgramStateRef notNilState, nilState;
std::tie(notNilState, nilState) =
M.getState()->assume(Arg.castAs<DefinedOrUnknownSVal>());
if (!(nilState && !notNilState))
return nullptr;
const ObjCPropertyDecl *Prop = M.getAccessedProperty();
if (!Prop)
return nullptr;
ObjCIvarDecl *PropIvarDecl = Prop->getPropertyIvarDecl();
if (!PropIvarDecl)
return nullptr;
ProgramStateRef State = C.getState();
SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal);
Optional<Loc> LValLoc = LVal.getAs<Loc>();
if (!LValLoc)
return nullptr;
SVal CurrentValInIvar = State->getSVal(LValLoc.getValue());
return CurrentValInIvar.getAsSymbol();
}
示例2: isARCNilInitializedLocal
/// Returns true if \param S is a DeclStmt for a local variable that
/// ObjC automated reference counting initialized with zero.
static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S) {
// We suppress diagnostics for ARC zero-initialized _Nonnull locals. This
// prevents false positives when a _Nonnull local variable cannot be
// initialized with an initialization expression:
// NSString * _Nonnull s; // no-warning
// @autoreleasepool {
// s = ...
// }
//
// FIXME: We should treat implicitly zero-initialized _Nonnull locals as
// uninitialized in Sema's UninitializedValues analysis to warn when a use of
// the zero-initialized definition will unexpectedly yield nil.
// Locals are only zero-initialized when automated reference counting
// is turned on.
if (!C.getASTContext().getLangOpts().ObjCAutoRefCount)
return false;
auto *DS = dyn_cast<DeclStmt>(S);
if (!DS || !DS->isSingleDecl())
return false;
auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
if (!VD)
return false;
// Sema only zero-initializes locals with ObjCLifetimes.
if(!VD->getType().getQualifiers().hasObjCLifetime())
return false;
const Expr *Init = VD->getInit();
assert(Init && "ObjC local under ARC without initializer");
// Return false if the local is explicitly initialized (e.g., with '= nil').
if (!isa<ImplicitValueInitExpr>(Init))
return false;
return true;
}
示例3: PreVisitBinaryOperator
void DivZeroChecker::PreVisitBinaryOperator(CheckerContext &C,
const BinaryOperator *B) {
BinaryOperator::Opcode Op = B->getOpcode();
if (Op != BO_Div &&
Op != BO_Rem &&
Op != BO_DivAssign &&
Op != BO_RemAssign)
return;
if (!B->getRHS()->getType()->isIntegerType() ||
!B->getRHS()->getType()->isScalarType())
return;
SVal Denom = C.getState()->getSVal(B->getRHS());
const DefinedSVal *DV = dyn_cast<DefinedSVal>(&Denom);
// Divide-by-undefined handled in the generic checking for uses of
// undefined values.
if (!DV)
return;
// Check for divide by zero.
ConstraintManager &CM = C.getConstraintManager();
const GRState *stateNotZero, *stateZero;
llvm::tie(stateNotZero, stateZero) = CM.assumeDual(C.getState(), *DV);
if (stateZero && !stateNotZero) {
if (ExplodedNode *N = C.generateSink(stateZero)) {
if (!BT)
BT = new BuiltinBug("Division by zero");
EnhancedBugReport *R =
new EnhancedBugReport(*BT, BT->getDescription(), N);
R->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue,
bugreporter::GetDenomExpr(N));
C.EmitReport(R);
}
return;
}
// If we get here, then the denom should not be zero. We abandon the implicit
// zero denom case for now.
C.addTransition(stateNotZero);
}
示例4: evalCall
bool OSAtomicChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
const ProgramState *state = C.getState();
const Expr *Callee = CE->getCallee();
SVal L = state->getSVal(Callee);
const FunctionDecl *FD = L.getAsFunctionDecl();
if (!FD)
return false;
const IdentifierInfo *II = FD->getIdentifier();
if (!II)
return false;
StringRef FName(II->getName());
// Check for compare and swap.
if (FName.startswith("OSAtomicCompareAndSwap") ||
FName.startswith("objc_atomicCompareAndSwap"))
return evalOSAtomicCompareAndSwap(C, CE);
// FIXME: Other atomics.
return false;
}
示例5: modelUse
void MoveChecker::modelUse(ProgramStateRef State, const MemRegion *Region,
const CXXRecordDecl *RD, MisuseKind MK,
CheckerContext &C) const {
assert(!C.isDifferent() && "No transitions should have been made by now");
const RegionState *RS = State->get<TrackedRegionMap>(Region);
ObjectKind OK = classifyObject(Region, RD);
// Just in case: if it's not a smart pointer but it does have operator *,
// we shouldn't call the bug a dereference.
if (MK == MK_Dereference && OK.StdKind != SK_SmartPtr)
MK = MK_FunCall;
if (!RS || !shouldWarnAbout(OK, MK)
|| isInMoveSafeContext(C.getLocationContext())) {
// Finalize changes made by the caller.
C.addTransition(State);
return;
}
// Don't report it in case if any base region is already reported.
// But still generate a sink in case of UB.
// And still finalize changes made by the caller.
if (isAnyBaseRegionReported(State, Region)) {
if (misuseCausesCrash(MK)) {
C.generateSink(State, C.getPredecessor());
} else {
C.addTransition(State);
}
return;
}
ExplodedNode *N = reportBug(Region, RD, C, MK);
// If the program has already crashed on this path, don't bother.
if (N->isSink())
return;
State = State->set<TrackedRegionMap>(Region, RegionState::getReported());
C.addTransition(State, N);
}
示例6: PreVisitCallExpr
void MacOSXAPIChecker::PreVisitCallExpr(CheckerContext &C, const CallExpr *CE) {
// FIXME: Mostly copy and paste from UnixAPIChecker. Should refactor.
const GRState *state = C.getState();
const Expr *Callee = CE->getCallee();
const FunctionTextRegion *Fn =
dyn_cast_or_null<FunctionTextRegion>(state->getSVal(Callee).getAsRegion());
if (!Fn)
return;
const IdentifierInfo *FI = Fn->getDecl()->getIdentifier();
if (!FI)
return;
const SubCheck &SC =
llvm::StringSwitch<SubCheck>(FI->getName())
.Case("dispatch_once", SubCheck(CheckDispatchOnce, BTypes[DispatchOnce]))
.Case("dispatch_once_f", SubCheck(CheckDispatchOnce,
BTypes[DispatchOnceF]))
.Default(SubCheck());
SC.run(C, CE, FI);
}
示例7: checkPreStmt
void MacOSXAPIChecker::checkPreStmt(const CallExpr *CE,
CheckerContext &C) const {
// FIXME: This sort of logic is common to several checkers, including
// UnixAPIChecker, PthreadLockChecker, and CStringChecker. Should refactor.
const ProgramState *state = C.getState();
const Expr *Callee = CE->getCallee();
const FunctionDecl *Fn = state->getSVal(Callee).getAsFunctionDecl();
if (!Fn)
return;
const IdentifierInfo *FI = Fn->getIdentifier();
if (!FI)
return;
SubChecker SC =
llvm::StringSwitch<SubChecker>(FI->getName())
.Cases("dispatch_once", "dispatch_once_f",
&MacOSXAPIChecker::CheckDispatchOnce)
.Default(NULL);
if (SC)
(this->*SC)(C, CE, FI);
}
示例8: checkPreStmt
void UnixAPIChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
// Get the callee. All the functions we care about are C functions
// with simple identifiers.
const GRState *state = C.getState();
const Expr *Callee = CE->getCallee();
const FunctionDecl *Fn = state->getSVal(Callee).getAsFunctionDecl();
if (!Fn)
return;
const IdentifierInfo *FI = Fn->getIdentifier();
if (!FI)
return;
SubChecker SC =
llvm::StringSwitch<SubChecker>(FI->getName())
.Case("open", &UnixAPIChecker::CheckOpen)
.Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
.Case("malloc", &UnixAPIChecker::CheckMallocZero)
.Default(NULL);
if (SC)
(this->*SC)(C, CE);
}
示例9: preVisitObjCMessage
void NilArgChecker::preVisitObjCMessage(CheckerContext &C,
ObjCMessage msg)
{
const ObjCInterfaceType *ReceiverType = GetReceiverType(msg);
if (!ReceiverType)
return;
if (isNSString(ReceiverType->getDecl()->getIdentifier()->getName())) {
Selector S = msg.getSelector();
if (S.isUnarySelector())
return;
// FIXME: This is going to be really slow doing these checks with
// lexical comparisons.
std::string NameStr = S.getAsString();
llvm::StringRef Name(NameStr);
assert(!Name.empty());
// FIXME: Checking for initWithFormat: will not work in most cases
// yet because [NSString alloc] returns id, not NSString*. We will
// need support for tracking expected-type information in the analyzer
// to find these errors.
if (Name == "caseInsensitiveCompare:" ||
Name == "compare:" ||
Name == "compare:options:" ||
Name == "compare:options:range:" ||
Name == "compare:options:range:locale:" ||
Name == "componentsSeparatedByCharactersInSet:" ||
Name == "initWithFormat:") {
if (isNil(msg.getArgSVal(0, C.getState())))
WarnNilArg(C, msg, 0);
}
}
}
示例10: checkPreObjCMessage
void ObjCSuperDeallocChecker::checkPreObjCMessage(const ObjCMethodCall &M,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
SymbolRef ReceiverSymbol = M.getReceiverSVal().getAsSymbol();
if (!ReceiverSymbol) {
diagnoseCallArguments(M, C);
return;
}
bool AlreadyCalled = State->contains<CalledSuperDealloc>(ReceiverSymbol);
if (!AlreadyCalled)
return;
StringRef Desc;
if (isSuperDeallocMessage(M)) {
Desc = "[super dealloc] should not be called multiple times";
} else {
Desc = StringRef();
}
reportUseAfterDealloc(ReceiverSymbol, Desc, M.getOriginExpr(), C);
}
示例11: checkPreStmt
void DivZeroChecker::checkPreStmt(const BinaryOperator *B,
CheckerContext &C) const {
BinaryOperator::Opcode Op = B->getOpcode();
if (Op != BO_Div &&
Op != BO_Rem &&
Op != BO_DivAssign &&
Op != BO_RemAssign)
return;
if (!B->getRHS()->getType()->isScalarType())
return;
SVal Denom = C.getState()->getSVal(B->getRHS(), C.getLocationContext());
Optional<DefinedSVal> DV = Denom.getAs<DefinedSVal>();
// Divide-by-undefined handled in the generic checking for uses of
// undefined values.
if (!DV)
return;
// Check for divide by zero.
ConstraintManager &CM = C.getConstraintManager();
ProgramStateRef stateNotZero, stateZero;
llvm::tie(stateNotZero, stateZero) = CM.assumeDual(C.getState(), *DV);
if (!stateNotZero) {
assert(stateZero);
reportBug("Division by zero", stateZero, C);
return;
}
bool TaintedD = C.getState()->isTainted(*DV);
if ((stateNotZero && stateZero && TaintedD)) {
reportBug("Division by a tainted value, possibly zero", stateZero, C);
return;
}
// If we get here, then the denom should not be zero. We abandon the implicit
// zero denom case for now.
C.addTransition(stateNotZero);
}
示例12: checkPostStmt
void ObjCLoopChecker::checkPostStmt(const ObjCForCollectionStmt *FCS,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
// Check if this is the branch for the end of the loop.
SVal CollectionSentinel = C.getSVal(FCS);
if (CollectionSentinel.isZeroConstant()) {
if (!alreadyExecutedAtLeastOneLoopIteration(C.getPredecessor(), FCS))
State = assumeCollectionNonEmpty(C, State, FCS, /*Assumption*/false);
// Otherwise, this is a branch that goes through the loop body.
} else {
State = checkCollectionNonNil(C, State, FCS);
State = checkElementNonNil(C, State, FCS);
State = assumeCollectionNonEmpty(C, State, FCS, /*Assumption*/true);
}
if (!State)
C.generateSink();
else if (State != C.getState())
C.addTransition(State);
}
示例13: handleEnd
void IteratorChecker::handleEnd(CheckerContext &C, const Expr *CE,
const SVal &RetVal, const SVal &Cont) const {
const auto *ContReg = Cont.getAsRegion();
if (!ContReg)
return;
while (const auto *CBOR = ContReg->getAs<CXXBaseObjectRegion>()) {
ContReg = CBOR->getSuperRegion();
}
// If the container already has an end symbol then use it. Otherwise first
// create a new one.
auto State = C.getState();
auto EndSym = getContainerEnd(State, ContReg);
if (!EndSym) {
auto &SymMgr = C.getSymbolManager();
EndSym = SymMgr.conjureSymbol(CE, C.getLocationContext(),
C.getASTContext().LongTy, C.blockCount());
State = createContainerEnd(State, ContReg, EndSym);
}
State = setIteratorPosition(State, RetVal,
IteratorPosition::getPosition(ContReg, EndSym));
C.addTransition(State);
}
示例14: PreVisitCallExpr
void CFRetainReleaseChecker::PreVisitCallExpr(CheckerContext& C,
const CallExpr* CE) {
// If the CallExpr doesn't have exactly 1 argument just give up checking.
if (CE->getNumArgs() != 1)
return;
// Get the function declaration of the callee.
const GRState* state = C.getState();
SVal X = state->getSVal(CE->getCallee());
const FunctionDecl* FD = X.getAsFunctionDecl();
if (!FD)
return;
if (!BT) {
ASTContext &Ctx = C.getASTContext();
Retain = &Ctx.Idents.get("CFRetain");
Release = &Ctx.Idents.get("CFRelease");
BT = new APIMisuse("null passed to CFRetain/CFRelease");
}
// Check if we called CFRetain/CFRelease.
const IdentifierInfo *FuncII = FD->getIdentifier();
if (!(FuncII == Retain || FuncII == Release))
return;
// FIXME: The rest of this just checks that the argument is non-null.
// It should probably be refactored and combined with AttrNonNullChecker.
// Get the argument's value.
const Expr *Arg = CE->getArg(0);
SVal ArgVal = state->getSVal(Arg);
DefinedSVal *DefArgVal = dyn_cast<DefinedSVal>(&ArgVal);
if (!DefArgVal)
return;
// Get a NULL value.
SValBuilder &svalBuilder = C.getSValBuilder();
DefinedSVal zero = cast<DefinedSVal>(svalBuilder.makeZeroVal(Arg->getType()));
// Make an expression asserting that they're equal.
DefinedOrUnknownSVal ArgIsNull = svalBuilder.evalEQ(state, zero, *DefArgVal);
// Are they equal?
const GRState *stateTrue, *stateFalse;
llvm::tie(stateTrue, stateFalse) = state->assume(ArgIsNull);
if (stateTrue && !stateFalse) {
ExplodedNode *N = C.generateSink(stateTrue);
if (!N)
return;
const char *description = (FuncII == Retain)
? "Null pointer argument in call to CFRetain"
: "Null pointer argument in call to CFRelease";
EnhancedBugReport *report = new EnhancedBugReport(*BT, description, N);
report->addRange(Arg->getSourceRange());
report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, Arg);
C.EmitReport(report);
return;
}
// From here on, we know the argument is non-null.
C.addTransition(stateFalse);
}
示例15: checkPreCall
void NonNullParamChecker::checkPreCall(const CallEvent &Call,
CheckerContext &C) const {
const Decl *FD = Call.getDecl();
if (!FD)
return;
const NonNullAttr *Att = FD->getAttr<NonNullAttr>();
ProgramStateRef state = C.getState();
CallEvent::param_type_iterator TyI = Call.param_type_begin(),
TyE = Call.param_type_end();
for (unsigned idx = 0, count = Call.getNumArgs(); idx != count; ++idx){
// Check if the parameter is a reference. We want to report when reference
// to a null pointer is passed as a paramter.
bool haveRefTypeParam = false;
if (TyI != TyE) {
haveRefTypeParam = (*TyI)->isReferenceType();
TyI++;
}
bool haveAttrNonNull = Att && Att->isNonNull(idx);
if (!haveAttrNonNull) {
// Check if the parameter is also marked 'nonnull'.
ArrayRef<ParmVarDecl*> parms = Call.parameters();
if (idx < parms.size())
haveAttrNonNull = parms[idx]->hasAttr<NonNullAttr>();
}
if (!haveRefTypeParam && !haveAttrNonNull)
continue;
// If the value is unknown or undefined, we can't perform this check.
const Expr *ArgE = Call.getArgExpr(idx);
SVal V = Call.getArgSVal(idx);
Optional<DefinedSVal> DV = V.getAs<DefinedSVal>();
if (!DV)
continue;
// Process the case when the argument is not a location.
assert(!haveRefTypeParam || DV->getAs<Loc>());
if (haveAttrNonNull && !DV->getAs<Loc>()) {
// If the argument is a union type, we want to handle a potential
// transparent_union GCC extension.
if (!ArgE)
continue;
QualType T = ArgE->getType();
const RecordType *UT = T->getAsUnionType();
if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
continue;
if (Optional<nonloc::CompoundVal> CSV =
DV->getAs<nonloc::CompoundVal>()) {
nonloc::CompoundVal::iterator CSV_I = CSV->begin();
assert(CSV_I != CSV->end());
V = *CSV_I;
DV = V.getAs<DefinedSVal>();
assert(++CSV_I == CSV->end());
// FIXME: Handle (some_union){ some_other_union_val }, which turns into
// a LazyCompoundVal inside a CompoundVal.
if (!V.getAs<Loc>())
continue;
// Retrieve the corresponding expression.
if (const CompoundLiteralExpr *CE = dyn_cast<CompoundLiteralExpr>(ArgE))
if (const InitListExpr *IE =
dyn_cast<InitListExpr>(CE->getInitializer()))
ArgE = dyn_cast<Expr>(*(IE->begin()));
} else {
// FIXME: Handle LazyCompoundVals?
continue;
}
}
ConstraintManager &CM = C.getConstraintManager();
ProgramStateRef stateNotNull, stateNull;
std::tie(stateNotNull, stateNull) = CM.assumeDual(state, *DV);
if (stateNull && !stateNotNull) {
// Generate an error node. Check for a null node in case
// we cache out.
if (ExplodedNode *errorNode = C.generateSink(stateNull)) {
BugReport *R = 0;
if (haveAttrNonNull)
R = genReportNullAttrNonNull(errorNode, ArgE);
else if (haveRefTypeParam)
R = genReportReferenceToNullPointer(errorNode, ArgE);
// Highlight the range of the argument that was null.
R->addRange(Call.getArgSourceRange(idx));
// Emit the bug report.
C.emitReport(R);
}
//.........这里部分代码省略.........