ProgramState.cpp revision 56a46b51df691f857f7120aaf2d4deeff0b014de
1//= ProgramState.cpp - Path-Sensitive "State" for tracking values --*- C++ -*--= 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements ProgramState and ProgramStateManager. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Analysis/CFG.h" 15#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 16#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 17#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 18#include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h" 19#include "clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h" 20#include "llvm/Support/raw_ostream.h" 21 22using namespace clang; 23using namespace ento; 24 25// Give the vtable for ConstraintManager somewhere to live. 26// FIXME: Move this elsewhere. 27ConstraintManager::~ConstraintManager() {} 28 29namespace clang { namespace ento { 30/// Increments the number of times this state is referenced. 31 32void ProgramStateRetain(const ProgramState *state) { 33 ++const_cast<ProgramState*>(state)->refCount; 34} 35 36/// Decrement the number of times this state is referenced. 37void ProgramStateRelease(const ProgramState *state) { 38 assert(state->refCount > 0); 39 ProgramState *s = const_cast<ProgramState*>(state); 40 if (--s->refCount == 0) { 41 ProgramStateManager &Mgr = s->getStateManager(); 42 Mgr.StateSet.RemoveNode(s); 43 s->~ProgramState(); 44 Mgr.freeStates.push_back(s); 45 } 46} 47}} 48 49ProgramState::ProgramState(ProgramStateManager *mgr, const Environment& env, 50 StoreRef st, GenericDataMap gdm) 51 : stateMgr(mgr), 52 Env(env), 53 store(st.getStore()), 54 GDM(gdm), 55 refCount(0) { 56 stateMgr->getStoreManager().incrementReferenceCount(store); 57} 58 59ProgramState::ProgramState(const ProgramState &RHS) 60 : llvm::FoldingSetNode(), 61 stateMgr(RHS.stateMgr), 62 Env(RHS.Env), 63 store(RHS.store), 64 GDM(RHS.GDM), 65 refCount(0) { 66 stateMgr->getStoreManager().incrementReferenceCount(store); 67} 68 69ProgramState::~ProgramState() { 70 if (store) 71 stateMgr->getStoreManager().decrementReferenceCount(store); 72} 73 74ProgramStateManager::ProgramStateManager(ASTContext &Ctx, 75 StoreManagerCreator CreateSMgr, 76 ConstraintManagerCreator CreateCMgr, 77 llvm::BumpPtrAllocator &alloc, 78 SubEngine &SubEng) 79 : Eng(&SubEng), EnvMgr(alloc), GDMFactory(alloc), 80 svalBuilder(createSimpleSValBuilder(alloc, Ctx, *this)), 81 CallEventMgr(new CallEventManager(alloc)), Alloc(alloc) { 82 StoreMgr.reset((*CreateSMgr)(*this)); 83 ConstraintMgr.reset((*CreateCMgr)(*this, SubEng)); 84} 85 86 87ProgramStateManager::~ProgramStateManager() { 88 for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end(); 89 I!=E; ++I) 90 I->second.second(I->second.first); 91} 92 93ProgramStateRef 94ProgramStateManager::removeDeadBindings(ProgramStateRef state, 95 const StackFrameContext *LCtx, 96 SymbolReaper& SymReaper) { 97 98 // This code essentially performs a "mark-and-sweep" of the VariableBindings. 99 // The roots are any Block-level exprs and Decls that our liveness algorithm 100 // tells us are live. We then see what Decls they may reference, and keep 101 // those around. This code more than likely can be made faster, and the 102 // frequency of which this method is called should be experimented with 103 // for optimum performance. 104 ProgramState NewState = *state; 105 106 NewState.Env = EnvMgr.removeDeadBindings(NewState.Env, SymReaper, state); 107 108 // Clean up the store. 109 StoreRef newStore = StoreMgr->removeDeadBindings(NewState.getStore(), LCtx, 110 SymReaper); 111 NewState.setStore(newStore); 112 SymReaper.setReapedStore(newStore); 113 114 return getPersistentState(NewState); 115} 116 117ProgramStateRef ProgramStateManager::MarshalState(ProgramStateRef state, 118 const StackFrameContext *InitLoc) { 119 // make up an empty state for now. 120 ProgramState State(this, 121 EnvMgr.getInitialEnvironment(), 122 StoreMgr->getInitialStore(InitLoc), 123 GDMFactory.getEmptyMap()); 124 125 return getPersistentState(State); 126} 127 128ProgramStateRef ProgramState::bindCompoundLiteral(const CompoundLiteralExpr *CL, 129 const LocationContext *LC, 130 SVal V) const { 131 const StoreRef &newStore = 132 getStateManager().StoreMgr->bindCompoundLiteral(getStore(), CL, LC, V); 133 return makeWithStore(newStore); 134} 135 136ProgramStateRef ProgramState::bindLoc(Loc LV, SVal V, bool notifyChanges) const { 137 ProgramStateManager &Mgr = getStateManager(); 138 ProgramStateRef newState = makeWithStore(Mgr.StoreMgr->Bind(getStore(), 139 LV, V)); 140 const MemRegion *MR = LV.getAsRegion(); 141 if (MR && Mgr.getOwningEngine() && notifyChanges) 142 return Mgr.getOwningEngine()->processRegionChange(newState, MR); 143 144 return newState; 145} 146 147ProgramStateRef ProgramState::bindDefault(SVal loc, SVal V) const { 148 ProgramStateManager &Mgr = getStateManager(); 149 const MemRegion *R = cast<loc::MemRegionVal>(loc).getRegion(); 150 const StoreRef &newStore = Mgr.StoreMgr->BindDefault(getStore(), R, V); 151 ProgramStateRef new_state = makeWithStore(newStore); 152 return Mgr.getOwningEngine() ? 153 Mgr.getOwningEngine()->processRegionChange(new_state, R) : 154 new_state; 155} 156 157ProgramStateRef 158ProgramState::invalidateRegions(ArrayRef<const MemRegion *> Regions, 159 const Expr *E, unsigned Count, 160 const LocationContext *LCtx, 161 StoreManager::InvalidatedSymbols *IS, 162 const CallEvent *Call) const { 163 if (!IS) { 164 StoreManager::InvalidatedSymbols invalidated; 165 return invalidateRegionsImpl(Regions, E, Count, LCtx, 166 invalidated, Call); 167 } 168 return invalidateRegionsImpl(Regions, E, Count, LCtx, *IS, Call); 169} 170 171ProgramStateRef 172ProgramState::invalidateRegionsImpl(ArrayRef<const MemRegion *> Regions, 173 const Expr *E, unsigned Count, 174 const LocationContext *LCtx, 175 StoreManager::InvalidatedSymbols &IS, 176 const CallEvent *Call) const { 177 ProgramStateManager &Mgr = getStateManager(); 178 SubEngine* Eng = Mgr.getOwningEngine(); 179 180 if (Eng && Eng->wantsRegionChangeUpdate(this)) { 181 StoreManager::InvalidatedRegions Invalidated; 182 const StoreRef &newStore 183 = Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, LCtx, IS, 184 Call, &Invalidated); 185 ProgramStateRef newState = makeWithStore(newStore); 186 return Eng->processRegionChanges(newState, &IS, Regions, Invalidated, Call); 187 } 188 189 const StoreRef &newStore = 190 Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, LCtx, IS, 191 Call, NULL); 192 return makeWithStore(newStore); 193} 194 195ProgramStateRef ProgramState::killBinding(Loc LV) const { 196 assert(!isa<loc::MemRegionVal>(LV) && "Use invalidateRegion instead."); 197 198 Store OldStore = getStore(); 199 const StoreRef &newStore = 200 getStateManager().StoreMgr->killBinding(OldStore, LV); 201 202 if (newStore.getStore() == OldStore) 203 return this; 204 205 return makeWithStore(newStore); 206} 207 208ProgramStateRef 209ProgramState::enterStackFrame(const CallEvent &Call, 210 const StackFrameContext *CalleeCtx) const { 211 const StoreRef &NewStore = 212 getStateManager().StoreMgr->enterStackFrame(getStore(), Call, CalleeCtx); 213 return makeWithStore(NewStore); 214} 215 216SVal ProgramState::getSValAsScalarOrLoc(const MemRegion *R) const { 217 // We only want to do fetches from regions that we can actually bind 218 // values. For example, SymbolicRegions of type 'id<...>' cannot 219 // have direct bindings (but their can be bindings on their subregions). 220 if (!R->isBoundable()) 221 return UnknownVal(); 222 223 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) { 224 QualType T = TR->getValueType(); 225 if (Loc::isLocType(T) || T->isIntegerType()) 226 return getSVal(R); 227 } 228 229 return UnknownVal(); 230} 231 232SVal ProgramState::getSVal(Loc location, QualType T) const { 233 SVal V = getRawSVal(cast<Loc>(location), T); 234 235 // If 'V' is a symbolic value that is *perfectly* constrained to 236 // be a constant value, use that value instead to lessen the burden 237 // on later analysis stages (so we have less symbolic values to reason 238 // about). 239 if (!T.isNull()) { 240 if (SymbolRef sym = V.getAsSymbol()) { 241 if (const llvm::APSInt *Int = getSymVal(sym)) { 242 // FIXME: Because we don't correctly model (yet) sign-extension 243 // and truncation of symbolic values, we need to convert 244 // the integer value to the correct signedness and bitwidth. 245 // 246 // This shows up in the following: 247 // 248 // char foo(); 249 // unsigned x = foo(); 250 // if (x == 54) 251 // ... 252 // 253 // The symbolic value stored to 'x' is actually the conjured 254 // symbol for the call to foo(); the type of that symbol is 'char', 255 // not unsigned. 256 const llvm::APSInt &NewV = getBasicVals().Convert(T, *Int); 257 258 if (isa<Loc>(V)) 259 return loc::ConcreteInt(NewV); 260 else 261 return nonloc::ConcreteInt(NewV); 262 } 263 } 264 } 265 266 return V; 267} 268 269ProgramStateRef ProgramState::BindExpr(const Stmt *S, 270 const LocationContext *LCtx, 271 SVal V, bool Invalidate) const{ 272 Environment NewEnv = 273 getStateManager().EnvMgr.bindExpr(Env, EnvironmentEntry(S, LCtx), V, 274 Invalidate); 275 if (NewEnv == Env) 276 return this; 277 278 ProgramState NewSt = *this; 279 NewSt.Env = NewEnv; 280 return getStateManager().getPersistentState(NewSt); 281} 282 283ProgramStateRef 284ProgramState::bindExprAndLocation(const Stmt *S, const LocationContext *LCtx, 285 SVal location, 286 SVal V) const { 287 Environment NewEnv = 288 getStateManager().EnvMgr.bindExprAndLocation(Env, 289 EnvironmentEntry(S, LCtx), 290 location, V); 291 292 if (NewEnv == Env) 293 return this; 294 295 ProgramState NewSt = *this; 296 NewSt.Env = NewEnv; 297 return getStateManager().getPersistentState(NewSt); 298} 299 300ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx, 301 DefinedOrUnknownSVal UpperBound, 302 bool Assumption, 303 QualType indexTy) const { 304 if (Idx.isUnknown() || UpperBound.isUnknown()) 305 return this; 306 307 // Build an expression for 0 <= Idx < UpperBound. 308 // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed. 309 // FIXME: This should probably be part of SValBuilder. 310 ProgramStateManager &SM = getStateManager(); 311 SValBuilder &svalBuilder = SM.getSValBuilder(); 312 ASTContext &Ctx = svalBuilder.getContext(); 313 314 // Get the offset: the minimum value of the array index type. 315 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory(); 316 // FIXME: This should be using ValueManager::ArrayindexTy...somehow. 317 if (indexTy.isNull()) 318 indexTy = Ctx.IntTy; 319 nonloc::ConcreteInt Min(BVF.getMinValue(indexTy)); 320 321 // Adjust the index. 322 SVal newIdx = svalBuilder.evalBinOpNN(this, BO_Add, 323 cast<NonLoc>(Idx), Min, indexTy); 324 if (newIdx.isUnknownOrUndef()) 325 return this; 326 327 // Adjust the upper bound. 328 SVal newBound = 329 svalBuilder.evalBinOpNN(this, BO_Add, cast<NonLoc>(UpperBound), 330 Min, indexTy); 331 332 if (newBound.isUnknownOrUndef()) 333 return this; 334 335 // Build the actual comparison. 336 SVal inBound = svalBuilder.evalBinOpNN(this, BO_LT, 337 cast<NonLoc>(newIdx), cast<NonLoc>(newBound), 338 Ctx.IntTy); 339 if (inBound.isUnknownOrUndef()) 340 return this; 341 342 // Finally, let the constraint manager take care of it. 343 ConstraintManager &CM = SM.getConstraintManager(); 344 return CM.assume(this, cast<DefinedSVal>(inBound), Assumption); 345} 346 347ProgramStateRef ProgramStateManager::getInitialState(const LocationContext *InitLoc) { 348 ProgramState State(this, 349 EnvMgr.getInitialEnvironment(), 350 StoreMgr->getInitialStore(InitLoc), 351 GDMFactory.getEmptyMap()); 352 353 return getPersistentState(State); 354} 355 356ProgramStateRef ProgramStateManager::getPersistentStateWithGDM( 357 ProgramStateRef FromState, 358 ProgramStateRef GDMState) { 359 ProgramState NewState(*FromState); 360 NewState.GDM = GDMState->GDM; 361 return getPersistentState(NewState); 362} 363 364ProgramStateRef ProgramStateManager::getPersistentState(ProgramState &State) { 365 366 llvm::FoldingSetNodeID ID; 367 State.Profile(ID); 368 void *InsertPos; 369 370 if (ProgramState *I = StateSet.FindNodeOrInsertPos(ID, InsertPos)) 371 return I; 372 373 ProgramState *newState = 0; 374 if (!freeStates.empty()) { 375 newState = freeStates.back(); 376 freeStates.pop_back(); 377 } 378 else { 379 newState = (ProgramState*) Alloc.Allocate<ProgramState>(); 380 } 381 new (newState) ProgramState(State); 382 StateSet.InsertNode(newState, InsertPos); 383 return newState; 384} 385 386ProgramStateRef ProgramState::makeWithStore(const StoreRef &store) const { 387 ProgramState NewSt(*this); 388 NewSt.setStore(store); 389 return getStateManager().getPersistentState(NewSt); 390} 391 392void ProgramState::setStore(const StoreRef &newStore) { 393 Store newStoreStore = newStore.getStore(); 394 if (newStoreStore) 395 stateMgr->getStoreManager().incrementReferenceCount(newStoreStore); 396 if (store) 397 stateMgr->getStoreManager().decrementReferenceCount(store); 398 store = newStoreStore; 399} 400 401//===----------------------------------------------------------------------===// 402// State pretty-printing. 403//===----------------------------------------------------------------------===// 404 405void ProgramState::print(raw_ostream &Out, 406 const char *NL, const char *Sep) const { 407 // Print the store. 408 ProgramStateManager &Mgr = getStateManager(); 409 Mgr.getStoreManager().print(getStore(), Out, NL, Sep); 410 411 // Print out the environment. 412 Env.print(Out, NL, Sep); 413 414 // Print out the constraints. 415 Mgr.getConstraintManager().print(this, Out, NL, Sep); 416 417 // Print checker-specific data. 418 Mgr.getOwningEngine()->printState(Out, this, NL, Sep); 419} 420 421void ProgramState::printDOT(raw_ostream &Out) const { 422 print(Out, "\\l", "\\|"); 423} 424 425void ProgramState::dump() const { 426 print(llvm::errs()); 427} 428 429void ProgramState::printTaint(raw_ostream &Out, 430 const char *NL, const char *Sep) const { 431 TaintMapImpl TM = get<TaintMap>(); 432 433 if (!TM.isEmpty()) 434 Out <<"Tainted Symbols:" << NL; 435 436 for (TaintMapImpl::iterator I = TM.begin(), E = TM.end(); I != E; ++I) { 437 Out << I->first << " : " << I->second << NL; 438 } 439} 440 441void ProgramState::dumpTaint() const { 442 printTaint(llvm::errs()); 443} 444 445//===----------------------------------------------------------------------===// 446// Generic Data Map. 447//===----------------------------------------------------------------------===// 448 449void *const* ProgramState::FindGDM(void *K) const { 450 return GDM.lookup(K); 451} 452 453void* 454ProgramStateManager::FindGDMContext(void *K, 455 void *(*CreateContext)(llvm::BumpPtrAllocator&), 456 void (*DeleteContext)(void*)) { 457 458 std::pair<void*, void (*)(void*)>& p = GDMContexts[K]; 459 if (!p.first) { 460 p.first = CreateContext(Alloc); 461 p.second = DeleteContext; 462 } 463 464 return p.first; 465} 466 467ProgramStateRef ProgramStateManager::addGDM(ProgramStateRef St, void *Key, void *Data){ 468 ProgramState::GenericDataMap M1 = St->getGDM(); 469 ProgramState::GenericDataMap M2 = GDMFactory.add(M1, Key, Data); 470 471 if (M1 == M2) 472 return St; 473 474 ProgramState NewSt = *St; 475 NewSt.GDM = M2; 476 return getPersistentState(NewSt); 477} 478 479ProgramStateRef ProgramStateManager::removeGDM(ProgramStateRef state, void *Key) { 480 ProgramState::GenericDataMap OldM = state->getGDM(); 481 ProgramState::GenericDataMap NewM = GDMFactory.remove(OldM, Key); 482 483 if (NewM == OldM) 484 return state; 485 486 ProgramState NewState = *state; 487 NewState.GDM = NewM; 488 return getPersistentState(NewState); 489} 490 491bool ScanReachableSymbols::scan(nonloc::CompoundVal val) { 492 for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I) 493 if (!scan(*I)) 494 return false; 495 496 return true; 497} 498 499bool ScanReachableSymbols::scan(const SymExpr *sym) { 500 unsigned &isVisited = visited[sym]; 501 if (isVisited) 502 return true; 503 isVisited = 1; 504 505 if (!visitor.VisitSymbol(sym)) 506 return false; 507 508 // TODO: should be rewritten using SymExpr::symbol_iterator. 509 switch (sym->getKind()) { 510 case SymExpr::RegionValueKind: 511 case SymExpr::ConjuredKind: 512 case SymExpr::DerivedKind: 513 case SymExpr::ExtentKind: 514 case SymExpr::MetadataKind: 515 break; 516 case SymExpr::CastSymbolKind: 517 return scan(cast<SymbolCast>(sym)->getOperand()); 518 case SymExpr::SymIntKind: 519 return scan(cast<SymIntExpr>(sym)->getLHS()); 520 case SymExpr::IntSymKind: 521 return scan(cast<IntSymExpr>(sym)->getRHS()); 522 case SymExpr::SymSymKind: { 523 const SymSymExpr *x = cast<SymSymExpr>(sym); 524 return scan(x->getLHS()) && scan(x->getRHS()); 525 } 526 } 527 return true; 528} 529 530bool ScanReachableSymbols::scan(SVal val) { 531 if (loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&val)) 532 return scan(X->getRegion()); 533 534 if (nonloc::LazyCompoundVal *X = dyn_cast<nonloc::LazyCompoundVal>(&val)) 535 return scan(X->getRegion()); 536 537 if (nonloc::LocAsInteger *X = dyn_cast<nonloc::LocAsInteger>(&val)) 538 return scan(X->getLoc()); 539 540 if (SymbolRef Sym = val.getAsSymbol()) 541 return scan(Sym); 542 543 if (const SymExpr *Sym = val.getAsSymbolicExpression()) 544 return scan(Sym); 545 546 if (nonloc::CompoundVal *X = dyn_cast<nonloc::CompoundVal>(&val)) 547 return scan(*X); 548 549 return true; 550} 551 552bool ScanReachableSymbols::scan(const MemRegion *R) { 553 if (isa<MemSpaceRegion>(R)) 554 return true; 555 556 unsigned &isVisited = visited[R]; 557 if (isVisited) 558 return true; 559 isVisited = 1; 560 561 562 if (!visitor.VisitMemRegion(R)) 563 return false; 564 565 // If this is a symbolic region, visit the symbol for the region. 566 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) 567 if (!visitor.VisitSymbol(SR->getSymbol())) 568 return false; 569 570 // If this is a subregion, also visit the parent regions. 571 if (const SubRegion *SR = dyn_cast<SubRegion>(R)) { 572 const MemRegion *Super = SR->getSuperRegion(); 573 if (!scan(Super)) 574 return false; 575 576 // When we reach the topmost region, scan all symbols in it. 577 if (isa<MemSpaceRegion>(Super)) { 578 StoreManager &StoreMgr = state->getStateManager().getStoreManager(); 579 if (!StoreMgr.scanReachableSymbols(state->getStore(), SR, *this)) 580 return false; 581 } 582 } 583 584 // Regions captured by a block are also implicitly reachable. 585 if (const BlockDataRegion *BDR = dyn_cast<BlockDataRegion>(R)) { 586 BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(), 587 E = BDR->referenced_vars_end(); 588 for ( ; I != E; ++I) { 589 if (!scan(I.getCapturedRegion())) 590 return false; 591 } 592 } 593 594 return true; 595} 596 597bool ProgramState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const { 598 ScanReachableSymbols S(this, visitor); 599 return S.scan(val); 600} 601 602bool ProgramState::scanReachableSymbols(const SVal *I, const SVal *E, 603 SymbolVisitor &visitor) const { 604 ScanReachableSymbols S(this, visitor); 605 for ( ; I != E; ++I) { 606 if (!S.scan(*I)) 607 return false; 608 } 609 return true; 610} 611 612bool ProgramState::scanReachableSymbols(const MemRegion * const *I, 613 const MemRegion * const *E, 614 SymbolVisitor &visitor) const { 615 ScanReachableSymbols S(this, visitor); 616 for ( ; I != E; ++I) { 617 if (!S.scan(*I)) 618 return false; 619 } 620 return true; 621} 622 623ProgramStateRef ProgramState::addTaint(const Stmt *S, 624 const LocationContext *LCtx, 625 TaintTagType Kind) const { 626 if (const Expr *E = dyn_cast_or_null<Expr>(S)) 627 S = E->IgnoreParens(); 628 629 SymbolRef Sym = getSVal(S, LCtx).getAsSymbol(); 630 if (Sym) 631 return addTaint(Sym, Kind); 632 633 const MemRegion *R = getSVal(S, LCtx).getAsRegion(); 634 addTaint(R, Kind); 635 636 // Cannot add taint, so just return the state. 637 return this; 638} 639 640ProgramStateRef ProgramState::addTaint(const MemRegion *R, 641 TaintTagType Kind) const { 642 if (const SymbolicRegion *SR = dyn_cast_or_null<SymbolicRegion>(R)) 643 return addTaint(SR->getSymbol(), Kind); 644 return this; 645} 646 647ProgramStateRef ProgramState::addTaint(SymbolRef Sym, 648 TaintTagType Kind) const { 649 // If this is a symbol cast, remove the cast before adding the taint. Taint 650 // is cast agnostic. 651 while (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym)) 652 Sym = SC->getOperand(); 653 654 ProgramStateRef NewState = set<TaintMap>(Sym, Kind); 655 assert(NewState); 656 return NewState; 657} 658 659bool ProgramState::isTainted(const Stmt *S, const LocationContext *LCtx, 660 TaintTagType Kind) const { 661 if (const Expr *E = dyn_cast_or_null<Expr>(S)) 662 S = E->IgnoreParens(); 663 664 SVal val = getSVal(S, LCtx); 665 return isTainted(val, Kind); 666} 667 668bool ProgramState::isTainted(SVal V, TaintTagType Kind) const { 669 if (const SymExpr *Sym = V.getAsSymExpr()) 670 return isTainted(Sym, Kind); 671 if (const MemRegion *Reg = V.getAsRegion()) 672 return isTainted(Reg, Kind); 673 return false; 674} 675 676bool ProgramState::isTainted(const MemRegion *Reg, TaintTagType K) const { 677 if (!Reg) 678 return false; 679 680 // Element region (array element) is tainted if either the base or the offset 681 // are tainted. 682 if (const ElementRegion *ER = dyn_cast<ElementRegion>(Reg)) 683 return isTainted(ER->getSuperRegion(), K) || isTainted(ER->getIndex(), K); 684 685 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(Reg)) 686 return isTainted(SR->getSymbol(), K); 687 688 if (const SubRegion *ER = dyn_cast<SubRegion>(Reg)) 689 return isTainted(ER->getSuperRegion(), K); 690 691 return false; 692} 693 694bool ProgramState::isTainted(SymbolRef Sym, TaintTagType Kind) const { 695 if (!Sym) 696 return false; 697 698 // Traverse all the symbols this symbol depends on to see if any are tainted. 699 bool Tainted = false; 700 for (SymExpr::symbol_iterator SI = Sym->symbol_begin(), SE =Sym->symbol_end(); 701 SI != SE; ++SI) { 702 assert(isa<SymbolData>(*SI)); 703 const TaintTagType *Tag = get<TaintMap>(*SI); 704 Tainted = (Tag && *Tag == Kind); 705 706 // If this is a SymbolDerived with a tainted parent, it's also tainted. 707 if (const SymbolDerived *SD = dyn_cast<SymbolDerived>(*SI)) 708 Tainted = Tainted || isTainted(SD->getParentSymbol(), Kind); 709 710 // If memory region is tainted, data is also tainted. 711 if (const SymbolRegionValue *SRV = dyn_cast<SymbolRegionValue>(*SI)) 712 Tainted = Tainted || isTainted(SRV->getRegion(), Kind); 713 714 // If If this is a SymbolCast from a tainted value, it's also tainted. 715 if (const SymbolCast *SC = dyn_cast<SymbolCast>(*SI)) 716 Tainted = Tainted || isTainted(SC->getOperand(), Kind); 717 718 if (Tainted) 719 return true; 720 } 721 722 return Tainted; 723} 724 725/// The GDM component containing the dynamic type info. This is a map from a 726/// symbol to it's most likely type. 727namespace clang { 728namespace ento { 729typedef llvm::ImmutableMap<const MemRegion *, DynamicTypeInfo> DynamicTypeMap; 730template<> struct ProgramStateTrait<DynamicTypeMap> 731 : public ProgramStatePartialTrait<DynamicTypeMap> { 732 static void *GDMIndex() { static int index; return &index; } 733}; 734}} 735 736DynamicTypeInfo ProgramState::getDynamicTypeInfo(const MemRegion *Reg) const { 737 Reg = Reg->StripCasts(); 738 739 // Look up the dynamic type in the GDM. 740 const DynamicTypeInfo *GDMType = get<DynamicTypeMap>(Reg); 741 if (GDMType) 742 return *GDMType; 743 744 // Otherwise, fall back to what we know about the region. 745 if (const TypedRegion *TR = dyn_cast<TypedRegion>(Reg)) 746 return DynamicTypeInfo(TR->getLocationType(), /*CanBeSubclass=*/false); 747 748 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(Reg)) { 749 SymbolRef Sym = SR->getSymbol(); 750 return DynamicTypeInfo(Sym->getType(getStateManager().getContext())); 751 } 752 753 return DynamicTypeInfo(); 754} 755 756ProgramStateRef ProgramState::setDynamicTypeInfo(const MemRegion *Reg, 757 DynamicTypeInfo NewTy) const { 758 Reg = Reg->StripCasts(); 759 ProgramStateRef NewState = set<DynamicTypeMap>(Reg, NewTy); 760 assert(NewState); 761 return NewState; 762} 763