diff options
author | Ted Kremenek <kremenek@apple.com> | 2015-09-08 03:50:52 +0000 |
---|---|---|
committer | Ted Kremenek <kremenek@apple.com> | 2015-09-08 03:50:52 +0000 |
commit | 3a0678e33c516363ca302dc36d09f52f60b4ff30 (patch) | |
tree | bf83dcc1965183782d8d7ed29dce4377847a458c /clang/lib/StaticAnalyzer/Checkers | |
parent | 21dfbfb426aa443a5538960a74aaf1b3bf0358c1 (diff) | |
download | bcm5719-llvm-3a0678e33c516363ca302dc36d09f52f60b4ff30.tar.gz bcm5719-llvm-3a0678e33c516363ca302dc36d09f52f60b4ff30.zip |
[analyzer] Apply whitespace cleanups by Honggyu Kim.
llvm-svn: 246978
Diffstat (limited to 'clang/lib/StaticAnalyzer/Checkers')
46 files changed, 425 insertions, 425 deletions
diff --git a/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp index 166471aaa1a..a052d83f5af 100644 --- a/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChecker.cpp @@ -101,7 +101,7 @@ void AnalyzerStatsChecker::checkEndAnalysis(ExplodedGraph &G, else if (isa<BlockDecl>(D)) { output << "block(line:" << Loc.getLine() << ":col:" << Loc.getColumn(); } - + NumBlocksUnreachable += unreachable; NumBlocks += total; std::string NameOfRootFunction = output.str(); diff --git a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundChecker.cpp index 557439b2888..45706c2f2f6 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundChecker.cpp @@ -23,7 +23,7 @@ using namespace clang; using namespace ento; namespace { -class ArrayBoundChecker : +class ArrayBoundChecker : public Checker<check::Location> { mutable std::unique_ptr<BuiltinBug> BT; @@ -55,8 +55,8 @@ void ArrayBoundChecker::checkLocation(SVal l, bool isLoad, const Stmt* LoadS, ProgramStateRef state = C.getState(); // Get the size of the array. - DefinedOrUnknownSVal NumElements - = C.getStoreManager().getSizeInElements(state, ER->getSuperRegion(), + DefinedOrUnknownSVal NumElements + = C.getStoreManager().getSizeInElements(state, ER->getSuperRegion(), ER->getValueType()); ProgramStateRef StInBound = state->assumeInBound(Idx, NumElements, true); @@ -65,7 +65,7 @@ void ArrayBoundChecker::checkLocation(SVal l, bool isLoad, const Stmt* LoadS, ExplodedNode *N = C.generateSink(StOutBound); if (!N) return; - + if (!BT) BT.reset(new BuiltinBug( this, "Out-of-bound array access", @@ -82,7 +82,7 @@ void ArrayBoundChecker::checkLocation(SVal l, bool isLoad, const Stmt* LoadS, C.emitReport(std::move(report)); return; } - + // Array bound check succeeded. From this point forward the array bound // should always succeed. C.addTransition(StInBound); diff --git a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp index d8dc2aaa636..bc790d4584f 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp @@ -26,15 +26,15 @@ using namespace clang; using namespace ento; namespace { -class ArrayBoundCheckerV2 : +class ArrayBoundCheckerV2 : public Checker<check::Location> { mutable std::unique_ptr<BuiltinBug> BT; enum OOB_Kind { OOB_Precedes, OOB_Excedes, OOB_Tainted }; - + void reportOOB(CheckerContext &C, ProgramStateRef errorState, OOB_Kind kind) const; - + public: void checkLocation(SVal l, bool isLoad, const Stmt*S, CheckerContext &C) const; @@ -55,7 +55,7 @@ public: NonLoc getByteOffset() const { return byteOffset.castAs<NonLoc>(); } const SubRegion *getRegion() const { return baseRegion; } - + static RegionRawOffsetV2 computeOffset(ProgramStateRef state, SValBuilder &svalBuilder, SVal location); @@ -65,12 +65,12 @@ public: }; } -static SVal computeExtentBegin(SValBuilder &svalBuilder, +static SVal computeExtentBegin(SValBuilder &svalBuilder, const MemRegion *region) { while (true) switch (region->getKind()) { default: - return svalBuilder.makeZeroArrayIndex(); + return svalBuilder.makeZeroArrayIndex(); case MemRegion::SymbolicRegionKind: // FIXME: improve this later by tracking symbolic lower bounds // for symbolic regions. @@ -94,22 +94,22 @@ void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad, // memory access is within the extent of the base region. Since we // have some flexibility in defining the base region, we can achieve // various levels of conservatism in our buffer overflow checking. - ProgramStateRef state = checkerContext.getState(); + ProgramStateRef state = checkerContext.getState(); ProgramStateRef originalState = state; SValBuilder &svalBuilder = checkerContext.getSValBuilder(); - const RegionRawOffsetV2 &rawOffset = + const RegionRawOffsetV2 &rawOffset = RegionRawOffsetV2::computeOffset(state, svalBuilder, location); if (!rawOffset.getRegion()) return; - // CHECK LOWER BOUND: Is byteOffset < extent begin? + // CHECK LOWER BOUND: Is byteOffset < extent begin? // If so, we are doing a load/store // before the first valid offset in the memory region. SVal extentBegin = computeExtentBegin(svalBuilder, rawOffset.getRegion()); - + if (Optional<NonLoc> NV = extentBegin.getAs<NonLoc>()) { SVal lowerBound = svalBuilder.evalBinOpNN(state, BO_LT, rawOffset.getByteOffset(), *NV, @@ -118,7 +118,7 @@ void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad, Optional<NonLoc> lowerBoundToCheck = lowerBound.getAs<NonLoc>(); if (!lowerBoundToCheck) return; - + ProgramStateRef state_precedesLowerBound, state_withinLowerBound; std::tie(state_precedesLowerBound, state_withinLowerBound) = state->assume(*lowerBoundToCheck); @@ -128,12 +128,12 @@ void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad, reportOOB(checkerContext, state_precedesLowerBound, OOB_Precedes); return; } - + // Otherwise, assume the constraint of the lower bound. assert(state_withinLowerBound); state = state_withinLowerBound; } - + do { // CHECK UPPER BOUND: Is byteOffset >= extent(baseRegion)? If so, // we are doing a load/store after the last valid offset. @@ -146,11 +146,11 @@ void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad, = svalBuilder.evalBinOpNN(state, BO_GE, rawOffset.getByteOffset(), extentVal.castAs<NonLoc>(), svalBuilder.getConditionType()); - + Optional<NonLoc> upperboundToCheck = upperbound.getAs<NonLoc>(); if (!upperboundToCheck) break; - + ProgramStateRef state_exceedsUpperBound, state_withinUpperBound; std::tie(state_exceedsUpperBound, state_withinUpperBound) = state->assume(*upperboundToCheck); @@ -161,19 +161,19 @@ void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad, reportOOB(checkerContext, state_exceedsUpperBound, OOB_Tainted); return; } - + // If we are constrained enough to definitely exceed the upper bound, report. if (state_exceedsUpperBound) { assert(!state_withinUpperBound); reportOOB(checkerContext, state_exceedsUpperBound, OOB_Excedes); return; } - + assert(state_withinUpperBound); state = state_withinUpperBound; } while (false); - + if (state != originalState) checkerContext.addTransition(state); } @@ -181,7 +181,7 @@ void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad, void ArrayBoundCheckerV2::reportOOB(CheckerContext &checkerContext, ProgramStateRef errorState, OOB_Kind kind) const { - + ExplodedNode *errorNode = checkerContext.generateSink(errorState); if (!errorNode) return; @@ -259,7 +259,7 @@ RegionRawOffsetV2 RegionRawOffsetV2::computeOffset(ProgramStateRef state, { const MemRegion *region = location.getAsRegion(); SVal offset = UndefinedVal(); - + while (region) { switch (region->getKind()) { default: { @@ -280,7 +280,7 @@ RegionRawOffsetV2 RegionRawOffsetV2::computeOffset(ProgramStateRef state, ASTContext &astContext = svalBuilder.getContext(); if (elemType->isIncompleteType()) return RegionRawOffsetV2(); - + // Update the offset. offset = addValue(state, getValue(offset, svalBuilder), diff --git a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp index f763284aa2c..6adf39f3755 100644 --- a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp @@ -143,7 +143,7 @@ void NilArgChecker::warnIfNilExpr(const Expr *E, if (ExplodedNode *N = C.generateSink()) { generateBugReport(N, Msg, E->getSourceRange(), E, C); } - + } } @@ -156,7 +156,7 @@ void NilArgChecker::warnIfNilArg(CheckerContext &C, ProgramStateRef State = C.getState(); if (!State->isNull(msg.getArgSVal(Arg)).isConstrainedTrue()) return; - + if (ExplodedNode *N = C.generateSink()) { SmallString<128> sbuf; llvm::raw_svector_ostream os(sbuf); @@ -193,7 +193,7 @@ void NilArgChecker::warnIfNilArg(CheckerContext &C, os << "' cannot be nil"; } } - + generateBugReport(N, os.str(), msg.getArgSourceRange(Arg), msg.getArgExpr(Arg), C); } @@ -224,7 +224,7 @@ void NilArgChecker::checkPreObjCMessage(const ObjCMethodCall &msg, static const unsigned InvalidArgIndex = UINT_MAX; unsigned Arg = InvalidArgIndex; bool CanBeSubscript = false; - + if (Class == FC_NSString) { Selector S = msg.getSelector(); @@ -433,7 +433,7 @@ void CFNumberCreateChecker::checkPreStmt(const CallExpr *CE, const FunctionDecl *FD = C.getCalleeDecl(CE); if (!FD) return; - + ASTContext &Ctx = C.getASTContext(); if (!II) II = &Ctx.Idents.get("CFNumberCreate"); @@ -495,17 +495,17 @@ void CFNumberCreateChecker::checkPreStmt(const CallExpr *CE, // FIXME: We can actually create an abstract "CFNumber" object that has // the bits initialized to the provided values. // - if (ExplodedNode *N = SourceSize < TargetSize ? C.generateSink() + if (ExplodedNode *N = SourceSize < TargetSize ? C.generateSink() : C.addTransition()) { SmallString<128> sbuf; llvm::raw_svector_ostream os(sbuf); - + os << (SourceSize == 8 ? "An " : "A ") << SourceSize << " bit integer is used to initialize a CFNumber " "object that represents " << (TargetSize == 8 ? "an " : "a ") << TargetSize << " bit integer. "; - + if (SourceSize < TargetSize) os << (TargetSize - SourceSize) << " bits of the CFNumber value will be garbage." ; @@ -549,7 +549,7 @@ void CFRetainReleaseChecker::checkPreStmt(const CallExpr *CE, const FunctionDecl *FD = C.getCalleeDecl(CE); if (!FD) return; - + if (!BT) { ASTContext &Ctx = C.getASTContext(); Retain = &Ctx.Idents.get("CFRetain"); @@ -635,7 +635,7 @@ public: void ClassReleaseChecker::checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const { - + if (!BT) { BT.reset(new APIMisuse( this, "message incorrectly sent to class instead of class instance")); @@ -646,7 +646,7 @@ void ClassReleaseChecker::checkPreObjCMessage(const ObjCMethodCall &msg, autoreleaseS = GetNullarySelector("autorelease", Ctx); drainS = GetNullarySelector("drain", Ctx); } - + if (msg.isInstanceMessage()) return; const ObjCInterfaceDecl *Class = msg.getReceiverInterface(); @@ -655,7 +655,7 @@ void ClassReleaseChecker::checkPreObjCMessage(const ObjCMethodCall &msg, Selector S = msg.getSelector(); if (!(S == releaseS || S == retainS || S == autoreleaseS || S == drainS)) return; - + if (ExplodedNode *N = C.addTransition()) { SmallString<200> buf; llvm::raw_svector_ostream os(buf); @@ -665,7 +665,7 @@ void ClassReleaseChecker::checkPreObjCMessage(const ObjCMethodCall &msg, os << "' message should be sent to instances " "of class '" << Class->getName() << "' and not the class directly"; - + auto report = llvm::make_unique<BugReport>(*BT, os.str(), N); report->addRange(msg.getSourceRange()); C.emitReport(std::move(report)); @@ -699,12 +699,12 @@ public: bool VariadicMethodTypeChecker::isVariadicMessage(const ObjCMethodCall &msg) const { const ObjCMethodDecl *MD = msg.getDecl(); - + if (!MD || !MD->isVariadic() || isa<ObjCProtocolDecl>(MD->getDeclContext())) return false; - + Selector S = msg.getSelector(); - + if (msg.isInstanceMessage()) { // FIXME: Ideally we'd look at the receiver interface here, but that's not // useful for init, because alloc returns 'id'. In theory, this could lead @@ -751,7 +751,7 @@ void VariadicMethodTypeChecker::checkPreObjCMessage(const ObjCMethodCall &msg, ASTContext &Ctx = C.getASTContext(); arrayWithObjectsS = GetUnarySelector("arrayWithObjects", Ctx); - dictionaryWithObjectsAndKeysS = + dictionaryWithObjectsAndKeysS = GetUnarySelector("dictionaryWithObjectsAndKeys", Ctx); setWithObjectsS = GetUnarySelector("setWithObjects", Ctx); orderedSetWithObjectsS = GetUnarySelector("orderedSetWithObjects", Ctx); @@ -789,11 +789,11 @@ void VariadicMethodTypeChecker::checkPreObjCMessage(const ObjCMethodCall &msg, // Ignore pointer constants. if (msg.getArgSVal(I).getAs<loc::ConcreteInt>()) continue; - + // Ignore pointer types annotated with 'NSObject' attribute. if (C.getASTContext().isObjCNSObjectType(ArgTy)) continue; - + // Ignore CF references, which can be toll-free bridged. if (coreFoundation::isCFObjectRef(ArgTy)) continue; @@ -861,7 +861,7 @@ static bool isKnownNonNilCollectionType(QualType T) { const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>(); if (!PT) return false; - + const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); if (!ID) return false; @@ -1023,7 +1023,7 @@ void ObjCLoopChecker::checkPostStmt(const ObjCForCollectionStmt *FCS, State = checkElementNonNil(C, State, FCS); State = assumeCollectionNonEmpty(C, State, FCS, /*Assumption*/true); } - + if (!State) C.generateSink(); else if (State != C.getState()) @@ -1041,7 +1041,7 @@ bool ObjCLoopChecker::isCollectionCountMethod(const ObjCMethodCall &M, if (S.isUnarySelector() && (S.getIdentifierInfoForSlot(0) == CountSelectorII)) return true; - + return false; } @@ -1069,7 +1069,7 @@ void ObjCLoopChecker::checkPostObjCMessage(const ObjCMethodCall &M, // a call to "count" and add it to the map. if (!isCollectionCountMethod(M, C)) return; - + const Expr *MsgExpr = M.getOriginExpr(); SymbolRef CountS = C.getSVal(MsgExpr).getAsSymbol(); if (CountS) { diff --git a/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp index e945c38e77c..b4ac316fdce 100644 --- a/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp @@ -42,45 +42,45 @@ void BoolAssignmentChecker::emitReport(ProgramStateRef state, static bool isBooleanType(QualType Ty) { if (Ty->isBooleanType()) // C++ or C99 return true; - + if (const TypedefType *TT = Ty->getAs<TypedefType>()) return TT->getDecl()->getName() == "BOOL" || // Objective-C TT->getDecl()->getName() == "_Bool" || // stdbool.h < C99 TT->getDecl()->getName() == "Boolean"; // MacTypes.h - + return false; } void BoolAssignmentChecker::checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const { - + // We are only interested in stores into Booleans. const TypedValueRegion *TR = dyn_cast_or_null<TypedValueRegion>(loc.getAsRegion()); - + if (!TR) return; - + QualType valTy = TR->getValueType(); - + if (!isBooleanType(valTy)) return; - + // Get the value of the right-hand side. We only care about values // that are defined (UnknownVals and UndefinedVals are handled by other // checkers). Optional<DefinedSVal> DV = val.getAs<DefinedSVal>(); if (!DV) return; - + // Check if the assigned value meets our criteria for correctness. It must // be a value that is either 0 or 1. One way to check this is to see if // the value is possibly < 0 (for a negative value) or greater than 1. - ProgramStateRef state = C.getState(); + ProgramStateRef state = C.getState(); SValBuilder &svalBuilder = C.getSValBuilder(); ConstraintManager &CM = C.getConstraintManager(); - - // First, ensure that the value is >= 0. + + // First, ensure that the value is >= 0. DefinedSVal zeroVal = svalBuilder.makeIntVal(0, valTy); SVal greaterThanOrEqualToZeroVal = svalBuilder.evalBinOp(state, BO_GE, *DV, zeroVal, @@ -91,13 +91,13 @@ void BoolAssignmentChecker::checkBind(SVal loc, SVal val, const Stmt *S, if (!greaterThanEqualToZero) { // The SValBuilder cannot construct a valid SVal for this condition. - // This means we cannot properly reason about it. + // This means we cannot properly reason about it. return; } - + ProgramStateRef stateLT, stateGE; std::tie(stateGE, stateLT) = CM.assumeDual(state, *greaterThanEqualToZero); - + // Is it possible for the value to be less than zero? if (stateLT) { // It is possible for the value to be less than zero. We only @@ -106,15 +106,15 @@ void BoolAssignmentChecker::checkBind(SVal loc, SVal val, const Stmt *S, // value is underconstrained and there is nothing left to be done. if (!stateGE) emitReport(stateLT, C); - + // In either case, we are done. return; } - + // If we reach here, it must be the case that the value is constrained // to only be >= 0. assert(stateGE == state); - + // At this point we know that the value is >= 0. // Now check to ensure that the value is <= 1. DefinedSVal OneVal = svalBuilder.makeIntVal(1, valTy); @@ -127,13 +127,13 @@ void BoolAssignmentChecker::checkBind(SVal loc, SVal val, const Stmt *S, if (!lessThanEqToOne) { // The SValBuilder cannot construct a valid SVal for this condition. - // This means we cannot properly reason about it. + // This means we cannot properly reason about it. return; } - + ProgramStateRef stateGT, stateLE; std::tie(stateLE, stateGT) = CM.assumeDual(state, *lessThanEqToOne); - + // Is it possible for the value to be greater than one? if (stateGT) { // It is possible for the value to be greater than one. We only @@ -142,11 +142,11 @@ void BoolAssignmentChecker::checkBind(SVal loc, SVal val, const Stmt *S, // value is underconstrained and there is nothing left to be done. if (!stateLE) emitReport(stateGT, C); - + // In either case, we are done. return; } - + // If we reach here, it must be the case that the value is constrained // to only be <= 1. assert(stateLE == state); diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp index 54b12410aa5..477bea74d8c 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp @@ -65,7 +65,7 @@ public: void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const; bool wantsRegionChangeUpdate(ProgramStateRef state) const; - ProgramStateRef + ProgramStateRef checkRegionChanges(ProgramStateRef state, const InvalidatedSymbols *, ArrayRef<const MemRegion *> ExplicitRegions, @@ -92,7 +92,7 @@ public: void evalstrLength(CheckerContext &C, const CallExpr *CE) const; void evalstrnLength(CheckerContext &C, const CallExpr *CE) const; void evalstrLengthCommon(CheckerContext &C, - const CallExpr *CE, + const CallExpr *CE, bool IsStrnlen = false) const; void evalStrcpy(CheckerContext &C, const CallExpr *CE) const; @@ -137,9 +137,9 @@ public: SVal Buf, bool hypothetical = false) const; - const StringLiteral *getCStringLiteral(CheckerContext &C, + const StringLiteral *getCStringLiteral(CheckerContext &C, ProgramStateRef &state, - const Expr *expr, + const Expr *expr, SVal val) const; static ProgramStateRef InvalidateBuffer(CheckerContext &C, @@ -282,7 +282,7 @@ ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C, // Get the size of the array. const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion()); SValBuilder &svalBuilder = C.getSValBuilder(); - SVal Extent = + SVal Extent = svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder)); DefinedOrUnknownSVal Size = Extent.castAs<DefinedOrUnknownSVal>(); @@ -327,7 +327,7 @@ ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C, C.emitReport(std::move(report)); return nullptr; } - + // Array bound check succeeded. From this point forward the array bound // should always succeed. return StInBound; @@ -442,7 +442,7 @@ ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C, return state; // Are the two values the same? - SValBuilder &svalBuilder = C.getSValBuilder(); + SValBuilder &svalBuilder = C.getSValBuilder(); std::tie(stateTrue, stateFalse) = state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc)); @@ -489,7 +489,7 @@ ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C, // Bail out if the cast fails. ASTContext &Ctx = svalBuilder.getContext(); QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy); - SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy, + SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy, First->getType()); Optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>(); if (!FirstStartLoc) @@ -568,7 +568,7 @@ ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C, } else { // Try switching the operands. (The order of these two assignments is // important!) - maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left, + maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left, sizeTy); left = right; } @@ -723,7 +723,7 @@ SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state, auto report = llvm::make_unique<BugReport>(*BT_NotCString, os.str(), N); report->addRange(Ex->getSourceRange()); - C.emitReport(std::move(report)); + C.emitReport(std::move(report)); } return UndefinedVal(); @@ -787,7 +787,7 @@ SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state, auto report = llvm::make_unique<BugReport>(*BT_NotCString, os.str(), N); report->addRange(Ex->getSourceRange()); - C.emitReport(std::move(report)); + C.emitReport(std::move(report)); } return UndefinedVal(); @@ -843,13 +843,13 @@ ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C, // Invalidate and escape only indirect regions accessible through the source // buffer. if (IsSourceBuffer) { - ITraits.setTrait(R, + ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_PreserveContents); ITraits.setTrait(R, RegionAndSymbolInvalidationTraits::TK_SuppressEscape); CausesPointerEscape = true; } - return state->invalidateRegions(R, E, C.blockCount(), LCtx, + return state->invalidateRegions(R, E, C.blockCount(), LCtx, CausesPointerEscape, nullptr, nullptr, &ITraits); } @@ -901,7 +901,7 @@ bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx, // evaluation of individual function calls. //===----------------------------------------------------------------------===// -void CStringChecker::evalCopyCommon(CheckerContext &C, +void CStringChecker::evalCopyCommon(CheckerContext &C, const CallExpr *CE, ProgramStateRef state, const Expr *Size, const Expr *Dest, @@ -941,7 +941,7 @@ void CStringChecker::evalCopyCommon(CheckerContext &C, // Get the value of the Src. 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); @@ -959,11 +959,11 @@ void CStringChecker::evalCopyCommon(CheckerContext &C, if (!state) return; - // If this is mempcpy, get the byte after the last byte copied and + // If this is mempcpy, get the byte after the last byte copied and // bind the expr. if (IsMempcpy) { loc::MemRegionVal destRegVal = destVal.castAs<loc::MemRegionVal>(); - + // Get the length to copy. if (Optional<NonLoc> lenValNonLoc = sizeVal.getAs<NonLoc>()) { // Get the byte after the last byte copied. @@ -972,11 +972,11 @@ void CStringChecker::evalCopyCommon(CheckerContext &C, QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy); loc::MemRegionVal DestRegCharVal = SvalBuilder.evalCast(destRegVal, CharPtrTy, Dest->getType()).castAs<loc::MemRegionVal>(); - SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add, + SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add, DestRegCharVal, - *lenValNonLoc, + *lenValNonLoc, Dest->getType()); - + // The byte after the last byte copied is the return value. state = state->BindExpr(CE, LCtx, lastElement); } else { @@ -999,12 +999,12 @@ void CStringChecker::evalCopyCommon(CheckerContext &C, // 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. - state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest), + state = InvalidateBuffer(C, state, Dest, C.getSVal(Dest), /*IsSourceBuffer*/false); // Invalidate the source (const-invalidation without const-pointer-escaping // the address of the top-level region). - state = InvalidateBuffer(C, state, Source, C.getSVal(Source), + state = InvalidateBuffer(C, state, Source, C.getSVal(Source), /*IsSourceBuffer*/true); C.addTransition(state); @@ -1032,7 +1032,7 @@ void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const { // 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); } @@ -1053,7 +1053,7 @@ void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const { return; // void bcopy(const void *src, void *dst, size_t n); - evalCopyCommon(C, CE, C.getState(), + evalCopyCommon(C, CE, C.getState(), CE->getArg(2), CE->getArg(1), CE->getArg(0)); } @@ -1244,7 +1244,7 @@ void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE, state, BO_LE, resultNL, *strLengthNL, cmpTy) .castAs<DefinedOrUnknownSVal>(), true); } - + if (maxlenValNL) { state = state->assume(C.getSValBuilder().evalBinOpNN( state, BO_LE, resultNL, *maxlenValNL, cmpTy) @@ -1275,8 +1275,8 @@ void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const { return; // char *strcpy(char *restrict dst, const char *restrict src); - evalStrcpyCommon(C, CE, - /* returnEnd = */ false, + evalStrcpyCommon(C, CE, + /* returnEnd = */ false, /* isBounded = */ false, /* isAppending = */ false); } @@ -1286,8 +1286,8 @@ void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const { return; // char *strncpy(char *restrict dst, const char *restrict src, size_t n); - evalStrcpyCommon(C, CE, - /* returnEnd = */ false, + evalStrcpyCommon(C, CE, + /* returnEnd = */ false, /* isBounded = */ true, /* isAppending = */ false); } @@ -1297,8 +1297,8 @@ void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const { return; // char *stpcpy(char *restrict dst, const char *restrict src); - evalStrcpyCommon(C, CE, - /* returnEnd = */ true, + evalStrcpyCommon(C, CE, + /* returnEnd = */ true, /* isBounded = */ false, /* isAppending = */ false); } @@ -1308,8 +1308,8 @@ void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const { return; //char *strcat(char *restrict s1, const char *restrict s2); - evalStrcpyCommon(C, CE, - /* returnEnd = */ false, + evalStrcpyCommon(C, CE, + /* returnEnd = */ false, /* isBounded = */ false, /* isAppending = */ true); } @@ -1319,8 +1319,8 @@ void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const { return; //char *strncat(char *restrict s1, const char *restrict s2, size_t n); - evalStrcpyCommon(C, CE, - /* returnEnd = */ false, + evalStrcpyCommon(C, CE, + /* returnEnd = */ false, /* isBounded = */ true, /* isAppending = */ true); } @@ -1515,7 +1515,7 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, Optional<NonLoc> srcStrLengthNL = amountCopied.getAs<NonLoc>(); Optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>(); - + // If we know both string lengths, we might know the final string length. if (srcStrLengthNL && dstStrLengthNL) { // Make sure the two lengths together don't overflow a size_t. @@ -1523,7 +1523,7 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, if (!state) return; - finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL, + finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL, *dstStrLengthNL, sizeTy); } @@ -1586,7 +1586,7 @@ void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, if (Optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) { SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal, *maxLastNL, ptrTy); - state = CheckLocation(C, state, CE->getArg(2), maxLastElement, + state = CheckLocation(C, state, CE->getArg(2), maxLastElement, boundWarning); if (!state) return; @@ -1667,7 +1667,7 @@ void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const { evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false); } -void CStringChecker::evalStrcasecmp(CheckerContext &C, +void CStringChecker::evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const { if (CE->getNumArgs() < 2) return; @@ -1676,7 +1676,7 @@ void CStringChecker::evalStrcasecmp(CheckerContext &C, evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true); } -void CStringChecker::evalStrncasecmp(CheckerContext &C, +void CStringChecker::evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const { if (CE->getNumArgs() < 3) return; @@ -1915,7 +1915,7 @@ bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const { evalFunction = &CStringChecker::evalBcopy; else if (C.isCLibraryFunction(FDecl, "bcmp")) evalFunction = &CStringChecker::evalMemcmp; - + // If the callee isn't a string function, let another checker handle it. if (!evalFunction) return false; @@ -1975,7 +1975,7 @@ bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const { return !Entries.isEmpty(); } -ProgramStateRef +ProgramStateRef CStringChecker::checkRegionChanges(ProgramStateRef state, const InvalidatedSymbols *, ArrayRef<const MemRegion *> ExplicitRegions, diff --git a/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp b/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp index 12eb0bde28a..25caa000259 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp @@ -51,7 +51,7 @@ static bool scan_ivar_release(Stmt *S, ObjCIvarDecl *ID, if (E->getDecl()->getIdentifier() == SelfII) if (ME->getMethodDecl() == PD->getSetterMethodDecl() && ME->getNumArgs() == 1 && - ME->getArg(0)->isNullPointerConstant(Ctx, + ME->getArg(0)->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNull)) return true; @@ -61,7 +61,7 @@ static bool scan_ivar_release(Stmt *S, ObjCIvarDecl *ID, if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BO->getLHS()->IgnoreParenCasts())) if (PRE->isExplicitProperty() && PRE->getExplicitProperty() == PD) - if (BO->getRHS()->isNullPointerConstant(Ctx, + if (BO->getRHS()->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNull)) { // This is only a 'release' if the property kind is not // 'assign'. diff --git a/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp b/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp index e0c113c8626..eab97560dbc 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp @@ -115,7 +115,7 @@ void WalkAST::VisitChildren(Stmt *S) { } void WalkAST::VisitCallExpr(CallExpr *CE) { - // Get the callee. + // Get the callee. const FunctionDecl *FD = CE->getDirectCallee(); if (!FD) @@ -307,7 +307,7 @@ void WalkAST::checkLoopConditionForFloat(const ForStmt *FS) { void WalkAST::checkCall_gets(const CallExpr *CE, const FunctionDecl *FD) { if (!filter.check_gets) return; - + const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>(); if (!FPT) return; @@ -434,18 +434,18 @@ void WalkAST::checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD) { .Case("mkdtemp", std::make_pair(0,-1)) .Case("mkstemps", std::make_pair(0,1)) .Default(std::make_pair(-1, -1)); - + assert(ArgSuffix.first >= 0 && "Unsupported function"); // Check if the number of arguments is consistent with out expectations. unsigned numArgs = CE->getNumArgs(); if ((signed) numArgs <= ArgSuffix.first) return; - + const StringLiteral *strArg = dyn_cast<StringLiteral>(CE->getArg((unsigned)ArgSuffix.first) ->IgnoreParenImpCasts()); - + // Currently we only handle string literals. It is possible to do better, // either by looking at references to const variables, or by doing real // flow analysis. @@ -470,13 +470,13 @@ void WalkAST::checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD) { suffix = (unsigned) Result.getZExtValue(); n = (n > suffix) ? n - suffix : 0; } - + for (unsigned i = 0; i < n; ++i) if (str[i] == 'X') ++numX; - + if (numX >= 6) return; - + // Issue a warning. PathDiagnosticLocation CELoc = PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); @@ -502,13 +502,13 @@ void WalkAST::checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD) { //===----------------------------------------------------------------------===// // Check: Any use of 'strcpy' is insecure. // -// CWE-119: Improper Restriction of Operations within -// the Bounds of a Memory Buffer +// CWE-119: Improper Restriction of Operations within +// the Bounds of a Memory Buffer //===----------------------------------------------------------------------===// void WalkAST::checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD) { if (!filter.check_strcpy) return; - + if (!checkCall_strCommon(CE, FD)) return; @@ -529,8 +529,8 @@ void WalkAST::checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD) { //===----------------------------------------------------------------------===// // Check: Any use of 'strcat' is insecure. // -// CWE-119: Improper Restriction of Operations within -// the Bounds of a Memory Buffer +// CWE-119: Improper Restriction of Operations within +// the Bounds of a Memory Buffer //===----------------------------------------------------------------------===// void WalkAST::checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD) { if (!filter.check_strcpy) @@ -684,7 +684,7 @@ void WalkAST::checkCall_vfork(const CallExpr *CE, const FunctionDecl *FD) { void WalkAST::checkUncheckedReturnValue(CallExpr *CE) { if (!filter.check_UncheckedReturn) return; - + const FunctionDecl *FD = CE->getDirectCallee(); if (!FD) return; @@ -749,7 +749,7 @@ namespace { class SecuritySyntaxChecker : public Checker<check::ASTCodeBody> { public: ChecksFilter filter; - + void checkASTCodeBody(const Decl *D, AnalysisManager& mgr, BugReporter &BR) const { WalkAST walker(BR, mgr.getAnalysisDeclContext(D), filter); diff --git a/clang/lib/StaticAnalyzer/Checkers/CheckSizeofPointer.cpp b/clang/lib/StaticAnalyzer/Checkers/CheckSizeofPointer.cpp index 81a20063f97..e079a8cb12b 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CheckSizeofPointer.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CheckSizeofPointer.cpp @@ -55,8 +55,8 @@ void WalkAST::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) { QualType T = E->getTypeOfArgument(); if (T->isPointerType()) { - // Many false positives have the form 'sizeof *p'. This is reasonable - // because people know what they are doing when they intentionally + // Many false positives have the form 'sizeof *p'. This is reasonable + // because people know what they are doing when they intentionally // dereference the pointer. Expr *ArgEx = E->getArgumentExpr(); if (!isa<DeclRefExpr>(ArgEx->IgnoreParens())) diff --git a/clang/lib/StaticAnalyzer/Checkers/CheckerDocumentation.cpp b/clang/lib/StaticAnalyzer/Checkers/CheckerDocumentation.cpp index 956dca7d925..86955c4fcb0 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CheckerDocumentation.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CheckerDocumentation.cpp @@ -222,7 +222,7 @@ public: /// changed, this allows the analyzer core to skip the more expensive /// #checkRegionChanges when no checkers are tracking any state. bool wantsRegionChangeUpdate(ProgramStateRef St) const { return true; } - + /// \brief Called when the contents of one or more regions change. /// /// This can occur in many different ways: an explicit bind, a blanket @@ -246,7 +246,7 @@ public: /// #wantsRegionChangeUpdate returns \c true. /// /// check::RegionChanges - ProgramStateRef + ProgramStateRef checkRegionChanges(ProgramStateRef State, const InvalidatedSymbols *Invalidated, ArrayRef<const MemRegion *> ExplicitRegions, @@ -259,12 +259,12 @@ public: /// /// This notifies the checkers about pointer escape, which occurs whenever /// the analyzer cannot track the symbol any more. For example, as a - /// result of assigning a pointer into a global or when it's passed to a + /// result of assigning a pointer into a global or when it's passed to a /// function call the analyzer cannot model. - /// + /// /// \param State The state at the point of escape. /// \param Escaped The list of escaped symbols. - /// \param Call The corresponding CallEvent, if the symbols escape as + /// \param Call The corresponding CallEvent, if the symbols escape as /// parameters to the given call. /// \param Kind How the symbols have escaped. /// \returns Checkers can modify the state by returning a new state. @@ -285,7 +285,7 @@ public: PointerEscapeKind Kind) const { return State; } - + /// check::Event<ImplicitNullDerefEvent> void checkEvent(ImplicitNullDerefEvent Event) const {} diff --git a/clang/lib/StaticAnalyzer/Checkers/Checkers.td b/clang/lib/StaticAnalyzer/Checkers/Checkers.td index 2632b31742e..408fb4e0939 100644 --- a/clang/lib/StaticAnalyzer/Checkers/Checkers.td +++ b/clang/lib/StaticAnalyzer/Checkers/Checkers.td @@ -30,7 +30,7 @@ def DeadCodeAlpha : Package<"deadcode">, InPackage<Alpha>, Hidden; def Security : Package <"security">; def InsecureAPI : Package<"insecureAPI">, InPackage<Security>; def SecurityAlpha : Package<"security">, InPackage<Alpha>, Hidden; -def Taint : Package<"taint">, InPackage<SecurityAlpha>, Hidden; +def Taint : Package<"taint">, InPackage<SecurityAlpha>, Hidden; def Unix : Package<"unix">; def UnixAlpha : Package<"unix">, InPackage<Alpha>, Hidden; @@ -192,7 +192,7 @@ def UndefBranchChecker : Checker<"Branch">, def UndefCapturedBlockVarChecker : Checker<"CapturedBlockVariable">, HelpText<"Check for blocks that capture uninitialized values">, DescFile<"UndefCapturedBlockVarChecker.cpp">; - + def ReturnUndefChecker : Checker<"UndefReturn">, HelpText<"Check for uninitialized values being returned to the caller">, DescFile<"ReturnUndefChecker.cpp">; @@ -206,11 +206,11 @@ def ReturnUndefChecker : Checker<"UndefReturn">, let ParentPackage = Cplusplus in { def NewDeleteChecker : Checker<"NewDelete">, - HelpText<"Check for double-free and use-after-free problems. Traces memory managed by new/delete.">, + HelpText<"Check for double-free and use-after-free problems. Traces memory managed by new/delete.">, DescFile<"MallocChecker.cpp">; def NewDeleteLeaksChecker : Checker<"NewDeleteLeaks">, - HelpText<"Check for memory leaks. Traces memory managed by new/delete.">, + HelpText<"Check for memory leaks. Traces memory managed by new/delete.">, DescFile<"MallocChecker.cpp">; } // end: "cplusplus" @@ -218,7 +218,7 @@ def NewDeleteLeaksChecker : Checker<"NewDeleteLeaks">, let ParentPackage = CplusplusAlpha in { def VirtualCallChecker : Checker<"VirtualCall">, - HelpText<"Check virtual function calls during construction or destruction">, + HelpText<"Check virtual function calls during construction or destruction">, DescFile<"VirtualCallChecker.cpp">; } // end: "alpha.cplusplus" @@ -282,7 +282,7 @@ let ParentPackage = SecurityAlpha in { def ArrayBoundChecker : Checker<"ArrayBound">, HelpText<"Warn about buffer overflows (older checker)">, - DescFile<"ArrayBoundChecker.cpp">; + DescFile<"ArrayBoundChecker.cpp">; def ArrayBoundCheckerV2 : Checker<"ArrayBoundV2">, HelpText<"Warn about buffer overflows (newer checker)">, @@ -323,7 +323,7 @@ def UnixAPIChecker : Checker<"API">, def MallocChecker: Checker<"Malloc">, HelpText<"Check for memory leaks, double free, and use-after-free problems. Traces memory managed by malloc()/free().">, DescFile<"MallocChecker.cpp">; - + def MallocSizeofChecker : Checker<"MallocSizeof">, HelpText<"Check for dubious malloc arguments involving sizeof">, DescFile<"MallocSizeofChecker.cpp">; @@ -331,7 +331,7 @@ def MallocSizeofChecker : Checker<"MallocSizeof">, def MismatchedDeallocatorChecker : Checker<"MismatchedDeallocator">, HelpText<"Check for mismatched deallocators.">, DescFile<"MallocChecker.cpp">; - + } // end "unix" let ParentPackage = UnixAlpha in { @@ -362,7 +362,7 @@ def CStringNullArg : Checker<"NullArg">, def CStringSyntaxChecker : Checker<"BadSizeArg">, HelpText<"Check the size argument passed into C string functions for common erroneous patterns">, - DescFile<"CStringSyntaxChecker.cpp">; + DescFile<"CStringSyntaxChecker.cpp">; } let ParentPackage = CStringAlpha in { @@ -514,7 +514,7 @@ def ObjCContainersASTChecker : Checker<"PointerSizedValues">, def ObjCContainersChecker : Checker<"OutOfBounds">, HelpText<"Checks for index out-of-bounds when using 'CFArray' API">, DescFile<"ObjCContainersChecker.cpp">; - + } //===----------------------------------------------------------------------===// // Checkers for LLVM development. diff --git a/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp index 804e83c0fb2..cefdb064534 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp @@ -27,7 +27,7 @@ namespace { // enum value that represent the jail state enum Kind { NO_CHROOT, ROOT_CHANGED, JAIL_ENTERED }; - + bool isRootChanged(intptr_t k) { return k == ROOT_CHANGED; } //bool isJailEntered(intptr_t k) { return k == JAIL_ENTERED; } @@ -50,7 +50,7 @@ public: static int x; return &x; } - + bool evalCall(const CallExpr *CE, CheckerContext &C) const; void checkPreStmt(const CallExpr *CE, CheckerContext &C) const; @@ -87,8 +87,8 @@ bool ChrootChecker::evalCall(const CallExpr *CE, CheckerContext &C) const { void ChrootChecker::Chroot(CheckerContext &C, const CallExpr *CE) const { ProgramStateRef state = C.getState(); ProgramStateManager &Mgr = state->getStateManager(); - - // Once encouter a chroot(), set the enum value ROOT_CHANGED directly in + + // Once encouter a chroot(), set the enum value ROOT_CHANGED directly in // the GDM. state = Mgr.addGDM(state, ChrootChecker::getTag(), (void*) ROOT_CHANGED); C.addTransition(state); @@ -106,7 +106,7 @@ void ChrootChecker::Chdir(CheckerContext &C, const CallExpr *CE) const { // After chdir("/"), enter the jail, set the enum value JAIL_ENTERED. const Expr *ArgExpr = CE->getArg(0); SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext()); - + if (const MemRegion *R = ArgVal.getAsRegion()) { R = R->StripCasts(); if (const StringRegion* StrRegion= dyn_cast<StringRegion>(R)) { @@ -135,7 +135,7 @@ void ChrootChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const { // Ingnore chroot and chdir. if (FD->getIdentifier() == II_chroot || FD->getIdentifier() == II_chdir) return; - + // If jail state is ROOT_CHANGED, generate BugReport. void *const* k = C.getState()->FindGDM(ChrootChecker::getTag()); if (k) diff --git a/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp index f4be5b3e82f..5d8baf6ba7d 100644 --- a/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp @@ -28,36 +28,36 @@ using namespace clang; using namespace ento; -namespace { - +namespace { + /// A simple visitor to record what VarDecls occur in EH-handling code. class EHCodeVisitor : public RecursiveASTVisitor<EHCodeVisitor> { public: bool inEH; llvm::DenseSet<const VarDecl *> &S; - + bool TraverseObjCAtFinallyStmt(ObjCAtFinallyStmt *S) { SaveAndRestore<bool> inFinally(inEH, true); return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtFinallyStmt(S); } - + bool TraverseObjCAtCatchStmt(ObjCAtCatchStmt *S) { SaveAndRestore<bool> inCatch(inEH, true); return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtCatchStmt(S); } - + bool TraverseCXXCatchStmt(CXXCatchStmt *S) { SaveAndRestore<bool> inCatch(inEH, true); return TraverseStmt(S->getHandlerBlock()); } - + bool VisitDeclRefExpr(DeclRefExpr *DR) { if (inEH) if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl())) S.insert(D); return true; } - + EHCodeVisitor(llvm::DenseSet<const VarDecl *> &S) : inEH(false), S(S) {} }; @@ -70,9 +70,9 @@ class ReachableCode { public: ReachableCode(const CFG &cfg) : cfg(cfg), reachable(cfg.getNumBlockIDs(), false) {} - + void computeReachableBlocks(); - + bool isReachable(const CFGBlock *block) const { return reachable[block->getBlockID()]; } @@ -82,7 +82,7 @@ public: void ReachableCode::computeReachableBlocks() { if (!cfg.getNumBlockIDs()) return; - + SmallVector<const CFGBlock*, 10> worklist; worklist.push_back(&cfg.getEntry()); @@ -160,19 +160,19 @@ public: // to analyze that yet. return InEH->count(D); } - + void Report(const VarDecl *V, DeadStoreKind dsk, PathDiagnosticLocation L, SourceRange R) { if (Escaped.count(V)) return; - + // Compute reachable blocks within the CFG for trivial cases // where a bogus dead store can be reported because itself is unreachable. if (!reachableCode.get()) { reachableCode.reset(new ReachableCode(cfg)); reachableCode->computeReachableBlocks(); } - + if (!reachableCode->isReachable(currentBlock)) return; @@ -196,7 +196,7 @@ public: case Enclosing: // Don't report issues in this case, e.g.: "if (x = foo())", - // where 'x' is unused later. We have yet to see a case where + // where 'x' is unused later. We have yet to see a case where // this is a real bug. return; } @@ -259,7 +259,7 @@ public: const LiveVariables::LivenessValues &Live) override { currentBlock = block; - + // Skip statements in macros. if (S->getLocStart().isMacroID()) return; @@ -276,7 +276,7 @@ public: const Expr *RHS = LookThroughTransitiveAssignmentsAndCommaOperators(B->getRHS()); RHS = RHS->IgnoreParenCasts(); - + QualType T = VD->getType(); if (T->isPointerType() || T->isObjCObjectPointerType()) { if (RHS->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNull)) @@ -318,27 +318,27 @@ public: if (!V) continue; - - if (V->hasLocalStorage()) { + + if (V->hasLocalStorage()) { // Reference types confuse the dead stores checker. Skip them // for now. if (V->getType()->getAs<ReferenceType>()) return; - + if (const Expr *E = V->getInit()) { while (const ExprWithCleanups *exprClean = dyn_cast<ExprWithCleanups>(E)) E = exprClean->getSubExpr(); - + // Look through transitive assignments, e.g.: // int x = y = 0; E = LookThroughTransitiveAssignmentsAndCommaOperators(E); - + // Don't warn on C++ objects (yet) until we can show that their // constructors/destructors don't have side effects. if (isa<CXXConstructExpr>(E)) return; - + // A dead initialization is a variable that is dead after it // is initialized. We don't flag warnings for those variables // marked 'unused' or 'objc_precise_lifetime'. diff --git a/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp index 07be5a59e51..0df31860906 100644 --- a/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp @@ -84,7 +84,7 @@ DereferenceChecker::AddDerefSource(raw_ostream &os, SourceLocation L = IV->getLocation(); Ranges.push_back(SourceRange(L, L)); break; - } + } } } diff --git a/clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp index 79f9479b144..211a1c1d0cf 100644 --- a/clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp @@ -29,7 +29,7 @@ class DivZeroChecker : public Checker< check::PreStmt<BinaryOperator> > { CheckerContext &C) const ; public: void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const; -}; +}; } // end anonymous namespace void DivZeroChecker::reportBug(const char *Msg, diff --git a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp index 43a28121877..15137b0d17f 100644 --- a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp @@ -113,7 +113,7 @@ void DynamicTypePropagation::checkPostCall(const CallEvent &Call, ProgramStateRef State = C.getState(); const ObjCMethodDecl *D = Msg->getDecl(); - + if (D && D->hasRelatedResultType()) { switch (Msg->getMethodFamily()) { default: @@ -201,7 +201,7 @@ void DynamicTypePropagation::checkPostStmt(const CXXNewExpr *NewE, const MemRegion *MR = C.getSVal(NewE).getAsRegion(); if (!MR) return; - + C.addTransition(C.getState()->setDynamicTypeInfo(MR, NewE->getType(), /*CanBeSubclass=*/false)); } diff --git a/clang/lib/StaticAnalyzer/Checkers/FixedAddressChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/FixedAddressChecker.cpp index 48d6bd4b37e..ae226f727c7 100644 --- a/clang/lib/StaticAnalyzer/Checkers/FixedAddressChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/FixedAddressChecker.cpp @@ -23,7 +23,7 @@ using namespace clang; using namespace ento; namespace { -class FixedAddressChecker +class FixedAddressChecker : public Checker< check::PreStmt<BinaryOperator> > { mutable std::unique_ptr<BuiltinBug> BT; diff --git a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp index 2cf508ff086..cb2bf108ef7 100644 --- a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp @@ -100,8 +100,8 @@ private: /// Generate a report if the expression is tainted or points to tainted data. bool generateReportIfTainted(const Expr *E, const char Msg[], CheckerContext &C) const; - - + + typedef SmallVector<unsigned, 2> ArgVector; /// \brief A struct used to specify taint propagation rules for a function. @@ -441,7 +441,7 @@ SymbolRef GenericTaintChecker::getPointedToSymbol(CheckerContext &C, return Val.getAsSymbol(); } -ProgramStateRef +ProgramStateRef GenericTaintChecker::TaintPropagationRule::process(const CallExpr *CE, CheckerContext &C) const { ProgramStateRef State = C.getState(); @@ -667,8 +667,8 @@ bool GenericTaintChecker::checkUncontrolledFormatString(const CallExpr *CE, bool GenericTaintChecker::checkSystemCall(const CallExpr *CE, StringRef Name, CheckerContext &C) const { - // TODO: It might make sense to run this check on demand. In some cases, - // we should check if the environment has been cleansed here. We also might + // TODO: It might make sense to run this check on demand. In some cases, + // we should check if the environment has been cleansed here. We also might // need to know if the user was reset before these calls(seteuid). unsigned ArgNum = llvm::StringSwitch<unsigned>(Name) .Case("system", 0) diff --git a/clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp index 3e50d2e3345..6cfd07a9e9b 100644 --- a/clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp @@ -96,7 +96,7 @@ void FindIdenticalExprVisitor::checkBitwiseOrLogicalOp(const BinaryOperator *B, } LHS = B2->getLHS(); } - + if (isIdenticalStmt(AC->getASTContext(), RHS, LHS)) { Sr[0] = RHS->getSourceRange(); Sr[1] = LHS->getSourceRange(); diff --git a/clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp index 3df5fa034a4..dffff38c91a 100644 --- a/clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp @@ -20,8 +20,8 @@ // been called on them. An invalidation method should either invalidate all // the ivars or call another invalidation method (on self). // -// Partial invalidor annotation allows to addess cases when ivars are -// invalidated by other methods, which might or might not be called from +// Partial invalidor annotation allows to addess cases when ivars are +// invalidated by other methods, which might or might not be called from // the invalidation method. The checker checks that each invalidation // method and all the partial methods cumulatively invalidate all ivars. // __attribute__((annotate("objc_instance_variable_invalidator_partial"))); @@ -310,7 +310,7 @@ const ObjCIvarDecl *IvarInvalidationCheckerImpl::findPropertyBackingIvar( // Lookup for the synthesized case. IvarD = Prop->getPropertyIvarDecl(); - // We only track the ivars/properties that are defined in the current + // We only track the ivars/properties that are defined in the current // class (not the parent). if (IvarD && IvarD->getContainingInterface() == InterfaceD) { if (TrackedIvars.count(IvarD)) { diff --git a/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp index d3b3d75c7ef..932d3d6ffff 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp @@ -118,7 +118,7 @@ private: SValBuilder &Builder) const { return definitelyReturnedError(RetSym, State, Builder, true); } - + /// Mark an AllocationPair interesting for diagnostic reporting. void markInteresting(BugReport *R, const AllocationPair &AP) const { R->markInteresting(AP.first); @@ -282,7 +282,7 @@ void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE, const FunctionDecl *FD = C.getCalleeDecl(CE); if (!FD || FD->getKind() != Decl::Function) return; - + StringRef funName = C.getCalleeName(FD); if (funName.empty()) return; diff --git a/clang/lib/StaticAnalyzer/Checkers/MacOSXAPIChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MacOSXAPIChecker.cpp index 11ba6096e2d..4ce936aa0fe 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MacOSXAPIChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MacOSXAPIChecker.cpp @@ -79,7 +79,7 @@ void MacOSXAPIChecker::CheckDispatchOnce(CheckerContext &C, const CallExpr *CE, if (TrimmedFName != FName) FName = TrimmedFName; } - + SmallString<256> S; llvm::raw_svector_ostream os(S); os << "Call to '" << FName << "' uses"; diff --git a/clang/lib/StaticAnalyzer/Checkers/Makefile b/clang/lib/StaticAnalyzer/Checkers/Makefile index 2582908b95d..7c8f7bf1bc4 100644 --- a/clang/lib/StaticAnalyzer/Checkers/Makefile +++ b/clang/lib/StaticAnalyzer/Checkers/Makefile @@ -1,13 +1,13 @@ ##===- clang/lib/Checker/Makefile --------------------------*- Makefile -*-===## -# +# # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. -# +# ##===----------------------------------------------------------------------===## # -# This implements analyses built on top of source-level CFGs. +# This implements analyses built on top of source-level CFGs. # ##===----------------------------------------------------------------------===## diff --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp index 0738d5af5b8..c95b2fd7f4b 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp @@ -65,10 +65,10 @@ class RefState { const Stmt *S; unsigned K : 3; // Kind enum, but stored as a bitfield. - unsigned Family : 29; // Rest of 32-bit word, currently just an allocation + unsigned Family : 29; // Rest of 32-bit word, currently just an allocation // family. - RefState(Kind k, const Stmt *s, unsigned family) + RefState(Kind k, const Stmt *s, unsigned family) : S(s), K(k), Family(family) { assert(family != AF_None); } @@ -94,7 +94,7 @@ public: return RefState(AllocatedOfSizeZero, RS->getStmt(), RS->getAllocationFamily()); } - static RefState getReleased(unsigned family, const Stmt *s) { + static RefState getReleased(unsigned family, const Stmt *s) { return RefState(Released, s, family); } static RefState getRelinquished(unsigned family, const Stmt *s) { @@ -169,9 +169,9 @@ class MallocChecker : public Checker<check::DeadSymbols, { public: MallocChecker() - : II_alloca(nullptr), II_malloc(nullptr), II_free(nullptr), + : II_alloca(nullptr), II_malloc(nullptr), II_free(nullptr), II_realloc(nullptr), II_calloc(nullptr), II_valloc(nullptr), - II_reallocf(nullptr), II_strndup(nullptr), II_strdup(nullptr), + II_reallocf(nullptr), II_strndup(nullptr), II_strdup(nullptr), II_kmalloc(nullptr), II_if_nameindex(nullptr), II_if_freenameindex(nullptr) {} @@ -185,7 +185,7 @@ public: CK_NumCheckKinds }; - enum class MemoryOperationKind { + enum class MemoryOperationKind { MOK_Allocate, MOK_Free, MOK_Any @@ -245,19 +245,19 @@ private: /// \brief Print names of allocators and deallocators. /// /// \returns true on success. - bool printAllocDeallocName(raw_ostream &os, CheckerContext &C, + bool printAllocDeallocName(raw_ostream &os, CheckerContext &C, const Expr *E) const; /// \brief Print expected name of an allocator based on the deallocator's /// family derived from the DeallocExpr. - void printExpectedAllocName(raw_ostream &os, CheckerContext &C, + void printExpectedAllocName(raw_ostream &os, CheckerContext &C, const Expr *DeallocExpr) const; - /// \brief Print expected name of a deallocator based on the allocator's + /// \brief Print expected name of a deallocator based on the allocator's /// family. void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const; ///@{ - /// Check if this is one of the functions which can allocate/reallocate memory + /// Check if this is one of the functions which can allocate/reallocate memory /// pointed to by one of its arguments. bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const; bool isCMemFunction(const FunctionDecl *FD, @@ -292,7 +292,7 @@ private: const ProgramStateRef &State) const; /// Update the RefState to reflect the new memory allocation. - static ProgramStateRef + static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State, AllocationFamily Family = AF_Malloc); @@ -312,17 +312,17 @@ private: bool ReturnsNullOnFailure = false) const; ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE, - bool FreesMemOnFailure, + bool FreesMemOnFailure, ProgramStateRef State) const; static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE, ProgramStateRef State); - + ///\brief Check if the memory associated with this symbol was released. bool isReleased(SymbolRef Sym, CheckerContext &C) const; bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const; - void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C, + void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C, const Stmt *S) const; bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const; @@ -330,7 +330,7 @@ private: /// Check if the function is known free memory, or if it is /// "interesting" and should be modeled explicitly. /// - /// \param [out] EscapingSymbol A function might not free memory in general, + /// \param [out] EscapingSymbol A function might not free memory in general, /// but could be known to free a particular symbol. In this case, false is /// returned and the single escaping symbol is returned through the out /// parameter. @@ -357,20 +357,20 @@ private: Optional<CheckKind> getCheckIfTracked(CheckerContext &C, const Stmt *AllocDeallocStmt, bool IsALeakCheck = false) const; - Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym, + Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym, bool IsALeakCheck = false) const; ///@} static bool SummarizeValue(raw_ostream &os, SVal V); static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR); - void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range, + void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range, const Expr *DeallocExpr) const; void ReportFreeAlloca(CheckerContext &C, SVal ArgVal, SourceRange Range) const; void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range, const Expr *DeallocExpr, const RefState *RS, SymbolRef Sym, bool OwnershipTransferred) const; - void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range, - const Expr *DeallocExpr, + void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range, + const Expr *DeallocExpr, const Expr *AllocExpr = nullptr) const; void ReportUseAfterFree(CheckerContext &C, SourceRange Range, SymbolRef Sym) const; @@ -425,8 +425,8 @@ private: const Stmt *Stmt) { // Did not track -> allocated. Other state (released) -> allocated. return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) && - (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) && - (!SPrev || !(SPrev->isAllocated() || + (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) && + (!SPrev || !(SPrev->isAllocated() || SPrev->isAllocatedOfSizeZero()))); } @@ -509,7 +509,7 @@ private: REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState) REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair) -// A map from the freed symbol to the symbol representing the return value of +// A map from the freed symbol to the symbol representing the return value of // the free function. REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef) @@ -633,7 +633,7 @@ bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD, return false; OverloadedOperatorKind Kind = FD->getOverloadedOperator(); - if (Kind != OO_New && Kind != OO_Array_New && + if (Kind != OO_New && Kind != OO_Array_New && Kind != OO_Delete && Kind != OO_Array_Delete) return false; @@ -798,8 +798,8 @@ void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const { State = ProcessZeroAllocation(C, CE, 0, State); } else if (isStandardNewDelete(FD, C.getASTContext())) { // Process direct calls to operator new/new[]/delete/delete[] functions - // as distinct from new/new[]/delete/delete[] expressions that are - // processed by the checkPostStmt callbacks for CXXNewExpr and + // as distinct from new/new[]/delete/delete[] expressions that are + // processed by the checkPostStmt callbacks for CXXNewExpr and // CXXDeleteExpr. OverloadedOperatorKind K = FD->getOverloadedOperator(); if (K == OO_New) { @@ -869,7 +869,7 @@ ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C, assert(Arg); - Optional<DefinedSVal> DefArgVal = + Optional<DefinedSVal> DefArgVal = State->getSVal(Arg, C.getLocationContext()).getAs<DefinedSVal>(); if (!DefArgVal) @@ -881,7 +881,7 @@ ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C, DefinedSVal Zero = SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>(); - std::tie(TrueState, FalseState) = + std::tie(TrueState, FalseState) = State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero)); if (TrueState && !FalseState) { @@ -892,7 +892,7 @@ ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C, const RefState *RS = State->get<RegionState>(Sym); if (!RS) - return State; // TODO: change to assert(RS); after realloc() will + return State; // TODO: change to assert(RS); after realloc() will // guarantee have a RegionState attached. if (!RS->isAllocated()) @@ -943,7 +943,7 @@ static bool treatUnusedNewEscaped(const CXXNewExpr *NE) { return false; } -void MallocChecker::checkPostStmt(const CXXNewExpr *NE, +void MallocChecker::checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const { if (NE->getNumPlacementArgs()) @@ -960,17 +960,17 @@ void MallocChecker::checkPostStmt(const CXXNewExpr *NE, return; ProgramStateRef State = C.getState(); - // The return value from operator new is bound to a specified initialization - // value (if any) and we don't want to loose this value. So we call - // MallocUpdateRefState() instead of MallocMemAux() which breakes the + // The return value from operator new is bound to a specified initialization + // value (if any) and we don't want to loose this value. So we call + // MallocUpdateRefState() instead of MallocMemAux() which breakes the // existing binding. - State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray + State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray : AF_CXXNew); State = ProcessZeroAllocation(C, NE, 0, State); C.addTransition(State); } -void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE, +void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const { if (!ChecksEnabled[CK_NewDeleteChecker]) @@ -1037,7 +1037,7 @@ void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call, ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE, - const OwnershipAttr *Att, + const OwnershipAttr *Att, ProgramStateRef State) const { if (!State) return nullptr; @@ -1104,7 +1104,7 @@ ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C, State = State->assume(extentMatchesSize, true); assert(State); } - + return MallocUpdateRefState(C, CE, State, Family); } @@ -1131,7 +1131,7 @@ ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C, ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE, - const OwnershipAttr *Att, + const OwnershipAttr *Att, ProgramStateRef State) const { if (!State) return nullptr; @@ -1183,7 +1183,7 @@ static bool didPreviousFreeFail(ProgramStateRef State, return false; } -AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C, +AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C, const Stmt *S) const { if (!S) return AF_None; @@ -1228,14 +1228,14 @@ AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C, return AF_None; } -bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C, +bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C, const Expr *E) const { if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { // FIXME: This doesn't handle indirect calls. const FunctionDecl *FD = CE->getDirectCallee(); if (!FD) return false; - + os << *FD; if (!FD->isOverloadedOperator()) os << "()"; @@ -1252,14 +1252,14 @@ bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C, } if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) { - os << "'" + os << "'" << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator()) << "'"; return true; } if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) { - os << "'" + os << "'" << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator()) << "'"; return true; @@ -1282,7 +1282,7 @@ void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C, } } -void MallocChecker::printExpectedDeallocName(raw_ostream &os, +void MallocChecker::printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const { switch(Family) { case AF_Malloc: os << "free()"; return; @@ -1326,25 +1326,25 @@ ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C, return nullptr; const MemRegion *R = ArgVal.getAsRegion(); - + // Nonlocs can't be freed, of course. // Non-region locations (labels and fixed addresses) also shouldn't be freed. if (!R) { ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr); return nullptr; } - + R = R->StripCasts(); - + // Blocks might show up as heap data, but should not be free()d if (isa<BlockDataRegion>(R)) { ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr); return nullptr; } - + const MemSpaceRegion *MS = R->getMemorySpace(); - - // Parameters, locals, statics, globals, and memory returned by + + // Parameters, locals, statics, globals, and memory returned by // __builtin_alloca() shouldn't be freed. if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) { // FIXME: at the time this code was written, malloc() regions were @@ -1390,7 +1390,7 @@ ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C, // If the pointer is allocated or escaped, but we are now trying to free it, // check that the call to free is proper. - } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() || + } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() || RsBase->isEscaped()) { // Check if an expected deallocation function matches the real one. @@ -1409,20 +1409,20 @@ ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C, !Offset.hasSymbolicOffset() && Offset.getOffset() != 0) { const Expr *AllocExpr = cast<Expr>(RsBase->getStmt()); - ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr, + ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr, AllocExpr); return nullptr; } } } - ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() || + ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero()); // Clean out the info on previous call to free return info. State = State->remove<FreeReturnValue>(SymBase); - // Keep track of the return value. If it is NULL, we will know that free + // Keep track of the return value. If it is NULL, we will know that free // failed. if (ReturnsNullOnFailure) { SVal RetVal = C.getSVal(ParentExpr); @@ -1462,7 +1462,7 @@ MallocChecker::getCheckIfTracked(AllocationFamily Family, if (IsALeakCheck) { if (ChecksEnabled[CK_NewDeleteLeaksChecker]) return CK_NewDeleteLeaksChecker; - } + } else { if (ChecksEnabled[CK_NewDeleteChecker]) return CK_NewDeleteChecker; @@ -1501,7 +1501,7 @@ bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) { os << "the address of the label '" << Label->getLabel()->getName() << "'"; else return false; - + return true; } @@ -1525,7 +1525,7 @@ bool MallocChecker::SummarizeRegion(raw_ostream &os, return true; default: { const MemSpaceRegion *MS = MR->getMemorySpace(); - + if (isa<StackLocalsSpaceRegion>(MS)) { const VarRegion *VR = dyn_cast<VarRegion>(MR); const VarDecl *VD; @@ -1579,8 +1579,8 @@ bool MallocChecker::SummarizeRegion(raw_ostream &os, } } -void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal, - SourceRange Range, +void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal, + SourceRange Range, const Expr *DeallocExpr) const { if (!ChecksEnabled[CK_MallocChecker] && @@ -1609,7 +1609,7 @@ void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal, os << "deallocator"; os << " is "; - bool Summarized = MR ? SummarizeRegion(os, MR) + bool Summarized = MR ? SummarizeRegion(os, MR) : SummarizeValue(os, ArgVal); if (Summarized) os << ", which is not memory allocated by "; @@ -1625,7 +1625,7 @@ void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal, } } -void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal, +void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal, SourceRange Range) const { Optional<MallocChecker::CheckKind> CheckKind; @@ -1651,11 +1651,11 @@ void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal, } } -void MallocChecker::ReportMismatchedDealloc(CheckerContext &C, +void MallocChecker::ReportMismatchedDealloc(CheckerContext &C, SourceRange Range, - const Expr *DeallocExpr, + const Expr *DeallocExpr, const RefState *RS, - SymbolRef Sym, + SymbolRef Sym, bool OwnershipTransferred) const { if (!ChecksEnabled[CK_MismatchedDeallocatorChecker]) @@ -1679,7 +1679,7 @@ void MallocChecker::ReportMismatchedDealloc(CheckerContext &C, if (OwnershipTransferred) { if (printAllocDeallocName(DeallocOs, C, DeallocExpr)) os << DeallocOs.str() << " cannot"; - else + else os << "Cannot"; os << " take ownership of memory"; @@ -1790,7 +1790,7 @@ void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range, } void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range, - bool Released, SymbolRef Sym, + bool Released, SymbolRef Sym, SymbolRef PrevSym) const { if (!ChecksEnabled[CK_MallocChecker] && @@ -1920,7 +1920,7 @@ ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C, bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull; bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero; - // If the ptr is NULL and the size is not 0, the call is equivalent to + // If the ptr is NULL and the size is not 0, the call is equivalent to // malloc(size). if ( PrtIsNull && !SizeIsZero) { ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1), @@ -1978,7 +1978,7 @@ ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C, return nullptr; } -ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE, +ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE, ProgramStateRef State) { if (!State) return nullptr; @@ -1991,7 +1991,7 @@ ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE, SVal count = State->getSVal(CE->getArg(0), LCtx); SVal elementSize = State->getSVal(CE->getArg(1), LCtx); SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize, - svalBuilder.getContext().getSizeType()); + svalBuilder.getContext().getSizeType()); SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy); return MallocMemAux(C, CE, TotalSize, zeroVal, State); @@ -2078,7 +2078,7 @@ void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N, const ExplodedNode *AllocNode = nullptr; const MemRegion *Region = nullptr; std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C); - + ProgramPoint P = AllocNode->getLocation(); const Stmt *AllocationStmt = nullptr; if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>()) @@ -2127,7 +2127,7 @@ void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper, } } - + // Cleanup the Realloc Pairs Map. ReallocPairsTy RP = state->get<ReallocPairs>(); for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) { @@ -2232,7 +2232,7 @@ void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const { } // TODO: Blocks should be either inlined or should call invalidate regions -// upon invocation. After that's in place, special casing here will not be +// upon invocation. After that's in place, special casing here will not be // needed. void MallocChecker::checkPostStmt(const BlockExpr *BE, CheckerContext &C) const { @@ -2446,7 +2446,7 @@ bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly( StringRef FName = II->getName(); // White list the 'XXXNoCopy' CoreFoundation functions. - // We specifically check these before + // We specifically check these before if (FName.endswith("NoCopy")) { // Look for the deallocator argument. We know that the memory ownership // is not transferred only if the deallocator argument is @@ -2555,7 +2555,7 @@ ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State, if (EscapingSymbol && EscapingSymbol != sym) continue; - + if (const RefState *RS = State->get<RegionState>(sym)) { if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) && CheckRefState(RS)) { @@ -2702,7 +2702,7 @@ void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) { checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true; checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] = mgr.getCurrentCheckName(); - // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete + // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete // checker. if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker]) checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true; diff --git a/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp index e91347999dc..45ebd6892ca 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp @@ -33,7 +33,7 @@ struct MallocOverflowCheck { const BinaryOperator *mulop; const Expr *variable; - MallocOverflowCheck (const BinaryOperator *m, const Expr *v) + MallocOverflowCheck (const BinaryOperator *m, const Expr *v) : mulop(m), variable (v) {} }; diff --git a/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp index fb07484bfcd..80a3fbe1a40 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp @@ -143,20 +143,20 @@ static bool typesCompatible(ASTContext &C, QualType A, QualType B) { while (true) { A = A.getCanonicalType(); B = B.getCanonicalType(); - + if (A.getTypePtr() == B.getTypePtr()) return true; - + if (const PointerType *ptrA = A->getAs<PointerType>()) if (const PointerType *ptrB = B->getAs<PointerType>()) { A = ptrA->getPointeeType(); B = ptrB->getPointeeType(); continue; } - + break; } - + return false; } diff --git a/clang/lib/StaticAnalyzer/Checkers/NSAutoreleasePoolChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/NSAutoreleasePoolChecker.cpp index d23708ecbd9..5d9b32fa911 100644 --- a/clang/lib/StaticAnalyzer/Checkers/NSAutoreleasePoolChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/NSAutoreleasePoolChecker.cpp @@ -11,7 +11,7 @@ // about subpar uses of NSAutoreleasePool. Note that while the check itself // (in its current form) could be written as a flow-insensitive check, in // can be potentially enhanced in the future with flow-sensitive information. -// It is also a good example of the CheckerVisitor interface. +// It is also a good example of the CheckerVisitor interface. // //===----------------------------------------------------------------------===// @@ -48,7 +48,7 @@ void NSAutoreleasePoolChecker::checkPreObjCMessage(const ObjCMethodCall &msg, const ObjCInterfaceDecl *OD = msg.getReceiverInterface(); if (!OD) - return; + return; if (!OD->getIdentifier()->isStr("NSAutoreleasePool")) return; diff --git a/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp index c351c6e9e08..dab068b27e8 100644 --- a/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp @@ -58,7 +58,7 @@ void NSErrorMethodChecker::checkASTDecl(const ObjCMethodDecl *D, return; if (!II) - II = &D->getASTContext().Idents.get("NSError"); + II = &D->getASTContext().Idents.get("NSError"); bool hasNSError = false; for (const auto *I : D->params()) { @@ -105,7 +105,7 @@ void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D, return; if (!II) - II = &D->getASTContext().Idents.get("CFErrorRef"); + II = &D->getASTContext().Idents.get("CFErrorRef"); bool hasCFError = false; for (auto I : D->params()) { diff --git a/clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp index 53e159879eb..14f4969c444 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp @@ -133,7 +133,7 @@ void ObjCContainersChecker::checkPreStmt(const CallExpr *CE, if (IdxVal.isUnknownOrUndef()) return; DefinedSVal Idx = IdxVal.castAs<DefinedSVal>(); - + // Now, check if 'Idx in [0, Size-1]'. const QualType T = IdxExpr->getType(); ProgramStateRef StInBound = State->assumeInBound(Idx, *Size, true, T); diff --git a/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp index 6df1da5eb4d..32a1adb587b 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp @@ -49,7 +49,7 @@ public: DoesCallSuper = true; // Recurse if we didn't find the super call yet. - return !DoesCallSuper; + return !DoesCallSuper; } bool DoesCallSuper; @@ -59,7 +59,7 @@ private: }; //===----------------------------------------------------------------------===// -// ObjCSuperCallChecker +// ObjCSuperCallChecker //===----------------------------------------------------------------------===// class ObjCSuperCallChecker : public Checker< @@ -202,7 +202,7 @@ void ObjCSuperCallChecker::checkASTDecl(const ObjCImplementationDecl *D, SmallString<320> Buf; llvm::raw_svector_ostream os(Buf); - os << "The '" << S.getAsString() + os << "The '" << S.getAsString() << "' instance method in " << SuperclassName.str() << " subclass '" << *D << "' is missing a [super " << S.getAsString() << "] call"; diff --git a/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp index 93b0553b3b7..193f515d1ca 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp @@ -145,13 +145,13 @@ void ObjCSelfInitChecker::checkForInvalidSelf(const Expr *E, CheckerContext &C, const char *errorStr) const { if (!E) return; - + if (!C.getState()->get<CalledInit>()) return; - + if (!isInvalidSelf(E, C)) return; - + // Generate an error node. ExplodedNode *N = C.generateSink(); if (!N) @@ -177,12 +177,12 @@ void ObjCSelfInitChecker::checkPostObjCMessage(const ObjCMethodCall &Msg, if (isInitMessage(Msg)) { // Tag the return value as the result of an initializer. ProgramStateRef state = C.getState(); - + // FIXME this really should be context sensitive, where we record // the current stack frame (for IPA). Also, we need to clean this // value out when we return from this method. state = state->set<CalledInit>(true); - + SVal V = state->getSVal(Msg.getOriginExpr(), C.getLocationContext()); addSelfFlag(state, V, SelfFlag_InitRes, C); return; @@ -318,7 +318,7 @@ void ObjCSelfInitChecker::checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const { // Allow assignment of anything to self. Self is a local variable in the // initializer, so it is legal to assign anything to it, like results of - // static functions/method calls. After self is assigned something we cannot + // static functions/method calls. After self is assigned something we cannot // reason about, stop enforcing the rules. // (Only continue checking if the assigned value should be treated as self.) if ((isSelfVar(loc, C)) && @@ -412,7 +412,7 @@ static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) { /// \brief Returns true if the location is 'self'. static bool isSelfVar(SVal location, CheckerContext &C) { - AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext(); + AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext(); if (!analCtx->getSelfDecl()) return false; if (!location.getAs<loc::MemRegionVal>()) diff --git a/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp index 806312468be..313fe7c43e0 100644 --- a/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp @@ -22,7 +22,7 @@ using namespace clang; using namespace ento; namespace { -class PointerArithChecker +class PointerArithChecker : public Checker< check::PreStmt<BinaryOperator> > { mutable std::unique_ptr<BuiltinBug> BT; @@ -48,7 +48,7 @@ void PointerArithChecker::checkPreStmt(const BinaryOperator *B, // If pointer arithmetic is done on variables of non-array type, this often // means behavior rely on memory organization, which is dangerous. - if (isa<VarRegion>(LR) || isa<CodeTextRegion>(LR) || + if (isa<VarRegion>(LR) || isa<CodeTextRegion>(LR) || isa<CompoundLiteralRegion>(LR)) { if (ExplodedNode *N = C.addTransition()) { diff --git a/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp index cf1f88a2851..a3b02d99741 100644 --- a/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp @@ -8,7 +8,7 @@ //===----------------------------------------------------------------------===// // // This files defines PointerSubChecker, a builtin checker that checks for -// pointer subtractions on two pointers pointing to different memory chunks. +// pointer subtractions on two pointers pointing to different memory chunks. // This check corresponds to CWE-469. // //===----------------------------------------------------------------------===// @@ -23,7 +23,7 @@ using namespace clang; using namespace ento; namespace { -class PointerSubChecker +class PointerSubChecker : public Checker< check::PreStmt<BinaryOperator> > { mutable std::unique_ptr<BuiltinBug> BT; diff --git a/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp index 4209017a58d..4b8c0b7a98e 100644 --- a/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp @@ -62,10 +62,10 @@ class PthreadLockChecker : public Checker< check::PostStmt<CallExpr> > { }; public: void checkPostStmt(const CallExpr *CE, CheckerContext &C) const; - + void AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock, bool isTryLock, enum LockingSemantics semantics) const; - + void ReleaseLock(CheckerContext &C, const CallExpr *CE, SVal lock) const; void DestroyLock(CheckerContext &C, const CallExpr *CE, SVal Lock) const; void InitLock(CheckerContext &C, const CallExpr *CE, SVal Lock) const; @@ -96,7 +96,7 @@ void PthreadLockChecker::checkPostStmt(const CallExpr *CE, false, PthreadSemantics); else if (FName == "lck_mtx_lock" || FName == "lck_rw_lock_exclusive" || - FName == "lck_rw_lock_shared") + FName == "lck_rw_lock_shared") AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx), false, XNUSemantics); else if (FName == "pthread_mutex_trylock" || @@ -124,17 +124,17 @@ void PthreadLockChecker::checkPostStmt(const CallExpr *CE, void PthreadLockChecker::AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock, bool isTryLock, enum LockingSemantics semantics) const { - + const MemRegion *lockR = lock.getAsRegion(); if (!lockR) return; - + ProgramStateRef state = C.getState(); - + SVal X = state->getSVal(CE, C.getLocationContext()); if (X.isUnknownOrUndef()) return; - + DefinedSVal retVal = X.castAs<DefinedSVal>(); if (const LockState *LState = state->get<LockMap>(lockR)) { @@ -183,8 +183,8 @@ void PthreadLockChecker::AcquireLock(CheckerContext &C, const CallExpr *CE, assert((semantics == XNUSemantics) && "Unknown locking semantics"); lockSucc = state; } - - // Record that the lock was acquired. + + // Record that the lock was acquired. lockSucc = lockSucc->add<LockSet>(lockR); lockSucc = lockSucc->set<LockMap>(lockR, LockState::getLocked()); C.addTransition(lockSucc); @@ -196,7 +196,7 @@ void PthreadLockChecker::ReleaseLock(CheckerContext &C, const CallExpr *CE, const MemRegion *lockR = lock.getAsRegion(); if (!lockR) return; - + ProgramStateRef state = C.getState(); if (const LockState *LState = state->get<LockMap>(lockR)) { diff --git a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp index 9369aeb5446..490a242191b 100644 --- a/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp @@ -250,7 +250,7 @@ public: bool operator==(const RefVal& X) const { return T == X.T && hasSameState(X) && getObjKind() == X.getObjKind(); } - + void Profile(llvm::FoldingSetNodeID& ID) const { ID.Add(T); ID.AddInteger(RawKind); @@ -426,16 +426,16 @@ public: /// setRetEffect - Set the effect of the return value of the call. void setRetEffect(RetEffect E) { Ret = E; } - + /// Sets the effect on the receiver of the message. void setReceiverEffect(ArgEffect e) { Receiver = e; } - + /// getReceiverEffect - Returns the effect on the receiver of the call. /// This is only meaningful if the summary applies to an ObjCMessageExpr*. ArgEffect getReceiverEffect() const { return Receiver; } /// Test if two retain summaries are identical. Note that merely equivalent - /// summaries are not necessarily identical (for example, if an explicit + /// summaries are not necessarily identical (for example, if an explicit /// argument effect matches the default effect). bool operator==(const RetainSummary &Other) const { return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect && @@ -621,7 +621,7 @@ class RetainSummaryManager { ArgEffects::Factory AF; /// ScratchArgs - A holding buffer for construct ArgEffects. - ArgEffects ScratchArgs; + ArgEffects ScratchArgs; /// ObjCAllocRetE - Default return effect for methods returning Objective-C /// objects. @@ -644,7 +644,7 @@ class RetainSummaryManager { ArgEffects getArgEffects(); enum UnaryFuncKind { cfretain, cfrelease, cfautorelease, cfmakecollectable }; - + const RetainSummary *getUnarySummary(const FunctionType* FT, UnaryFuncKind func); @@ -664,7 +664,7 @@ class RetainSummaryManager { const RetainSummary *getDoNothingSummary() { return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); } - + const RetainSummary *getDefaultSummary() { return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, MayEscape); @@ -689,7 +689,7 @@ private: void addClassMethSummary(const char* Cls, const char* name, const RetainSummary *Summ, bool isNullary = true) { IdentifierInfo* ClsII = &Ctx.Idents.get(Cls); - Selector S = isNullary ? GetNullarySelector(name, Ctx) + Selector S = isNullary ? GetNullarySelector(name, Ctx) : GetUnarySelector(name, Ctx); ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; } @@ -739,7 +739,7 @@ public: ? RetEffect::MakeGCNotOwned() : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC) : RetEffect::MakeOwned(RetEffect::ObjC, true))), - ObjCInitRetE(gcenabled + ObjCInitRetE(gcenabled ? RetEffect::MakeGCNotOwned() : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC) : RetEffect::MakeOwnedWhenTrackedReceiver())) { @@ -803,7 +803,7 @@ public: bool isGCEnabled() const { return GCEnabled; } bool isARCEnabled() const { return ARCEnabled; } - + bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; } RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; } @@ -966,7 +966,7 @@ void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S, // Additionally, our Self Init checker already warns about it. To avoid // overwhelming the user with messages from both checkers, we model the case // of '[super init]' in cases when it is not consumed by another expression - // as if the call preserves the value of 'self'; essentially, assuming it can + // as if the call preserves the value of 'self'; essentially, assuming it can // never fail and return 'nil'. // Note, we don't want to just stop tracking the value since we want the // RetainCount checker to report leaks and use-after-free if SelfInit checker @@ -1150,7 +1150,7 @@ RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) { if (S) break; - if (RetTy->isPointerType()) { + if (RetTy->isPointerType()) { // For CoreFoundation ('CF') types. if (cocoa::isRefType(RetTy, "CF", FName)) { if (isRetain(FD, FName)) { @@ -1278,14 +1278,14 @@ RetainSummaryManager::getUnarySummary(const FunctionType* FT, return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); } -const RetainSummary * +const RetainSummary * RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) { assert (ScratchArgs.isEmpty()); return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true)); } -const RetainSummary * +const RetainSummary * RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) { assert (ScratchArgs.isEmpty()); return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF), @@ -1331,7 +1331,7 @@ RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ, // Effects on the parameters. unsigned parm_idx = 0; - for (FunctionDecl::param_const_iterator pi = FD->param_begin(), + for (FunctionDecl::param_const_iterator pi = FD->param_begin(), pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) { const ParmVarDecl *pd = *pi; if (pd->hasAttr<NSConsumedAttr>()) @@ -1367,8 +1367,8 @@ RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ, // Effects on the receiver. if (MD->hasAttr<NSConsumesSelfAttr>()) - Template->setReceiverEffect(DecRefMsg); - + Template->setReceiverEffect(DecRefMsg); + // Effects on the parameters. unsigned parm_idx = 0; for (ObjCMethodDecl::param_const_iterator @@ -1376,9 +1376,9 @@ RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ, pi != pe; ++pi, ++parm_idx) { const ParmVarDecl *pd = *pi; if (pd->hasAttr<NSConsumedAttr>()) - Template->addArg(AF, parm_idx, DecRefMsg); + Template->addArg(AF, parm_idx, DecRefMsg); else if (pd->hasAttr<CFConsumedAttr>()) { - Template->addArg(AF, parm_idx, DecRef); + Template->addArg(AF, parm_idx, DecRef); } else if (pd->hasAttr<CFReturnsRetainedAttr>()) { QualType PointeeTy = pd->getType()->getPointeeType(); if (!PointeeTy.isNull()) @@ -1415,7 +1415,7 @@ RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD, if (cocoa::isCocoaObjectRef(RetTy)) ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC); else if (coreFoundation::isCFObjectRef(RetTy)) { - // ObjCMethodDecl currently doesn't consider CF objects as valid return + // ObjCMethodDecl currently doesn't consider CF objects as valid return // values for alloc, new, copy, or mutableCopy, so we have to // double-check with the selector. This is ugly, but there aren't that // many Objective-C methods that return CF objects, right? @@ -1428,11 +1428,11 @@ RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD, ResultEff = RetEffect::MakeOwned(RetEffect::CF, true); break; default: - ResultEff = RetEffect::MakeNotOwned(RetEffect::CF); + ResultEff = RetEffect::MakeNotOwned(RetEffect::CF); break; } } else { - ResultEff = RetEffect::MakeNotOwned(RetEffect::CF); + ResultEff = RetEffect::MakeNotOwned(RetEffect::CF); } } break; @@ -1749,7 +1749,7 @@ namespace { SymbolRef Sym; const SummaryLogTy &SummaryLog; bool GCEnabled; - + public: CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log) : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {} @@ -1869,7 +1869,7 @@ void CFRefReport::addGCModeDescription(const LangOptions &LOpts, static bool isNumericLiteralExpression(const Expr *E) { // FIXME: This set of cases was copied from SemaExprObjC. - return isa<IntegerLiteral>(E) || + return isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) || isa<FloatingLiteral>(E) || isa<ObjCBoolLiteralExpr>(E) || @@ -1948,7 +1948,7 @@ PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N, else if (isa<ObjCIvarRefExpr>(S)) { os << "Object loaded from instance variable"; } - else { + else { if (const CallExpr *CE = dyn_cast<CallExpr>(S)) { // Get the name of the callee (if it is available). SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx); @@ -2228,7 +2228,7 @@ GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N, StoreManager::FindUniqueBinding FB(Sym); StateMgr.iterBindings(St, FB); - + if (FB) { const MemRegion *R = FB.getRegion(); const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>(); @@ -2345,10 +2345,10 @@ CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC, // objects. Only "copy", "alloc", "retain" and "new" transfer ownership // to the caller for NS objects. const Decl *D = &EndN->getCodeDecl(); - + os << (isa<ObjCMethodDecl>(D) ? " is returned from a method " : " is returned from a function "); - + if (D->hasAttr<CFReturnsNotRetainedAttr>()) os << "that is annotated as CF_RETURNS_NOT_RETAINED"; else if (D->hasAttr<NSReturnsNotRetainedAttr>()) @@ -2385,7 +2385,7 @@ CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC, } CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, - bool GCEnabled, const SummaryLogTy &Log, + bool GCEnabled, const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym, CheckerContext &Ctx, bool IncludeAllocationLine) @@ -2492,7 +2492,7 @@ class RetainCountChecker /// the allocation line. mutable bool IncludeAllocationLine; -public: +public: RetainCountChecker(AnalyzerOptions &AO) : ShouldResetSummaryLog(false), IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {} @@ -2617,7 +2617,7 @@ public: void checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const; void checkPostCall(const CallEvent &Call, CheckerContext &C) const; - + void checkSummary(const RetainSummary &Summ, const CallEvent &Call, CheckerContext &C) const; @@ -2630,13 +2630,13 @@ public: ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond, bool Assumption) const; - ProgramStateRef + ProgramStateRef checkRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef<const MemRegion *> ExplicitRegions, ArrayRef<const MemRegion *> Regions, const CallEvent *Call) const; - + bool wantsRegionChangeUpdate(ProgramStateRef state) const { return true; } @@ -2645,7 +2645,7 @@ public: void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C, ExplodedNode *Pred, RetEffect RE, RefVal X, SymbolRef Sym, ProgramStateRef state) const; - + void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const; void checkEndFunction(CheckerContext &C) const; @@ -2656,7 +2656,7 @@ public: void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange, RefVal::Kind ErrorKind, SymbolRef Sym, CheckerContext &C) const; - + void processObjCLiterals(CheckerContext &C, const Expr *Ex) const; const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const; @@ -2740,21 +2740,21 @@ void RetainCountChecker::checkPostStmt(const CastExpr *CE, const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE); if (!BE) return; - + ArgEffect AE = IncRef; - + switch (BE->getBridgeKind()) { case clang::OBC_Bridge: // Do nothing. return; case clang::OBC_BridgeRetained: AE = IncRef; - break; + break; case clang::OBC_BridgeTransfer: AE = DecRefBridgedTransferred; break; } - + ProgramStateRef state = C.getState(); SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol(); if (!Sym) @@ -2765,7 +2765,7 @@ void RetainCountChecker::checkPostStmt(const CastExpr *CE, RefVal::Kind hasErr = (RefVal::Kind) 0; state = updateSymbol(state, Sym, *T, AE, hasErr, C); - + if (hasErr) { // FIXME: If we get an error during a bridge cast, should we report it? return; @@ -2777,7 +2777,7 @@ void RetainCountChecker::checkPostStmt(const CastExpr *CE, void RetainCountChecker::processObjCLiterals(CheckerContext &C, const Expr *Ex) const { ProgramStateRef state = C.getState(); - const ExplodedNode *pred = C.getPredecessor(); + const ExplodedNode *pred = C.getPredecessor(); for (const Stmt *Child : Ex->children()) { SVal V = state->getSVal(Child, pred->getLocationContext()); if (SymbolRef sym = V.getAsSymbol()) @@ -2790,17 +2790,17 @@ void RetainCountChecker::processObjCLiterals(CheckerContext &C, } } } - + // Return the object as autoreleased. // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC); - if (SymbolRef sym = + if (SymbolRef sym = state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) { QualType ResultTy = Ex->getType(); state = setRefBinding(state, sym, RefVal::makeNotOwned(RetEffect::ObjC, ResultTy)); } - - C.addTransition(state); + + C.addTransition(state); } void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL, @@ -2817,7 +2817,7 @@ void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL, void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex, CheckerContext &C) const { - const ExplodedNode *Pred = C.getPredecessor(); + const ExplodedNode *Pred = C.getPredecessor(); const LocationContext *LCtx = Pred->getLocationContext(); ProgramStateRef State = Pred->getState(); @@ -2966,7 +2966,7 @@ void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ, if (Sym) state = removeRefBinding(state, Sym); } - + C.addTransition(state); } @@ -3062,7 +3062,7 @@ void RetainCountChecker::checkSummary(const RetainSummary &Summ, if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) { if (ReceiverIsTracked) - RE = getSummaryManager(C).getObjAllocRetEffect(); + RE = getSummaryManager(C).getObjAllocRetEffect(); else RE = RetEffect::MakeNoRet(); } @@ -3130,7 +3130,7 @@ void RetainCountChecker::checkSummary(const RetainSummary &Summ, } -ProgramStateRef +ProgramStateRef RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym, RefVal V, ArgEffect E, RefVal::Kind &hasErr, CheckerContext &C) const { @@ -3388,7 +3388,7 @@ bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const { isMakeCollectable(FD, FName); } } - + if (!canEval) return false; @@ -3700,7 +3700,7 @@ ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state, return state; } -ProgramStateRef +ProgramStateRef RetainCountChecker::checkRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef<const MemRegion *> ExplicitRegions, @@ -3810,7 +3810,7 @@ RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state, return nullptr; } -ProgramStateRef +ProgramStateRef RetainCountChecker::handleSymbolDeath(ProgramStateRef state, SymbolRef sid, RefVal V, SmallVectorImpl<SymbolRef> &Leaked) const { @@ -3890,7 +3890,7 @@ void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const { // and suggest annotations. if (LCtx->getParent()) return; - + B = state->get<RefBindings>(); SmallVector<SymbolRef, 10> Leaked; @@ -3910,7 +3910,7 @@ RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const { sym->dumpToStream(out); tag = new CheckerProgramPointTag(this, out.str()); } - return tag; + return tag; } void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper, diff --git a/clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp index acbd0d95d07..d94299c050d 100644 --- a/clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp @@ -23,7 +23,7 @@ using namespace clang; using namespace ento; namespace { -class ReturnPointerRangeChecker : +class ReturnPointerRangeChecker : public Checker< check::PreStmt<ReturnStmt> > { mutable std::unique_ptr<BuiltinBug> BT; @@ -39,7 +39,7 @@ void ReturnPointerRangeChecker::checkPreStmt(const ReturnStmt *RS, const Expr *RetE = RS->getRetValue(); if (!RetE) return; - + SVal V = state->getSVal(RetE, C.getLocationContext()); const MemRegion *R = V.getAsRegion(); @@ -66,7 +66,7 @@ void ReturnPointerRangeChecker::checkPreStmt(const ReturnStmt *RS, if (!N) return; - + // FIXME: This bug correspond to CWE-466. Eventually we should have bug // types explicitly reference such exploit categories (when applicable). if (!BT) diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp index 813c811ef15..f57cd70fd44 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file defines stack address leak checker, which checks if an invalid +// This file defines stack address leak checker, which checks if an invalid // stack address is stored into a global or heap location. See CERT DCL30-C. // //===----------------------------------------------------------------------===// @@ -49,20 +49,20 @@ SourceRange StackAddrEscapeChecker::genName(raw_ostream &os, const MemRegion *R, SourceManager &SM = Ctx.getSourceManager(); SourceRange range; os << "Address of "; - + // Check if the region is a compound literal. - if (const CompoundLiteralRegion* CR = dyn_cast<CompoundLiteralRegion>(R)) { + if (const CompoundLiteralRegion* CR = dyn_cast<CompoundLiteralRegion>(R)) { const CompoundLiteralExpr *CL = CR->getLiteralExpr(); os << "stack memory associated with a compound literal " "declared on line " << SM.getExpansionLineNumber(CL->getLocStart()) - << " returned to caller"; + << " returned to caller"; range = CL->getSourceRange(); } else if (const AllocaRegion* AR = dyn_cast<AllocaRegion>(R)) { const Expr *ARE = AR->getExpr(); SourceLocation L = ARE->getLocStart(); - range = ARE->getSourceRange(); + range = ARE->getSourceRange(); os << "stack memory allocated by call to alloca() on line " << SM.getExpansionLineNumber(L); } @@ -87,8 +87,8 @@ SourceRange StackAddrEscapeChecker::genName(raw_ostream &os, const MemRegion *R, } else { llvm_unreachable("Invalid region in ReturnStackAddressChecker."); - } - + } + return range; } @@ -118,7 +118,7 @@ void StackAddrEscapeChecker::EmitStackError(CheckerContext &C, const MemRegion * void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const { - + const Expr *RetE = RS->getRetValue(); if (!RetE) return; @@ -130,10 +130,10 @@ void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS, if (!R) return; - + const StackSpaceRegion *SS = dyn_cast_or_null<StackSpaceRegion>(R->getMemorySpace()); - + if (!SS) return; @@ -175,35 +175,35 @@ void StackAddrEscapeChecker::checkEndFunction(CheckerContext &Ctx) const { Ctx(CC), CurSFC(CC.getLocationContext()->getCurrentStackFrame()) {} - + bool HandleBinding(StoreManager &SMgr, Store store, const MemRegion *region, SVal val) override { if (!isa<GlobalsSpaceRegion>(region->getMemorySpace())) return true; - + const MemRegion *vR = val.getAsRegion(); if (!vR) return true; - + // Under automated retain release, it is okay to assign a block // directly to a global variable. if (Ctx.getASTContext().getLangOpts().ObjCAutoRefCount && isa<BlockDataRegion>(vR)) return true; - if (const StackSpaceRegion *SSR = + if (const StackSpaceRegion *SSR = dyn_cast<StackSpaceRegion>(vR->getMemorySpace())) { // If the global variable holds a location in the current stack frame, // record the binding to emit a warning. if (SSR->getStackFrame() == CurSFC) V.push_back(std::make_pair(region, vR)); } - + return true; } }; - + CallBack cb(Ctx); state->getStateManager().getStoreManager().iterBindings(state->getStore(),cb); diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp index 2109a75b1fb..f9dfd38e1f8 100644 --- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp @@ -43,8 +43,8 @@ struct StreamState { static StreamState getOpened(const Stmt *s) { return StreamState(Opened, s); } static StreamState getClosed(const Stmt *s) { return StreamState(Closed, s); } - static StreamState getOpenFailed(const Stmt *s) { - return StreamState(OpenFailed, s); + static StreamState getOpenFailed(const Stmt *s) { + return StreamState(OpenFailed, s); } static StreamState getEscaped(const Stmt *s) { return StreamState(Escaped, s); @@ -59,14 +59,14 @@ struct StreamState { class StreamChecker : public Checker<eval::Call, check::DeadSymbols > { mutable IdentifierInfo *II_fopen, *II_tmpfile, *II_fclose, *II_fread, - *II_fwrite, - *II_fseek, *II_ftell, *II_rewind, *II_fgetpos, *II_fsetpos, + *II_fwrite, + *II_fseek, *II_ftell, *II_rewind, *II_fgetpos, *II_fsetpos, *II_clearerr, *II_feof, *II_ferror, *II_fileno; mutable std::unique_ptr<BuiltinBug> BT_nullfp, BT_illegalwhence, BT_doubleclose, BT_ResourceLeak; public: - StreamChecker() + StreamChecker() : II_fopen(nullptr), II_tmpfile(nullptr), II_fclose(nullptr), II_fread(nullptr), II_fwrite(nullptr), II_fseek(nullptr), II_ftell(nullptr), II_rewind(nullptr), II_fgetpos(nullptr), @@ -93,10 +93,10 @@ private: void Fileno(CheckerContext &C, const CallExpr *CE) const; void OpenFileAux(CheckerContext &C, const CallExpr *CE) const; - - ProgramStateRef CheckNullStream(SVal SV, ProgramStateRef state, + + ProgramStateRef CheckNullStream(SVal SV, ProgramStateRef state, CheckerContext &C) const; - ProgramStateRef CheckDoubleClose(const CallExpr *CE, ProgramStateRef state, + ProgramStateRef CheckDoubleClose(const CallExpr *CE, ProgramStateRef state, CheckerContext &C) const; }; @@ -216,13 +216,13 @@ void StreamChecker::OpenFileAux(CheckerContext &C, const CallExpr *CE) const { C.blockCount()) .castAs<DefinedSVal>(); state = state->BindExpr(CE, C.getLocationContext(), RetVal); - + ConstraintManager &CM = C.getConstraintManager(); // Bifurcate the state into two: one with a valid FILE* pointer, the other // with a NULL. ProgramStateRef stateNotNull, stateNull; std::tie(stateNotNull, stateNull) = CM.assumeDual(state, RetVal); - + if (SymbolRef Sym = RetVal.getAsSymbol()) { // if RetVal is not NULL, set the symbol's state to Opened. stateNotNull = @@ -368,13 +368,13 @@ ProgramStateRef StreamChecker::CheckDoubleClose(const CallExpr *CE, state->getSVal(CE->getArg(0), C.getLocationContext()).getAsSymbol(); if (!Sym) return state; - + const StreamState *SS = state->get<StreamMap>(Sym); // If the file stream is not tracked, return. if (!SS) return state; - + // Check: Double close a File Descriptor could cause undefined behaviour. // Conforming to man-pages if (SS->isClosed()) { @@ -389,7 +389,7 @@ ProgramStateRef StreamChecker::CheckDoubleClose(const CallExpr *CE, } return nullptr; } - + // Close the File Descriptor. return state->set<StreamMap>(Sym, StreamState::getClosed(CE)); } diff --git a/clang/lib/StaticAnalyzer/Checkers/UndefBranchChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UndefBranchChecker.cpp index 1d8ef994717..268e957ea5b 100644 --- a/clang/lib/StaticAnalyzer/Checkers/UndefBranchChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UndefBranchChecker.cpp @@ -30,7 +30,7 @@ class UndefBranchChecker : public Checker<check::BranchCondition> { ProgramStateRef St; const LocationContext *LCtx; - FindUndefExpr(ProgramStateRef S, const LocationContext *L) + FindUndefExpr(ProgramStateRef S, const LocationContext *L) : St(S), LCtx(L) {} const Expr *FindExpr(const Expr *Ex) { @@ -45,7 +45,7 @@ class UndefBranchChecker : public Checker<check::BranchCondition> { return Ex; } - bool MatchesCriteria(const Expr *Ex) { + bool MatchesCriteria(const Expr *Ex) { return St->getSVal(Ex, LCtx).isUndef(); } }; diff --git a/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp index 53fd069bf15..0f426b5d54e 100644 --- a/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp @@ -83,7 +83,7 @@ UndefCapturedBlockVarChecker::checkPostStmt(const BlockExpr *BE, SmallString<128> buf; llvm::raw_svector_ostream os(buf); - os << "Variable '" << VD->getName() + os << "Variable '" << VD->getName() << "' is uninitialized when captured by block"; auto R = llvm::make_unique<BugReport>(*BT, os.str(), N); diff --git a/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp index 5353310e6d5..8ae8694ca70 100644 --- a/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This defines UndefResultChecker, a builtin check in ExprEngine that +// This defines UndefResultChecker, a builtin check in ExprEngine that // performs checks for undefined results of non-assignment binary operators. // //===----------------------------------------------------------------------===// @@ -25,7 +25,7 @@ using namespace clang; using namespace ento; namespace { -class UndefResultChecker +class UndefResultChecker : public Checker< check::PostStmt<BinaryOperator> > { mutable std::unique_ptr<BugType> BT; @@ -53,7 +53,7 @@ void UndefResultChecker::checkPostStmt(const BinaryOperator *B, ExplodedNode *N = C.generateSink(); if (!N) return; - + if (!BT) BT.reset( new BuiltinBug(this, "Result of operation is garbage or undefined")); @@ -62,7 +62,7 @@ void UndefResultChecker::checkPostStmt(const BinaryOperator *B, llvm::raw_svector_ostream OS(sbuf); const Expr *Ex = nullptr; bool isLeft = true; - + if (state->getSVal(B->getLHS(), LCtx).isUndef()) { Ex = B->getLHS()->IgnoreParenCasts(); isLeft = true; @@ -71,13 +71,13 @@ void UndefResultChecker::checkPostStmt(const BinaryOperator *B, Ex = B->getRHS()->IgnoreParenCasts(); isLeft = false; } - + if (Ex) { OS << "The " << (isLeft ? "left" : "right") << " operand of '" << BinaryOperator::getOpcodeStr(B->getOpcode()) << "' is a garbage value"; - } + } else { // Neither operand was undefined, but the result is undefined. OS << "The result of the '" @@ -91,7 +91,7 @@ void UndefResultChecker::checkPostStmt(const BinaryOperator *B, } else bugreporter::trackNullOrUndefValue(N, B, *report); - + C.emitReport(std::move(report)); } } diff --git a/clang/lib/StaticAnalyzer/Checkers/UndefinedArraySubscriptChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UndefinedArraySubscriptChecker.cpp index ba4daf83514..c80732f2741 100644 --- a/clang/lib/StaticAnalyzer/Checkers/UndefinedArraySubscriptChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UndefinedArraySubscriptChecker.cpp @@ -32,7 +32,7 @@ public: }; } // end anonymous namespace -void +void UndefinedArraySubscriptChecker::checkPreStmt(const ArraySubscriptExpr *A, CheckerContext &C) const { const Expr *Index = A->getIdx(); diff --git a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp index a799b4c2198..cf580ad4654 100644 --- a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp @@ -114,7 +114,7 @@ void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const { // The definition of O_CREAT is platform specific. We need a better way // of querying this information from the checking environment. if (!Val_O_CREAT.hasValue()) { - if (C.getASTContext().getTargetInfo().getTriple().getVendor() + if (C.getASTContext().getTargetInfo().getTriple().getVendor() == llvm::Triple::Apple) Val_O_CREAT = 0x0200; else { @@ -220,7 +220,7 @@ static bool IsZeroByteAllocation(ProgramStateRef state, ProgramStateRef *falseState) { std::tie(*trueState, *falseState) = state->assume(argVal.castAs<DefinedSVal>()); - + return (*falseState && !*trueState); } @@ -239,7 +239,7 @@ bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C, "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)"); SmallString<256> S; - llvm::raw_svector_ostream os(S); + llvm::raw_svector_ostream os(S); os << "Call to '" << fn_name << "' has an allocation size of 0 bytes"; auto report = llvm::make_unique<BugReport>(*BT_mallocZero, os.str(), N); @@ -272,13 +272,13 @@ void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C, // Is the value perfectly constrained to zero? if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) { - (void) ReportZeroByteAllocation(C, falseState, arg, fn); + (void) ReportZeroByteAllocation(C, falseState, arg, fn); return; } // Assume the value is non-zero going forward. assert(trueState); if (trueState != state) - C.addTransition(trueState); + C.addTransition(trueState); } void UnixAPIChecker::CheckCallocZero(CheckerContext &C, diff --git a/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp index d78de3c6f3a..9f66dc9be4c 100644 --- a/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp @@ -54,7 +54,7 @@ void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G, BugReporter &B, ExprEngine &Eng) const { CFGBlocksSet reachable, visited; - + if (Eng.hasWorkRemaining()) return; @@ -88,7 +88,7 @@ void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G, // Bail out if we didn't get the CFG or the ParentMap. if (!D || !C || !PM) return; - + // Don't do anything for template instantiations. Proving that code // in a template instantiation is unreachable means proving that it is // unreachable in all instantiations. diff --git a/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp index 80384bbfdb3..8cd3aac7476 100644 --- a/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This defines VLASizeChecker, a builtin check in ExprEngine that +// This defines VLASizeChecker, a builtin check in ExprEngine that // performs checks for declaration of VLA of undefined or zero size. // In addition, VLASizeChecker is responsible for defining the extent // of the MemRegion that represents a VLA. @@ -82,7 +82,7 @@ void VLASizeChecker::reportBug(VLASize_Kind Kind, void VLASizeChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const { if (!DS->isSingleDecl()) return; - + const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()); if (!VD) return; @@ -106,7 +106,7 @@ void VLASizeChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const { // warned about that already. if (sizeV.isUnknown()) return; - + // Check if the size is tainted. if (state->isTainted(sizeV)) { reportBug(VLA_Tainted, SE, nullptr, C); @@ -123,7 +123,7 @@ void VLASizeChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const { reportBug(VLA_Zero, SE, stateZero, C); return; } - + // From this point on, assume that the size is not zero. state = stateNotZero; diff --git a/clang/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp index f6ef4aef5c7..55025030261 100644 --- a/clang/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file defines a checker that checks virtual function calls during +// This file defines a checker that checks virtual function calls during // construction or destruction of C++ objects. // //===----------------------------------------------------------------------===// @@ -37,13 +37,13 @@ class WalkAST : public StmtVisitor<WalkAST> { /// A vector representing the worklist which has a chain of CallExprs. DFSWorkList WList; - + // PreVisited : A CallExpr to this FunctionDecl is in the worklist, but the // body has not been visited yet. // PostVisited : A CallExpr to this FunctionDecl is in the worklist, and the // body has been visited. enum Kind { NotVisited, - PreVisited, /**< A CallExpr to this FunctionDecl is in the + PreVisited, /**< A CallExpr to this FunctionDecl is in the worklist, but the body has not yet been visited. */ PostVisited /**< A CallExpr to this FunctionDecl is in the @@ -57,7 +57,7 @@ class WalkAST : public StmtVisitor<WalkAST> { /// generating bug reports. This is null while visiting the body of a /// constructor or destructor. const CallExpr *visitingCallExpr; - + public: WalkAST(const CheckerBase *checker, BugReporter &br, AnalysisDeclContext *ac) @@ -70,7 +70,7 @@ public: void Enqueue(WorkListUnit WLUnit) { const FunctionDecl *FD = WLUnit->getDirectCallee(); if (!FD || !FD->getBody()) - return; + return; Kind &K = VisitedFunctions[FD]; if (K != NotVisited) return; @@ -81,9 +81,9 @@ public: /// This method returns an item from the worklist without removing it. WorkListUnit Dequeue() { assert(!WList.empty()); - return WList.back(); + return WList.back(); } - + void Execute() { while (hasWork()) { WorkListUnit WLUnit = Dequeue(); @@ -95,7 +95,7 @@ public: // Visit the body. SaveAndRestore<const CallExpr *> SaveCall(visitingCallExpr, WLUnit); Visit(FD->getBody()); - + // Mark the function as being PostVisited to indicate we have // scanned the body. VisitedFunctions[FD] = PostVisited; @@ -114,7 +114,7 @@ public: void VisitCXXMemberCallExpr(CallExpr *CE); void VisitStmt(Stmt *S) { VisitChildren(S); } void VisitChildren(Stmt *S); - + void ReportVirtualCall(const CallExpr *CE, bool isPure); }; @@ -138,7 +138,7 @@ void WalkAST::VisitCallExpr(CallExpr *CE) { void WalkAST::VisitCXXMemberCallExpr(CallExpr *CE) { VisitChildren(CE); bool callIsNonVirtual = false; - + // Several situations to elide for checking. if (MemberExpr *CME = dyn_cast<MemberExpr>(CE->getCallee())) { // If the member access is fully qualified (i.e., X::F), then treat @@ -170,7 +170,7 @@ void WalkAST::VisitCXXMemberCallExpr(CallExpr *CE) { void WalkAST::ReportVirtualCall(const CallExpr *CE, bool isPure) { SmallString<100> buf; llvm::raw_svector_ostream os(buf); - + os << "Call Path : "; // Name of current visiting CallExpr. os << *CE->getDirectCallee(); @@ -190,7 +190,7 @@ void WalkAST::ReportVirtualCall(const CallExpr *CE, bool isPure) { PathDiagnosticLocation CELoc = PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); SourceRange R = CE->getCallee()->getSourceRange(); - + if (isPure) { os << "\n" << "Call pure virtual functions during construction or " << "destruction may leads undefined behaviour"; |