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