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