1 //= ProgramState.cpp - Path-Sensitive "State" for tracking values --*- C++ -*--=
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements ProgramState and ProgramStateManager.
11 //===----------------------------------------------------------------------===//
13 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
14 #include "clang/Analysis/CFG.h"
15 #include "clang/Basic/JsonSupport.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
21 #include "llvm/Support/raw_ostream.h"
23 using namespace clang;
26 namespace clang { namespace ento {
27 /// Increments the number of times this state is referenced.
29 void ProgramStateRetain(const ProgramState *state) {
30 ++const_cast<ProgramState*>(state)->refCount;
33 /// Decrement the number of times this state is referenced.
34 void ProgramStateRelease(const ProgramState *state) {
35 assert(state->refCount > 0);
36 ProgramState *s = const_cast<ProgramState*>(state);
37 if (--s->refCount == 0) {
38 ProgramStateManager &Mgr = s->getStateManager();
39 Mgr.StateSet.RemoveNode(s);
41 Mgr.freeStates.push_back(s);
46 ProgramState::ProgramState(ProgramStateManager *mgr, const Environment& env,
47 StoreRef st, GenericDataMap gdm)
53 stateMgr->getStoreManager().incrementReferenceCount(store);
56 ProgramState::ProgramState(const ProgramState &RHS)
57 : llvm::FoldingSetNode(),
58 stateMgr(RHS.stateMgr),
63 stateMgr->getStoreManager().incrementReferenceCount(store);
66 ProgramState::~ProgramState() {
68 stateMgr->getStoreManager().decrementReferenceCount(store);
71 int64_t ProgramState::getID() const {
72 return getStateManager().Alloc.identifyKnownAlignedObject<ProgramState>(this);
75 ProgramStateManager::ProgramStateManager(ASTContext &Ctx,
76 StoreManagerCreator CreateSMgr,
77 ConstraintManagerCreator CreateCMgr,
78 llvm::BumpPtrAllocator &alloc,
80 : Eng(SubEng), EnvMgr(alloc), GDMFactory(alloc),
81 svalBuilder(createSimpleSValBuilder(alloc, Ctx, *this)),
82 CallEventMgr(new CallEventManager(alloc)), Alloc(alloc) {
83 StoreMgr = (*CreateSMgr)(*this);
84 ConstraintMgr = (*CreateCMgr)(*this, SubEng);
88 ProgramStateManager::~ProgramStateManager() {
89 for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
91 I->second.second(I->second.first);
95 ProgramStateManager::removeDeadBindings(ProgramStateRef state,
96 const StackFrameContext *LCtx,
97 SymbolReaper& SymReaper) {
99 // This code essentially performs a "mark-and-sweep" of the VariableBindings.
100 // The roots are any Block-level exprs and Decls that our liveness algorithm
101 // tells us are live. We then see what Decls they may reference, and keep
102 // those around. This code more than likely can be made faster, and the
103 // frequency of which this method is called should be experimented with
104 // for optimum performance.
105 ProgramState NewState = *state;
107 NewState.Env = EnvMgr.removeDeadBindings(NewState.Env, SymReaper, state);
109 // Clean up the store.
110 StoreRef newStore = StoreMgr->removeDeadBindings(NewState.getStore(), LCtx,
112 NewState.setStore(newStore);
113 SymReaper.setReapedStore(newStore);
115 ProgramStateRef Result = getPersistentState(NewState);
116 return ConstraintMgr->removeDeadBindings(Result, SymReaper);
119 ProgramStateRef ProgramState::bindLoc(Loc LV,
121 const LocationContext *LCtx,
122 bool notifyChanges) const {
123 ProgramStateManager &Mgr = getStateManager();
124 ProgramStateRef newState = makeWithStore(Mgr.StoreMgr->Bind(getStore(),
126 const MemRegion *MR = LV.getAsRegion();
127 if (MR && notifyChanges)
128 return Mgr.getOwningEngine().processRegionChange(newState, MR, LCtx);
134 ProgramState::bindDefaultInitial(SVal loc, SVal V,
135 const LocationContext *LCtx) const {
136 ProgramStateManager &Mgr = getStateManager();
137 const MemRegion *R = loc.castAs<loc::MemRegionVal>().getRegion();
138 const StoreRef &newStore = Mgr.StoreMgr->BindDefaultInitial(getStore(), R, V);
139 ProgramStateRef new_state = makeWithStore(newStore);
140 return Mgr.getOwningEngine().processRegionChange(new_state, R, LCtx);
144 ProgramState::bindDefaultZero(SVal loc, const LocationContext *LCtx) const {
145 ProgramStateManager &Mgr = getStateManager();
146 const MemRegion *R = loc.castAs<loc::MemRegionVal>().getRegion();
147 const StoreRef &newStore = Mgr.StoreMgr->BindDefaultZero(getStore(), R);
148 ProgramStateRef new_state = makeWithStore(newStore);
149 return Mgr.getOwningEngine().processRegionChange(new_state, R, LCtx);
152 typedef ArrayRef<const MemRegion *> RegionList;
153 typedef ArrayRef<SVal> ValueList;
156 ProgramState::invalidateRegions(RegionList Regions,
157 const Expr *E, unsigned Count,
158 const LocationContext *LCtx,
159 bool CausedByPointerEscape,
160 InvalidatedSymbols *IS,
161 const CallEvent *Call,
162 RegionAndSymbolInvalidationTraits *ITraits) const {
163 SmallVector<SVal, 8> Values;
164 for (RegionList::const_iterator I = Regions.begin(),
165 End = Regions.end(); I != End; ++I)
166 Values.push_back(loc::MemRegionVal(*I));
168 return invalidateRegionsImpl(Values, E, Count, LCtx, CausedByPointerEscape,
173 ProgramState::invalidateRegions(ValueList Values,
174 const Expr *E, unsigned Count,
175 const LocationContext *LCtx,
176 bool CausedByPointerEscape,
177 InvalidatedSymbols *IS,
178 const CallEvent *Call,
179 RegionAndSymbolInvalidationTraits *ITraits) const {
181 return invalidateRegionsImpl(Values, E, Count, LCtx, CausedByPointerEscape,
186 ProgramState::invalidateRegionsImpl(ValueList Values,
187 const Expr *E, unsigned Count,
188 const LocationContext *LCtx,
189 bool CausedByPointerEscape,
190 InvalidatedSymbols *IS,
191 RegionAndSymbolInvalidationTraits *ITraits,
192 const CallEvent *Call) const {
193 ProgramStateManager &Mgr = getStateManager();
194 SubEngine &Eng = Mgr.getOwningEngine();
196 InvalidatedSymbols InvalidatedSyms;
198 IS = &InvalidatedSyms;
200 RegionAndSymbolInvalidationTraits ITraitsLocal;
202 ITraits = &ITraitsLocal;
204 StoreManager::InvalidatedRegions TopLevelInvalidated;
205 StoreManager::InvalidatedRegions Invalidated;
206 const StoreRef &newStore
207 = Mgr.StoreMgr->invalidateRegions(getStore(), Values, E, Count, LCtx, Call,
208 *IS, *ITraits, &TopLevelInvalidated,
211 ProgramStateRef newState = makeWithStore(newStore);
213 if (CausedByPointerEscape) {
214 newState = Eng.notifyCheckersOfPointerEscape(newState, IS,
220 return Eng.processRegionChanges(newState, IS, TopLevelInvalidated,
221 Invalidated, LCtx, Call);
224 ProgramStateRef ProgramState::killBinding(Loc LV) const {
225 assert(!LV.getAs<loc::MemRegionVal>() && "Use invalidateRegion instead.");
227 Store OldStore = getStore();
228 const StoreRef &newStore =
229 getStateManager().StoreMgr->killBinding(OldStore, LV);
231 if (newStore.getStore() == OldStore)
234 return makeWithStore(newStore);
238 ProgramState::enterStackFrame(const CallEvent &Call,
239 const StackFrameContext *CalleeCtx) const {
240 const StoreRef &NewStore =
241 getStateManager().StoreMgr->enterStackFrame(getStore(), Call, CalleeCtx);
242 return makeWithStore(NewStore);
245 SVal ProgramState::getSValAsScalarOrLoc(const MemRegion *R) const {
246 // We only want to do fetches from regions that we can actually bind
247 // values. For example, SymbolicRegions of type 'id<...>' cannot
248 // have direct bindings (but their can be bindings on their subregions).
249 if (!R->isBoundable())
252 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
253 QualType T = TR->getValueType();
254 if (Loc::isLocType(T) || T->isIntegralOrEnumerationType())
261 SVal ProgramState::getSVal(Loc location, QualType T) const {
262 SVal V = getRawSVal(location, T);
264 // If 'V' is a symbolic value that is *perfectly* constrained to
265 // be a constant value, use that value instead to lessen the burden
266 // on later analysis stages (so we have less symbolic values to reason
268 // We only go into this branch if we can convert the APSInt value we have
269 // to the type of T, which is not always the case (e.g. for void).
270 if (!T.isNull() && (T->isIntegralOrEnumerationType() || Loc::isLocType(T))) {
271 if (SymbolRef sym = V.getAsSymbol()) {
272 if (const llvm::APSInt *Int = getStateManager()
273 .getConstraintManager()
274 .getSymVal(this, sym)) {
275 // FIXME: Because we don't correctly model (yet) sign-extension
276 // and truncation of symbolic values, we need to convert
277 // the integer value to the correct signedness and bitwidth.
279 // This shows up in the following:
282 // unsigned x = foo();
286 // The symbolic value stored to 'x' is actually the conjured
287 // symbol for the call to foo(); the type of that symbol is 'char',
289 const llvm::APSInt &NewV = getBasicVals().Convert(T, *Int);
292 return loc::ConcreteInt(NewV);
294 return nonloc::ConcreteInt(NewV);
302 ProgramStateRef ProgramState::BindExpr(const Stmt *S,
303 const LocationContext *LCtx,
304 SVal V, bool Invalidate) const{
306 getStateManager().EnvMgr.bindExpr(Env, EnvironmentEntry(S, LCtx), V,
311 ProgramState NewSt = *this;
313 return getStateManager().getPersistentState(NewSt);
316 ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
317 DefinedOrUnknownSVal UpperBound,
319 QualType indexTy) const {
320 if (Idx.isUnknown() || UpperBound.isUnknown())
323 // Build an expression for 0 <= Idx < UpperBound.
324 // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed.
325 // FIXME: This should probably be part of SValBuilder.
326 ProgramStateManager &SM = getStateManager();
327 SValBuilder &svalBuilder = SM.getSValBuilder();
328 ASTContext &Ctx = svalBuilder.getContext();
330 // Get the offset: the minimum value of the array index type.
331 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
332 if (indexTy.isNull())
333 indexTy = svalBuilder.getArrayIndexType();
334 nonloc::ConcreteInt Min(BVF.getMinValue(indexTy));
337 SVal newIdx = svalBuilder.evalBinOpNN(this, BO_Add,
338 Idx.castAs<NonLoc>(), Min, indexTy);
339 if (newIdx.isUnknownOrUndef())
342 // Adjust the upper bound.
344 svalBuilder.evalBinOpNN(this, BO_Add, UpperBound.castAs<NonLoc>(),
347 if (newBound.isUnknownOrUndef())
350 // Build the actual comparison.
351 SVal inBound = svalBuilder.evalBinOpNN(this, BO_LT, newIdx.castAs<NonLoc>(),
352 newBound.castAs<NonLoc>(), Ctx.IntTy);
353 if (inBound.isUnknownOrUndef())
356 // Finally, let the constraint manager take care of it.
357 ConstraintManager &CM = SM.getConstraintManager();
358 return CM.assume(this, inBound.castAs<DefinedSVal>(), Assumption);
361 ConditionTruthVal ProgramState::isNonNull(SVal V) const {
362 ConditionTruthVal IsNull = isNull(V);
363 if (IsNull.isUnderconstrained())
365 return ConditionTruthVal(!IsNull.getValue());
368 ConditionTruthVal ProgramState::areEqual(SVal Lhs, SVal Rhs) const {
369 return stateMgr->getSValBuilder().areEqual(this, Lhs, Rhs);
372 ConditionTruthVal ProgramState::isNull(SVal V) const {
373 if (V.isZeroConstant())
379 SymbolRef Sym = V.getAsSymbol(/* IncludeBaseRegion */ true);
381 return ConditionTruthVal();
383 return getStateManager().ConstraintMgr->isNull(this, Sym);
386 ProgramStateRef ProgramStateManager::getInitialState(const LocationContext *InitLoc) {
387 ProgramState State(this,
388 EnvMgr.getInitialEnvironment(),
389 StoreMgr->getInitialStore(InitLoc),
390 GDMFactory.getEmptyMap());
392 return getPersistentState(State);
395 ProgramStateRef ProgramStateManager::getPersistentStateWithGDM(
396 ProgramStateRef FromState,
397 ProgramStateRef GDMState) {
398 ProgramState NewState(*FromState);
399 NewState.GDM = GDMState->GDM;
400 return getPersistentState(NewState);
403 ProgramStateRef ProgramStateManager::getPersistentState(ProgramState &State) {
405 llvm::FoldingSetNodeID ID;
409 if (ProgramState *I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
412 ProgramState *newState = nullptr;
413 if (!freeStates.empty()) {
414 newState = freeStates.back();
415 freeStates.pop_back();
418 newState = (ProgramState*) Alloc.Allocate<ProgramState>();
420 new (newState) ProgramState(State);
421 StateSet.InsertNode(newState, InsertPos);
425 ProgramStateRef ProgramState::makeWithStore(const StoreRef &store) const {
426 ProgramState NewSt(*this);
427 NewSt.setStore(store);
428 return getStateManager().getPersistentState(NewSt);
431 void ProgramState::setStore(const StoreRef &newStore) {
432 Store newStoreStore = newStore.getStore();
434 stateMgr->getStoreManager().incrementReferenceCount(newStoreStore);
436 stateMgr->getStoreManager().decrementReferenceCount(store);
437 store = newStoreStore;
440 //===----------------------------------------------------------------------===//
441 // State pretty-printing.
442 //===----------------------------------------------------------------------===//
444 void ProgramState::printJson(raw_ostream &Out, const LocationContext *LCtx,
445 const char *NL, unsigned int Space,
447 Indent(Out, Space, IsDot) << "\"program_state\": {" << NL;
450 ProgramStateManager &Mgr = getStateManager();
453 Mgr.getStoreManager().printJson(Out, getStore(), NL, Space, IsDot);
455 // Print out the environment.
456 Env.printJson(Out, Mgr.getContext(), LCtx, NL, Space, IsDot);
458 // Print out the constraints.
459 Mgr.getConstraintManager().printJson(Out, this, NL, Space, IsDot);
461 // Print out the tracked dynamic types.
462 printDynamicTypeInfoJson(Out, this, NL, Space, IsDot);
464 // Print checker-specific data.
465 Mgr.getOwningEngine().printJson(Out, this, LCtx, NL, Space, IsDot);
468 Indent(Out, Space, IsDot) << '}';
471 void ProgramState::printDOT(raw_ostream &Out, const LocationContext *LCtx,
472 unsigned int Space) const {
473 printJson(Out, LCtx, /*NL=*/"\\l", Space, /*IsDot=*/true);
476 LLVM_DUMP_METHOD void ProgramState::dump() const {
477 printJson(llvm::errs());
480 AnalysisManager& ProgramState::getAnalysisManager() const {
481 return stateMgr->getOwningEngine().getAnalysisManager();
484 //===----------------------------------------------------------------------===//
486 //===----------------------------------------------------------------------===//
488 void *const* ProgramState::FindGDM(void *K) const {
489 return GDM.lookup(K);
493 ProgramStateManager::FindGDMContext(void *K,
494 void *(*CreateContext)(llvm::BumpPtrAllocator&),
495 void (*DeleteContext)(void*)) {
497 std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
499 p.first = CreateContext(Alloc);
500 p.second = DeleteContext;
506 ProgramStateRef ProgramStateManager::addGDM(ProgramStateRef St, void *Key, void *Data){
507 ProgramState::GenericDataMap M1 = St->getGDM();
508 ProgramState::GenericDataMap M2 = GDMFactory.add(M1, Key, Data);
513 ProgramState NewSt = *St;
515 return getPersistentState(NewSt);
518 ProgramStateRef ProgramStateManager::removeGDM(ProgramStateRef state, void *Key) {
519 ProgramState::GenericDataMap OldM = state->getGDM();
520 ProgramState::GenericDataMap NewM = GDMFactory.remove(OldM, Key);
525 ProgramState NewState = *state;
527 return getPersistentState(NewState);
530 bool ScanReachableSymbols::scan(nonloc::LazyCompoundVal val) {
531 bool wasVisited = !visited.insert(val.getCVData()).second;
535 StoreManager &StoreMgr = state->getStateManager().getStoreManager();
536 // FIXME: We don't really want to use getBaseRegion() here because pointer
537 // arithmetic doesn't apply, but scanReachableSymbols only accepts base
538 // regions right now.
539 const MemRegion *R = val.getRegion()->getBaseRegion();
540 return StoreMgr.scanReachableSymbols(val.getStore(), R, *this);
543 bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
544 for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
551 bool ScanReachableSymbols::scan(const SymExpr *sym) {
552 for (SymExpr::symbol_iterator SI = sym->symbol_begin(),
553 SE = sym->symbol_end();
555 bool wasVisited = !visited.insert(*SI).second;
559 if (!visitor.VisitSymbol(*SI))
566 bool ScanReachableSymbols::scan(SVal val) {
567 if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>())
568 return scan(X->getRegion());
570 if (Optional<nonloc::LazyCompoundVal> X =
571 val.getAs<nonloc::LazyCompoundVal>())
574 if (Optional<nonloc::LocAsInteger> X = val.getAs<nonloc::LocAsInteger>())
575 return scan(X->getLoc());
577 if (SymbolRef Sym = val.getAsSymbol())
580 if (const SymExpr *Sym = val.getAsSymbolicExpression())
583 if (Optional<nonloc::CompoundVal> X = val.getAs<nonloc::CompoundVal>())
589 bool ScanReachableSymbols::scan(const MemRegion *R) {
590 if (isa<MemSpaceRegion>(R))
593 bool wasVisited = !visited.insert(R).second;
597 if (!visitor.VisitMemRegion(R))
600 // If this is a symbolic region, visit the symbol for the region.
601 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
602 if (!visitor.VisitSymbol(SR->getSymbol()))
605 // If this is a subregion, also visit the parent regions.
606 if (const SubRegion *SR = dyn_cast<SubRegion>(R)) {
607 const MemRegion *Super = SR->getSuperRegion();
611 // When we reach the topmost region, scan all symbols in it.
612 if (isa<MemSpaceRegion>(Super)) {
613 StoreManager &StoreMgr = state->getStateManager().getStoreManager();
614 if (!StoreMgr.scanReachableSymbols(state->getStore(), SR, *this))
619 // Regions captured by a block are also implicitly reachable.
620 if (const BlockDataRegion *BDR = dyn_cast<BlockDataRegion>(R)) {
621 BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
622 E = BDR->referenced_vars_end();
623 for ( ; I != E; ++I) {
624 if (!scan(I.getCapturedRegion()))
632 bool ProgramState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const {
633 ScanReachableSymbols S(this, visitor);
637 bool ProgramState::scanReachableSymbols(
638 llvm::iterator_range<region_iterator> Reachable,
639 SymbolVisitor &visitor) const {
640 ScanReachableSymbols S(this, visitor);
641 for (const MemRegion *R : Reachable) {