1 //== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==// 2 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines a basic region store model. In this model, we do have field 10 // sensitivity. But we assume nothing about the heap shape. So recursive data 11 // structures are largely ignored. Basically we do 1-limiting analysis. 12 // Parameter pointers are assumed with no aliasing. Pointee objects of 13 // parameters are created lazily. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/ASTMatchers/ASTMatchFinder.h" 20 #include "clang/Analysis/Analyses/LiveVariables.h" 21 #include "clang/Analysis/AnalysisDeclContext.h" 22 #include "clang/Basic/JsonSupport.h" 23 #include "clang/Basic/TargetInfo.h" 24 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 25 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 26 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 27 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" 28 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 29 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 30 #include "llvm/ADT/ImmutableMap.h" 31 #include "llvm/ADT/Optional.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include <utility> 34 35 using namespace clang; 36 using namespace ento; 37 38 //===----------------------------------------------------------------------===// 39 // Representation of binding keys. 40 //===----------------------------------------------------------------------===// 41 42 namespace { 43 class BindingKey { 44 public: 45 enum Kind { Default = 0x0, Direct = 0x1 }; 46 private: 47 enum { Symbolic = 0x2 }; 48 49 llvm::PointerIntPair<const MemRegion *, 2> P; 50 uint64_t Data; 51 52 /// Create a key for a binding to region \p r, which has a symbolic offset 53 /// from region \p Base. 54 explicit BindingKey(const SubRegion *r, const SubRegion *Base, Kind k) 55 : P(r, k | Symbolic), Data(reinterpret_cast<uintptr_t>(Base)) { 56 assert(r && Base && "Must have known regions."); 57 assert(getConcreteOffsetRegion() == Base && "Failed to store base region"); 58 } 59 60 /// Create a key for a binding at \p offset from base region \p r. 61 explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k) 62 : P(r, k), Data(offset) { 63 assert(r && "Must have known regions."); 64 assert(getOffset() == offset && "Failed to store offset"); 65 assert((r == r->getBaseRegion() || 66 isa<ObjCIvarRegion, CXXDerivedObjectRegion>(r)) && 67 "Not a base"); 68 } 69 public: 70 71 bool isDirect() const { return P.getInt() & Direct; } 72 bool hasSymbolicOffset() const { return P.getInt() & Symbolic; } 73 74 const MemRegion *getRegion() const { return P.getPointer(); } 75 uint64_t getOffset() const { 76 assert(!hasSymbolicOffset()); 77 return Data; 78 } 79 80 const SubRegion *getConcreteOffsetRegion() const { 81 assert(hasSymbolicOffset()); 82 return reinterpret_cast<const SubRegion *>(static_cast<uintptr_t>(Data)); 83 } 84 85 const MemRegion *getBaseRegion() const { 86 if (hasSymbolicOffset()) 87 return getConcreteOffsetRegion()->getBaseRegion(); 88 return getRegion()->getBaseRegion(); 89 } 90 91 void Profile(llvm::FoldingSetNodeID& ID) const { 92 ID.AddPointer(P.getOpaqueValue()); 93 ID.AddInteger(Data); 94 } 95 96 static BindingKey Make(const MemRegion *R, Kind k); 97 98 bool operator<(const BindingKey &X) const { 99 if (P.getOpaqueValue() < X.P.getOpaqueValue()) 100 return true; 101 if (P.getOpaqueValue() > X.P.getOpaqueValue()) 102 return false; 103 return Data < X.Data; 104 } 105 106 bool operator==(const BindingKey &X) const { 107 return P.getOpaqueValue() == X.P.getOpaqueValue() && 108 Data == X.Data; 109 } 110 111 LLVM_DUMP_METHOD void dump() const; 112 }; 113 } // end anonymous namespace 114 115 BindingKey BindingKey::Make(const MemRegion *R, Kind k) { 116 const RegionOffset &RO = R->getAsOffset(); 117 if (RO.hasSymbolicOffset()) 118 return BindingKey(cast<SubRegion>(R), cast<SubRegion>(RO.getRegion()), k); 119 120 return BindingKey(RO.getRegion(), RO.getOffset(), k); 121 } 122 123 namespace llvm { 124 static inline raw_ostream &operator<<(raw_ostream &Out, BindingKey K) { 125 Out << "\"kind\": \"" << (K.isDirect() ? "Direct" : "Default") 126 << "\", \"offset\": "; 127 128 if (!K.hasSymbolicOffset()) 129 Out << K.getOffset(); 130 else 131 Out << "null"; 132 133 return Out; 134 } 135 136 } // namespace llvm 137 138 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 139 void BindingKey::dump() const { llvm::errs() << *this; } 140 #endif 141 142 //===----------------------------------------------------------------------===// 143 // Actual Store type. 144 //===----------------------------------------------------------------------===// 145 146 typedef llvm::ImmutableMap<BindingKey, SVal> ClusterBindings; 147 typedef llvm::ImmutableMapRef<BindingKey, SVal> ClusterBindingsRef; 148 typedef std::pair<BindingKey, SVal> BindingPair; 149 150 typedef llvm::ImmutableMap<const MemRegion *, ClusterBindings> 151 RegionBindings; 152 153 namespace { 154 class RegionBindingsRef : public llvm::ImmutableMapRef<const MemRegion *, 155 ClusterBindings> { 156 ClusterBindings::Factory *CBFactory; 157 158 // This flag indicates whether the current bindings are within the analysis 159 // that has started from main(). It affects how we perform loads from 160 // global variables that have initializers: if we have observed the 161 // program execution from the start and we know that these variables 162 // have not been overwritten yet, we can be sure that their initializers 163 // are still relevant. This flag never gets changed when the bindings are 164 // updated, so it could potentially be moved into RegionStoreManager 165 // (as if it's the same bindings but a different loading procedure) 166 // however that would have made the manager needlessly stateful. 167 bool IsMainAnalysis; 168 169 public: 170 typedef llvm::ImmutableMapRef<const MemRegion *, ClusterBindings> 171 ParentTy; 172 173 RegionBindingsRef(ClusterBindings::Factory &CBFactory, 174 const RegionBindings::TreeTy *T, 175 RegionBindings::TreeTy::Factory *F, 176 bool IsMainAnalysis) 177 : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(T, F), 178 CBFactory(&CBFactory), IsMainAnalysis(IsMainAnalysis) {} 179 180 RegionBindingsRef(const ParentTy &P, 181 ClusterBindings::Factory &CBFactory, 182 bool IsMainAnalysis) 183 : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(P), 184 CBFactory(&CBFactory), IsMainAnalysis(IsMainAnalysis) {} 185 186 RegionBindingsRef add(key_type_ref K, data_type_ref D) const { 187 return RegionBindingsRef(static_cast<const ParentTy *>(this)->add(K, D), 188 *CBFactory, IsMainAnalysis); 189 } 190 191 RegionBindingsRef remove(key_type_ref K) const { 192 return RegionBindingsRef(static_cast<const ParentTy *>(this)->remove(K), 193 *CBFactory, IsMainAnalysis); 194 } 195 196 RegionBindingsRef addBinding(BindingKey K, SVal V) const; 197 198 RegionBindingsRef addBinding(const MemRegion *R, 199 BindingKey::Kind k, SVal V) const; 200 201 const SVal *lookup(BindingKey K) const; 202 const SVal *lookup(const MemRegion *R, BindingKey::Kind k) const; 203 using llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>::lookup; 204 205 RegionBindingsRef removeBinding(BindingKey K); 206 207 RegionBindingsRef removeBinding(const MemRegion *R, 208 BindingKey::Kind k); 209 210 RegionBindingsRef removeBinding(const MemRegion *R) { 211 return removeBinding(R, BindingKey::Direct). 212 removeBinding(R, BindingKey::Default); 213 } 214 215 Optional<SVal> getDirectBinding(const MemRegion *R) const; 216 217 /// getDefaultBinding - Returns an SVal* representing an optional default 218 /// binding associated with a region and its subregions. 219 Optional<SVal> getDefaultBinding(const MemRegion *R) const; 220 221 /// Return the internal tree as a Store. 222 Store asStore() const { 223 llvm::PointerIntPair<Store, 1, bool> Ptr = { 224 asImmutableMap().getRootWithoutRetain(), IsMainAnalysis}; 225 return reinterpret_cast<Store>(Ptr.getOpaqueValue()); 226 } 227 228 bool isMainAnalysis() const { 229 return IsMainAnalysis; 230 } 231 232 void printJson(raw_ostream &Out, const char *NL = "\n", 233 unsigned int Space = 0, bool IsDot = false) const { 234 for (iterator I = begin(); I != end(); ++I) { 235 // TODO: We might need a .printJson for I.getKey() as well. 236 Indent(Out, Space, IsDot) 237 << "{ \"cluster\": \"" << I.getKey() << "\", \"pointer\": \"" 238 << (const void *)I.getKey() << "\", \"items\": [" << NL; 239 240 ++Space; 241 const ClusterBindings &CB = I.getData(); 242 for (ClusterBindings::iterator CI = CB.begin(); CI != CB.end(); ++CI) { 243 Indent(Out, Space, IsDot) << "{ " << CI.getKey() << ", \"value\": "; 244 CI.getData().printJson(Out, /*AddQuotes=*/true); 245 Out << " }"; 246 if (std::next(CI) != CB.end()) 247 Out << ','; 248 Out << NL; 249 } 250 251 --Space; 252 Indent(Out, Space, IsDot) << "]}"; 253 if (std::next(I) != end()) 254 Out << ','; 255 Out << NL; 256 } 257 } 258 259 LLVM_DUMP_METHOD void dump() const { printJson(llvm::errs()); } 260 }; 261 } // end anonymous namespace 262 263 typedef const RegionBindingsRef& RegionBindingsConstRef; 264 265 Optional<SVal> RegionBindingsRef::getDirectBinding(const MemRegion *R) const { 266 return Optional<SVal>::create(lookup(R, BindingKey::Direct)); 267 } 268 269 Optional<SVal> RegionBindingsRef::getDefaultBinding(const MemRegion *R) const { 270 return Optional<SVal>::create(lookup(R, BindingKey::Default)); 271 } 272 273 RegionBindingsRef RegionBindingsRef::addBinding(BindingKey K, SVal V) const { 274 const MemRegion *Base = K.getBaseRegion(); 275 276 const ClusterBindings *ExistingCluster = lookup(Base); 277 ClusterBindings Cluster = 278 (ExistingCluster ? *ExistingCluster : CBFactory->getEmptyMap()); 279 280 ClusterBindings NewCluster = CBFactory->add(Cluster, K, V); 281 return add(Base, NewCluster); 282 } 283 284 285 RegionBindingsRef RegionBindingsRef::addBinding(const MemRegion *R, 286 BindingKey::Kind k, 287 SVal V) const { 288 return addBinding(BindingKey::Make(R, k), V); 289 } 290 291 const SVal *RegionBindingsRef::lookup(BindingKey K) const { 292 const ClusterBindings *Cluster = lookup(K.getBaseRegion()); 293 if (!Cluster) 294 return nullptr; 295 return Cluster->lookup(K); 296 } 297 298 const SVal *RegionBindingsRef::lookup(const MemRegion *R, 299 BindingKey::Kind k) const { 300 return lookup(BindingKey::Make(R, k)); 301 } 302 303 RegionBindingsRef RegionBindingsRef::removeBinding(BindingKey K) { 304 const MemRegion *Base = K.getBaseRegion(); 305 const ClusterBindings *Cluster = lookup(Base); 306 if (!Cluster) 307 return *this; 308 309 ClusterBindings NewCluster = CBFactory->remove(*Cluster, K); 310 if (NewCluster.isEmpty()) 311 return remove(Base); 312 return add(Base, NewCluster); 313 } 314 315 RegionBindingsRef RegionBindingsRef::removeBinding(const MemRegion *R, 316 BindingKey::Kind k){ 317 return removeBinding(BindingKey::Make(R, k)); 318 } 319 320 //===----------------------------------------------------------------------===// 321 // Fine-grained control of RegionStoreManager. 322 //===----------------------------------------------------------------------===// 323 324 namespace { 325 struct minimal_features_tag {}; 326 struct maximal_features_tag {}; 327 328 class RegionStoreFeatures { 329 bool SupportsFields; 330 public: 331 RegionStoreFeatures(minimal_features_tag) : 332 SupportsFields(false) {} 333 334 RegionStoreFeatures(maximal_features_tag) : 335 SupportsFields(true) {} 336 337 void enableFields(bool t) { SupportsFields = t; } 338 339 bool supportsFields() const { return SupportsFields; } 340 }; 341 } 342 343 //===----------------------------------------------------------------------===// 344 // Main RegionStore logic. 345 //===----------------------------------------------------------------------===// 346 347 namespace { 348 class InvalidateRegionsWorker; 349 350 class RegionStoreManager : public StoreManager { 351 public: 352 const RegionStoreFeatures Features; 353 354 RegionBindings::Factory RBFactory; 355 mutable ClusterBindings::Factory CBFactory; 356 357 typedef std::vector<SVal> SValListTy; 358 private: 359 typedef llvm::DenseMap<const LazyCompoundValData *, 360 SValListTy> LazyBindingsMapTy; 361 LazyBindingsMapTy LazyBindingsMap; 362 363 /// The largest number of fields a struct can have and still be 364 /// considered "small". 365 /// 366 /// This is currently used to decide whether or not it is worth "forcing" a 367 /// LazyCompoundVal on bind. 368 /// 369 /// This is controlled by 'region-store-small-struct-limit' option. 370 /// To disable all small-struct-dependent behavior, set the option to "0". 371 unsigned SmallStructLimit; 372 373 /// A helper used to populate the work list with the given set of 374 /// regions. 375 void populateWorkList(InvalidateRegionsWorker &W, 376 ArrayRef<SVal> Values, 377 InvalidatedRegions *TopLevelRegions); 378 379 public: 380 RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f) 381 : StoreManager(mgr), Features(f), 382 RBFactory(mgr.getAllocator()), CBFactory(mgr.getAllocator()), 383 SmallStructLimit(0) { 384 ExprEngine &Eng = StateMgr.getOwningEngine(); 385 AnalyzerOptions &Options = Eng.getAnalysisManager().options; 386 SmallStructLimit = Options.RegionStoreSmallStructLimit; 387 } 388 389 390 /// setImplicitDefaultValue - Set the default binding for the provided 391 /// MemRegion to the value implicitly defined for compound literals when 392 /// the value is not specified. 393 RegionBindingsRef setImplicitDefaultValue(RegionBindingsConstRef B, 394 const MemRegion *R, QualType T); 395 396 /// ArrayToPointer - Emulates the "decay" of an array to a pointer 397 /// type. 'Array' represents the lvalue of the array being decayed 398 /// to a pointer, and the returned SVal represents the decayed 399 /// version of that lvalue (i.e., a pointer to the first element of 400 /// the array). This is called by ExprEngine when evaluating 401 /// casts from arrays to pointers. 402 SVal ArrayToPointer(Loc Array, QualType ElementTy) override; 403 404 /// Creates the Store that correctly represents memory contents before 405 /// the beginning of the analysis of the given top-level stack frame. 406 StoreRef getInitialStore(const LocationContext *InitLoc) override { 407 bool IsMainAnalysis = false; 408 if (const auto *FD = dyn_cast<FunctionDecl>(InitLoc->getDecl())) 409 IsMainAnalysis = FD->isMain() && !Ctx.getLangOpts().CPlusPlus; 410 return StoreRef(RegionBindingsRef( 411 RegionBindingsRef::ParentTy(RBFactory.getEmptyMap(), RBFactory), 412 CBFactory, IsMainAnalysis).asStore(), *this); 413 } 414 415 //===-------------------------------------------------------------------===// 416 // Binding values to regions. 417 //===-------------------------------------------------------------------===// 418 RegionBindingsRef invalidateGlobalRegion(MemRegion::Kind K, 419 const Expr *Ex, 420 unsigned Count, 421 const LocationContext *LCtx, 422 RegionBindingsRef B, 423 InvalidatedRegions *Invalidated); 424 425 StoreRef invalidateRegions(Store store, 426 ArrayRef<SVal> Values, 427 const Expr *E, unsigned Count, 428 const LocationContext *LCtx, 429 const CallEvent *Call, 430 InvalidatedSymbols &IS, 431 RegionAndSymbolInvalidationTraits &ITraits, 432 InvalidatedRegions *Invalidated, 433 InvalidatedRegions *InvalidatedTopLevel) override; 434 435 bool scanReachableSymbols(Store S, const MemRegion *R, 436 ScanReachableSymbols &Callbacks) override; 437 438 RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B, 439 const SubRegion *R); 440 Optional<SVal> getConstantValFromConstArrayInitializer( 441 RegionBindingsConstRef B, const VarRegion *VR, const ElementRegion *R); 442 Optional<SVal> getSValFromInitListExpr(const InitListExpr *ILE, 443 uint64_t Offset, QualType ElemT); 444 SVal getSValFromStringLiteral(const StringLiteral *SL, uint64_t Offset, 445 QualType ElemT); 446 447 public: // Part of public interface to class. 448 449 StoreRef Bind(Store store, Loc LV, SVal V) override { 450 return StoreRef(bind(getRegionBindings(store), LV, V).asStore(), *this); 451 } 452 453 RegionBindingsRef bind(RegionBindingsConstRef B, Loc LV, SVal V); 454 455 // BindDefaultInitial is only used to initialize a region with 456 // a default value. 457 StoreRef BindDefaultInitial(Store store, const MemRegion *R, 458 SVal V) override { 459 RegionBindingsRef B = getRegionBindings(store); 460 // Use other APIs when you have to wipe the region that was initialized 461 // earlier. 462 assert(!(B.getDefaultBinding(R) || B.getDirectBinding(R)) && 463 "Double initialization!"); 464 B = B.addBinding(BindingKey::Make(R, BindingKey::Default), V); 465 return StoreRef(B.asImmutableMap().getRootWithoutRetain(), *this); 466 } 467 468 // BindDefaultZero is used for zeroing constructors that may accidentally 469 // overwrite existing bindings. 470 StoreRef BindDefaultZero(Store store, const MemRegion *R) override { 471 // FIXME: The offsets of empty bases can be tricky because of 472 // of the so called "empty base class optimization". 473 // If a base class has been optimized out 474 // we should not try to create a binding, otherwise we should. 475 // Unfortunately, at the moment ASTRecordLayout doesn't expose 476 // the actual sizes of the empty bases 477 // and trying to infer them from offsets/alignments 478 // seems to be error-prone and non-trivial because of the trailing padding. 479 // As a temporary mitigation we don't create bindings for empty bases. 480 if (const auto *BR = dyn_cast<CXXBaseObjectRegion>(R)) 481 if (BR->getDecl()->isEmpty()) 482 return StoreRef(store, *this); 483 484 RegionBindingsRef B = getRegionBindings(store); 485 SVal V = svalBuilder.makeZeroVal(Ctx.CharTy); 486 B = removeSubRegionBindings(B, cast<SubRegion>(R)); 487 B = B.addBinding(BindingKey::Make(R, BindingKey::Default), V); 488 return StoreRef(B.asImmutableMap().getRootWithoutRetain(), *this); 489 } 490 491 /// Attempt to extract the fields of \p LCV and bind them to the struct region 492 /// \p R. 493 /// 494 /// This path is used when it seems advantageous to "force" loading the values 495 /// within a LazyCompoundVal to bind memberwise to the struct region, rather 496 /// than using a Default binding at the base of the entire region. This is a 497 /// heuristic attempting to avoid building long chains of LazyCompoundVals. 498 /// 499 /// \returns The updated store bindings, or \c None if binding non-lazily 500 /// would be too expensive. 501 Optional<RegionBindingsRef> tryBindSmallStruct(RegionBindingsConstRef B, 502 const TypedValueRegion *R, 503 const RecordDecl *RD, 504 nonloc::LazyCompoundVal LCV); 505 506 /// BindStruct - Bind a compound value to a structure. 507 RegionBindingsRef bindStruct(RegionBindingsConstRef B, 508 const TypedValueRegion* R, SVal V); 509 510 /// BindVector - Bind a compound value to a vector. 511 RegionBindingsRef bindVector(RegionBindingsConstRef B, 512 const TypedValueRegion* R, SVal V); 513 514 RegionBindingsRef bindArray(RegionBindingsConstRef B, 515 const TypedValueRegion* R, 516 SVal V); 517 518 /// Clears out all bindings in the given region and assigns a new value 519 /// as a Default binding. 520 RegionBindingsRef bindAggregate(RegionBindingsConstRef B, 521 const TypedRegion *R, 522 SVal DefaultVal); 523 524 /// Create a new store with the specified binding removed. 525 /// \param ST the original store, that is the basis for the new store. 526 /// \param L the location whose binding should be removed. 527 StoreRef killBinding(Store ST, Loc L) override; 528 529 void incrementReferenceCount(Store store) override { 530 getRegionBindings(store).manualRetain(); 531 } 532 533 /// If the StoreManager supports it, decrement the reference count of 534 /// the specified Store object. If the reference count hits 0, the memory 535 /// associated with the object is recycled. 536 void decrementReferenceCount(Store store) override { 537 getRegionBindings(store).manualRelease(); 538 } 539 540 bool includedInBindings(Store store, const MemRegion *region) const override; 541 542 /// Return the value bound to specified location in a given state. 543 /// 544 /// The high level logic for this method is this: 545 /// getBinding (L) 546 /// if L has binding 547 /// return L's binding 548 /// else if L is in killset 549 /// return unknown 550 /// else 551 /// if L is on stack or heap 552 /// return undefined 553 /// else 554 /// return symbolic 555 SVal getBinding(Store S, Loc L, QualType T) override { 556 return getBinding(getRegionBindings(S), L, T); 557 } 558 559 Optional<SVal> getDefaultBinding(Store S, const MemRegion *R) override { 560 RegionBindingsRef B = getRegionBindings(S); 561 // Default bindings are always applied over a base region so look up the 562 // base region's default binding, otherwise the lookup will fail when R 563 // is at an offset from R->getBaseRegion(). 564 return B.getDefaultBinding(R->getBaseRegion()); 565 } 566 567 SVal getBinding(RegionBindingsConstRef B, Loc L, QualType T = QualType()); 568 569 SVal getBindingForElement(RegionBindingsConstRef B, const ElementRegion *R); 570 571 SVal getBindingForField(RegionBindingsConstRef B, const FieldRegion *R); 572 573 SVal getBindingForObjCIvar(RegionBindingsConstRef B, const ObjCIvarRegion *R); 574 575 SVal getBindingForVar(RegionBindingsConstRef B, const VarRegion *R); 576 577 SVal getBindingForLazySymbol(const TypedValueRegion *R); 578 579 SVal getBindingForFieldOrElementCommon(RegionBindingsConstRef B, 580 const TypedValueRegion *R, 581 QualType Ty); 582 583 SVal getLazyBinding(const SubRegion *LazyBindingRegion, 584 RegionBindingsRef LazyBinding); 585 586 /// Get bindings for the values in a struct and return a CompoundVal, used 587 /// when doing struct copy: 588 /// struct s x, y; 589 /// x = y; 590 /// y's value is retrieved by this method. 591 SVal getBindingForStruct(RegionBindingsConstRef B, const TypedValueRegion *R); 592 SVal getBindingForArray(RegionBindingsConstRef B, const TypedValueRegion *R); 593 NonLoc createLazyBinding(RegionBindingsConstRef B, const TypedValueRegion *R); 594 595 /// Used to lazily generate derived symbols for bindings that are defined 596 /// implicitly by default bindings in a super region. 597 /// 598 /// Note that callers may need to specially handle LazyCompoundVals, which 599 /// are returned as is in case the caller needs to treat them differently. 600 Optional<SVal> getBindingForDerivedDefaultValue(RegionBindingsConstRef B, 601 const MemRegion *superR, 602 const TypedValueRegion *R, 603 QualType Ty); 604 605 /// Get the state and region whose binding this region \p R corresponds to. 606 /// 607 /// If there is no lazy binding for \p R, the returned value will have a null 608 /// \c second. Note that a null pointer can represents a valid Store. 609 std::pair<Store, const SubRegion *> 610 findLazyBinding(RegionBindingsConstRef B, const SubRegion *R, 611 const SubRegion *originalRegion); 612 613 /// Returns the cached set of interesting SVals contained within a lazy 614 /// binding. 615 /// 616 /// The precise value of "interesting" is determined for the purposes of 617 /// RegionStore's internal analysis. It must always contain all regions and 618 /// symbols, but may omit constants and other kinds of SVal. 619 const SValListTy &getInterestingValues(nonloc::LazyCompoundVal LCV); 620 621 //===------------------------------------------------------------------===// 622 // State pruning. 623 //===------------------------------------------------------------------===// 624 625 /// removeDeadBindings - Scans the RegionStore of 'state' for dead values. 626 /// It returns a new Store with these values removed. 627 StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx, 628 SymbolReaper& SymReaper) override; 629 630 //===------------------------------------------------------------------===// 631 // Utility methods. 632 //===------------------------------------------------------------------===// 633 634 RegionBindingsRef getRegionBindings(Store store) const { 635 llvm::PointerIntPair<Store, 1, bool> Ptr; 636 Ptr.setFromOpaqueValue(const_cast<void *>(store)); 637 return RegionBindingsRef( 638 CBFactory, 639 static_cast<const RegionBindings::TreeTy *>(Ptr.getPointer()), 640 RBFactory.getTreeFactory(), 641 Ptr.getInt()); 642 } 643 644 void printJson(raw_ostream &Out, Store S, const char *NL = "\n", 645 unsigned int Space = 0, bool IsDot = false) const override; 646 647 void iterBindings(Store store, BindingsHandler& f) override { 648 RegionBindingsRef B = getRegionBindings(store); 649 for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) { 650 const ClusterBindings &Cluster = I.getData(); 651 for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end(); 652 CI != CE; ++CI) { 653 const BindingKey &K = CI.getKey(); 654 if (!K.isDirect()) 655 continue; 656 if (const SubRegion *R = dyn_cast<SubRegion>(K.getRegion())) { 657 // FIXME: Possibly incorporate the offset? 658 if (!f.HandleBinding(*this, store, R, CI.getData())) 659 return; 660 } 661 } 662 } 663 } 664 }; 665 666 } // end anonymous namespace 667 668 //===----------------------------------------------------------------------===// 669 // RegionStore creation. 670 //===----------------------------------------------------------------------===// 671 672 std::unique_ptr<StoreManager> 673 ento::CreateRegionStoreManager(ProgramStateManager &StMgr) { 674 RegionStoreFeatures F = maximal_features_tag(); 675 return std::make_unique<RegionStoreManager>(StMgr, F); 676 } 677 678 std::unique_ptr<StoreManager> 679 ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) { 680 RegionStoreFeatures F = minimal_features_tag(); 681 F.enableFields(true); 682 return std::make_unique<RegionStoreManager>(StMgr, F); 683 } 684 685 686 //===----------------------------------------------------------------------===// 687 // Region Cluster analysis. 688 //===----------------------------------------------------------------------===// 689 690 namespace { 691 /// Used to determine which global regions are automatically included in the 692 /// initial worklist of a ClusterAnalysis. 693 enum GlobalsFilterKind { 694 /// Don't include any global regions. 695 GFK_None, 696 /// Only include system globals. 697 GFK_SystemOnly, 698 /// Include all global regions. 699 GFK_All 700 }; 701 702 template <typename DERIVED> 703 class ClusterAnalysis { 704 protected: 705 typedef llvm::DenseMap<const MemRegion *, const ClusterBindings *> ClusterMap; 706 typedef const MemRegion * WorkListElement; 707 typedef SmallVector<WorkListElement, 10> WorkList; 708 709 llvm::SmallPtrSet<const ClusterBindings *, 16> Visited; 710 711 WorkList WL; 712 713 RegionStoreManager &RM; 714 ASTContext &Ctx; 715 SValBuilder &svalBuilder; 716 717 RegionBindingsRef B; 718 719 720 protected: 721 const ClusterBindings *getCluster(const MemRegion *R) { 722 return B.lookup(R); 723 } 724 725 /// Returns true if all clusters in the given memspace should be initially 726 /// included in the cluster analysis. Subclasses may provide their 727 /// own implementation. 728 bool includeEntireMemorySpace(const MemRegion *Base) { 729 return false; 730 } 731 732 public: 733 ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr, 734 RegionBindingsRef b) 735 : RM(rm), Ctx(StateMgr.getContext()), 736 svalBuilder(StateMgr.getSValBuilder()), B(std::move(b)) {} 737 738 RegionBindingsRef getRegionBindings() const { return B; } 739 740 bool isVisited(const MemRegion *R) { 741 return Visited.count(getCluster(R)); 742 } 743 744 void GenerateClusters() { 745 // Scan the entire set of bindings and record the region clusters. 746 for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); 747 RI != RE; ++RI){ 748 const MemRegion *Base = RI.getKey(); 749 750 const ClusterBindings &Cluster = RI.getData(); 751 assert(!Cluster.isEmpty() && "Empty clusters should be removed"); 752 static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster); 753 754 // If the base's memspace should be entirely invalidated, add the cluster 755 // to the workspace up front. 756 if (static_cast<DERIVED*>(this)->includeEntireMemorySpace(Base)) 757 AddToWorkList(WorkListElement(Base), &Cluster); 758 } 759 } 760 761 bool AddToWorkList(WorkListElement E, const ClusterBindings *C) { 762 if (C && !Visited.insert(C).second) 763 return false; 764 WL.push_back(E); 765 return true; 766 } 767 768 bool AddToWorkList(const MemRegion *R) { 769 return static_cast<DERIVED*>(this)->AddToWorkList(R); 770 } 771 772 void RunWorkList() { 773 while (!WL.empty()) { 774 WorkListElement E = WL.pop_back_val(); 775 const MemRegion *BaseR = E; 776 777 static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR)); 778 } 779 } 780 781 void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) {} 782 void VisitCluster(const MemRegion *baseR, const ClusterBindings *C) {} 783 784 void VisitCluster(const MemRegion *BaseR, const ClusterBindings *C, 785 bool Flag) { 786 static_cast<DERIVED*>(this)->VisitCluster(BaseR, C); 787 } 788 }; 789 } 790 791 //===----------------------------------------------------------------------===// 792 // Binding invalidation. 793 //===----------------------------------------------------------------------===// 794 795 bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R, 796 ScanReachableSymbols &Callbacks) { 797 assert(R == R->getBaseRegion() && "Should only be called for base regions"); 798 RegionBindingsRef B = getRegionBindings(S); 799 const ClusterBindings *Cluster = B.lookup(R); 800 801 if (!Cluster) 802 return true; 803 804 for (ClusterBindings::iterator RI = Cluster->begin(), RE = Cluster->end(); 805 RI != RE; ++RI) { 806 if (!Callbacks.scan(RI.getData())) 807 return false; 808 } 809 810 return true; 811 } 812 813 static inline bool isUnionField(const FieldRegion *FR) { 814 return FR->getDecl()->getParent()->isUnion(); 815 } 816 817 typedef SmallVector<const FieldDecl *, 8> FieldVector; 818 819 static void getSymbolicOffsetFields(BindingKey K, FieldVector &Fields) { 820 assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys"); 821 822 const MemRegion *Base = K.getConcreteOffsetRegion(); 823 const MemRegion *R = K.getRegion(); 824 825 while (R != Base) { 826 if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) 827 if (!isUnionField(FR)) 828 Fields.push_back(FR->getDecl()); 829 830 R = cast<SubRegion>(R)->getSuperRegion(); 831 } 832 } 833 834 static bool isCompatibleWithFields(BindingKey K, const FieldVector &Fields) { 835 assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys"); 836 837 if (Fields.empty()) 838 return true; 839 840 FieldVector FieldsInBindingKey; 841 getSymbolicOffsetFields(K, FieldsInBindingKey); 842 843 ptrdiff_t Delta = FieldsInBindingKey.size() - Fields.size(); 844 if (Delta >= 0) 845 return std::equal(FieldsInBindingKey.begin() + Delta, 846 FieldsInBindingKey.end(), 847 Fields.begin()); 848 else 849 return std::equal(FieldsInBindingKey.begin(), FieldsInBindingKey.end(), 850 Fields.begin() - Delta); 851 } 852 853 /// Collects all bindings in \p Cluster that may refer to bindings within 854 /// \p Top. 855 /// 856 /// Each binding is a pair whose \c first is the key (a BindingKey) and whose 857 /// \c second is the value (an SVal). 858 /// 859 /// The \p IncludeAllDefaultBindings parameter specifies whether to include 860 /// default bindings that may extend beyond \p Top itself, e.g. if \p Top is 861 /// an aggregate within a larger aggregate with a default binding. 862 static void 863 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings, 864 SValBuilder &SVB, const ClusterBindings &Cluster, 865 const SubRegion *Top, BindingKey TopKey, 866 bool IncludeAllDefaultBindings) { 867 FieldVector FieldsInSymbolicSubregions; 868 if (TopKey.hasSymbolicOffset()) { 869 getSymbolicOffsetFields(TopKey, FieldsInSymbolicSubregions); 870 Top = TopKey.getConcreteOffsetRegion(); 871 TopKey = BindingKey::Make(Top, BindingKey::Default); 872 } 873 874 // Find the length (in bits) of the region being invalidated. 875 uint64_t Length = UINT64_MAX; 876 SVal Extent = Top->getMemRegionManager().getStaticSize(Top, SVB); 877 if (Optional<nonloc::ConcreteInt> ExtentCI = 878 Extent.getAs<nonloc::ConcreteInt>()) { 879 const llvm::APSInt &ExtentInt = ExtentCI->getValue(); 880 assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned()); 881 // Extents are in bytes but region offsets are in bits. Be careful! 882 Length = ExtentInt.getLimitedValue() * SVB.getContext().getCharWidth(); 883 } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(Top)) { 884 if (FR->getDecl()->isBitField()) 885 Length = FR->getDecl()->getBitWidthValue(SVB.getContext()); 886 } 887 888 for (ClusterBindings::iterator I = Cluster.begin(), E = Cluster.end(); 889 I != E; ++I) { 890 BindingKey NextKey = I.getKey(); 891 if (NextKey.getRegion() == TopKey.getRegion()) { 892 // FIXME: This doesn't catch the case where we're really invalidating a 893 // region with a symbolic offset. Example: 894 // R: points[i].y 895 // Next: points[0].x 896 897 if (NextKey.getOffset() > TopKey.getOffset() && 898 NextKey.getOffset() - TopKey.getOffset() < Length) { 899 // Case 1: The next binding is inside the region we're invalidating. 900 // Include it. 901 Bindings.push_back(*I); 902 903 } else if (NextKey.getOffset() == TopKey.getOffset()) { 904 // Case 2: The next binding is at the same offset as the region we're 905 // invalidating. In this case, we need to leave default bindings alone, 906 // since they may be providing a default value for a regions beyond what 907 // we're invalidating. 908 // FIXME: This is probably incorrect; consider invalidating an outer 909 // struct whose first field is bound to a LazyCompoundVal. 910 if (IncludeAllDefaultBindings || NextKey.isDirect()) 911 Bindings.push_back(*I); 912 } 913 914 } else if (NextKey.hasSymbolicOffset()) { 915 const MemRegion *Base = NextKey.getConcreteOffsetRegion(); 916 if (Top->isSubRegionOf(Base) && Top != Base) { 917 // Case 3: The next key is symbolic and we just changed something within 918 // its concrete region. We don't know if the binding is still valid, so 919 // we'll be conservative and include it. 920 if (IncludeAllDefaultBindings || NextKey.isDirect()) 921 if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions)) 922 Bindings.push_back(*I); 923 } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) { 924 // Case 4: The next key is symbolic, but we changed a known 925 // super-region. In this case the binding is certainly included. 926 if (BaseSR->isSubRegionOf(Top)) 927 if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions)) 928 Bindings.push_back(*I); 929 } 930 } 931 } 932 } 933 934 static void 935 collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings, 936 SValBuilder &SVB, const ClusterBindings &Cluster, 937 const SubRegion *Top, bool IncludeAllDefaultBindings) { 938 collectSubRegionBindings(Bindings, SVB, Cluster, Top, 939 BindingKey::Make(Top, BindingKey::Default), 940 IncludeAllDefaultBindings); 941 } 942 943 RegionBindingsRef 944 RegionStoreManager::removeSubRegionBindings(RegionBindingsConstRef B, 945 const SubRegion *Top) { 946 BindingKey TopKey = BindingKey::Make(Top, BindingKey::Default); 947 const MemRegion *ClusterHead = TopKey.getBaseRegion(); 948 949 if (Top == ClusterHead) { 950 // We can remove an entire cluster's bindings all in one go. 951 return B.remove(Top); 952 } 953 954 const ClusterBindings *Cluster = B.lookup(ClusterHead); 955 if (!Cluster) { 956 // If we're invalidating a region with a symbolic offset, we need to make 957 // sure we don't treat the base region as uninitialized anymore. 958 if (TopKey.hasSymbolicOffset()) { 959 const SubRegion *Concrete = TopKey.getConcreteOffsetRegion(); 960 return B.addBinding(Concrete, BindingKey::Default, UnknownVal()); 961 } 962 return B; 963 } 964 965 SmallVector<BindingPair, 32> Bindings; 966 collectSubRegionBindings(Bindings, svalBuilder, *Cluster, Top, TopKey, 967 /*IncludeAllDefaultBindings=*/false); 968 969 ClusterBindingsRef Result(*Cluster, CBFactory); 970 for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(), 971 E = Bindings.end(); 972 I != E; ++I) 973 Result = Result.remove(I->first); 974 975 // If we're invalidating a region with a symbolic offset, we need to make sure 976 // we don't treat the base region as uninitialized anymore. 977 // FIXME: This isn't very precise; see the example in 978 // collectSubRegionBindings. 979 if (TopKey.hasSymbolicOffset()) { 980 const SubRegion *Concrete = TopKey.getConcreteOffsetRegion(); 981 Result = Result.add(BindingKey::Make(Concrete, BindingKey::Default), 982 UnknownVal()); 983 } 984 985 if (Result.isEmpty()) 986 return B.remove(ClusterHead); 987 return B.add(ClusterHead, Result.asImmutableMap()); 988 } 989 990 namespace { 991 class InvalidateRegionsWorker : public ClusterAnalysis<InvalidateRegionsWorker> 992 { 993 const Expr *Ex; 994 unsigned Count; 995 const LocationContext *LCtx; 996 InvalidatedSymbols &IS; 997 RegionAndSymbolInvalidationTraits &ITraits; 998 StoreManager::InvalidatedRegions *Regions; 999 GlobalsFilterKind GlobalsFilter; 1000 public: 1001 InvalidateRegionsWorker(RegionStoreManager &rm, 1002 ProgramStateManager &stateMgr, 1003 RegionBindingsRef b, 1004 const Expr *ex, unsigned count, 1005 const LocationContext *lctx, 1006 InvalidatedSymbols &is, 1007 RegionAndSymbolInvalidationTraits &ITraitsIn, 1008 StoreManager::InvalidatedRegions *r, 1009 GlobalsFilterKind GFK) 1010 : ClusterAnalysis<InvalidateRegionsWorker>(rm, stateMgr, b), 1011 Ex(ex), Count(count), LCtx(lctx), IS(is), ITraits(ITraitsIn), Regions(r), 1012 GlobalsFilter(GFK) {} 1013 1014 void VisitCluster(const MemRegion *baseR, const ClusterBindings *C); 1015 void VisitBinding(SVal V); 1016 1017 using ClusterAnalysis::AddToWorkList; 1018 1019 bool AddToWorkList(const MemRegion *R); 1020 1021 /// Returns true if all clusters in the memory space for \p Base should be 1022 /// be invalidated. 1023 bool includeEntireMemorySpace(const MemRegion *Base); 1024 1025 /// Returns true if the memory space of the given region is one of the global 1026 /// regions specially included at the start of invalidation. 1027 bool isInitiallyIncludedGlobalRegion(const MemRegion *R); 1028 }; 1029 } 1030 1031 bool InvalidateRegionsWorker::AddToWorkList(const MemRegion *R) { 1032 bool doNotInvalidateSuperRegion = ITraits.hasTrait( 1033 R, RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion); 1034 const MemRegion *BaseR = doNotInvalidateSuperRegion ? R : R->getBaseRegion(); 1035 return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR)); 1036 } 1037 1038 void InvalidateRegionsWorker::VisitBinding(SVal V) { 1039 // A symbol? Mark it touched by the invalidation. 1040 if (SymbolRef Sym = V.getAsSymbol()) 1041 IS.insert(Sym); 1042 1043 if (const MemRegion *R = V.getAsRegion()) { 1044 AddToWorkList(R); 1045 return; 1046 } 1047 1048 // Is it a LazyCompoundVal? All references get invalidated as well. 1049 if (Optional<nonloc::LazyCompoundVal> LCS = 1050 V.getAs<nonloc::LazyCompoundVal>()) { 1051 1052 const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS); 1053 1054 for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(), 1055 E = Vals.end(); 1056 I != E; ++I) 1057 VisitBinding(*I); 1058 1059 return; 1060 } 1061 } 1062 1063 void InvalidateRegionsWorker::VisitCluster(const MemRegion *baseR, 1064 const ClusterBindings *C) { 1065 1066 bool PreserveRegionsContents = 1067 ITraits.hasTrait(baseR, 1068 RegionAndSymbolInvalidationTraits::TK_PreserveContents); 1069 1070 if (C) { 1071 for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I) 1072 VisitBinding(I.getData()); 1073 1074 // Invalidate regions contents. 1075 if (!PreserveRegionsContents) 1076 B = B.remove(baseR); 1077 } 1078 1079 if (const auto *TO = dyn_cast<TypedValueRegion>(baseR)) { 1080 if (const auto *RD = TO->getValueType()->getAsCXXRecordDecl()) { 1081 1082 // Lambdas can affect all static local variables without explicitly 1083 // capturing those. 1084 // We invalidate all static locals referenced inside the lambda body. 1085 if (RD->isLambda() && RD->getLambdaCallOperator()->getBody()) { 1086 using namespace ast_matchers; 1087 1088 const char *DeclBind = "DeclBind"; 1089 StatementMatcher RefToStatic = stmt(hasDescendant(declRefExpr( 1090 to(varDecl(hasStaticStorageDuration()).bind(DeclBind))))); 1091 auto Matches = 1092 match(RefToStatic, *RD->getLambdaCallOperator()->getBody(), 1093 RD->getASTContext()); 1094 1095 for (BoundNodes &Match : Matches) { 1096 auto *VD = Match.getNodeAs<VarDecl>(DeclBind); 1097 const VarRegion *ToInvalidate = 1098 RM.getRegionManager().getVarRegion(VD, LCtx); 1099 AddToWorkList(ToInvalidate); 1100 } 1101 } 1102 } 1103 } 1104 1105 // BlockDataRegion? If so, invalidate captured variables that are passed 1106 // by reference. 1107 if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) { 1108 for (BlockDataRegion::referenced_vars_iterator 1109 BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ; 1110 BI != BE; ++BI) { 1111 const VarRegion *VR = BI.getCapturedRegion(); 1112 const VarDecl *VD = VR->getDecl(); 1113 if (VD->hasAttr<BlocksAttr>() || !VD->hasLocalStorage()) { 1114 AddToWorkList(VR); 1115 } 1116 else if (Loc::isLocType(VR->getValueType())) { 1117 // Map the current bindings to a Store to retrieve the value 1118 // of the binding. If that binding itself is a region, we should 1119 // invalidate that region. This is because a block may capture 1120 // a pointer value, but the thing pointed by that pointer may 1121 // get invalidated. 1122 SVal V = RM.getBinding(B, loc::MemRegionVal(VR)); 1123 if (Optional<Loc> L = V.getAs<Loc>()) { 1124 if (const MemRegion *LR = L->getAsRegion()) 1125 AddToWorkList(LR); 1126 } 1127 } 1128 } 1129 return; 1130 } 1131 1132 // Symbolic region? 1133 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) 1134 IS.insert(SR->getSymbol()); 1135 1136 // Nothing else should be done in the case when we preserve regions context. 1137 if (PreserveRegionsContents) 1138 return; 1139 1140 // Otherwise, we have a normal data region. Record that we touched the region. 1141 if (Regions) 1142 Regions->push_back(baseR); 1143 1144 if (isa<AllocaRegion, SymbolicRegion>(baseR)) { 1145 // Invalidate the region by setting its default value to 1146 // conjured symbol. The type of the symbol is irrelevant. 1147 DefinedOrUnknownSVal V = 1148 svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count); 1149 B = B.addBinding(baseR, BindingKey::Default, V); 1150 return; 1151 } 1152 1153 if (!baseR->isBoundable()) 1154 return; 1155 1156 const TypedValueRegion *TR = cast<TypedValueRegion>(baseR); 1157 QualType T = TR->getValueType(); 1158 1159 if (isInitiallyIncludedGlobalRegion(baseR)) { 1160 // If the region is a global and we are invalidating all globals, 1161 // erasing the entry is good enough. This causes all globals to be lazily 1162 // symbolicated from the same base symbol. 1163 return; 1164 } 1165 1166 if (T->isRecordType()) { 1167 // Invalidate the region by setting its default value to 1168 // conjured symbol. The type of the symbol is irrelevant. 1169 DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, 1170 Ctx.IntTy, Count); 1171 B = B.addBinding(baseR, BindingKey::Default, V); 1172 return; 1173 } 1174 1175 if (const ArrayType *AT = Ctx.getAsArrayType(T)) { 1176 bool doNotInvalidateSuperRegion = ITraits.hasTrait( 1177 baseR, 1178 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion); 1179 1180 if (doNotInvalidateSuperRegion) { 1181 // We are not doing blank invalidation of the whole array region so we 1182 // have to manually invalidate each elements. 1183 Optional<uint64_t> NumElements; 1184 1185 // Compute lower and upper offsets for region within array. 1186 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 1187 NumElements = CAT->getSize().getZExtValue(); 1188 if (!NumElements) // We are not dealing with a constant size array 1189 goto conjure_default; 1190 QualType ElementTy = AT->getElementType(); 1191 uint64_t ElemSize = Ctx.getTypeSize(ElementTy); 1192 const RegionOffset &RO = baseR->getAsOffset(); 1193 const MemRegion *SuperR = baseR->getBaseRegion(); 1194 if (RO.hasSymbolicOffset()) { 1195 // If base region has a symbolic offset, 1196 // we revert to invalidating the super region. 1197 if (SuperR) 1198 AddToWorkList(SuperR); 1199 goto conjure_default; 1200 } 1201 1202 uint64_t LowerOffset = RO.getOffset(); 1203 uint64_t UpperOffset = LowerOffset + *NumElements * ElemSize; 1204 bool UpperOverflow = UpperOffset < LowerOffset; 1205 1206 // Invalidate regions which are within array boundaries, 1207 // or have a symbolic offset. 1208 if (!SuperR) 1209 goto conjure_default; 1210 1211 const ClusterBindings *C = B.lookup(SuperR); 1212 if (!C) 1213 goto conjure_default; 1214 1215 for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; 1216 ++I) { 1217 const BindingKey &BK = I.getKey(); 1218 Optional<uint64_t> ROffset = 1219 BK.hasSymbolicOffset() ? Optional<uint64_t>() : BK.getOffset(); 1220 1221 // Check offset is not symbolic and within array's boundaries. 1222 // Handles arrays of 0 elements and of 0-sized elements as well. 1223 if (!ROffset || 1224 ((*ROffset >= LowerOffset && *ROffset < UpperOffset) || 1225 (UpperOverflow && 1226 (*ROffset >= LowerOffset || *ROffset < UpperOffset)) || 1227 (LowerOffset == UpperOffset && *ROffset == LowerOffset))) { 1228 B = B.removeBinding(I.getKey()); 1229 // Bound symbolic regions need to be invalidated for dead symbol 1230 // detection. 1231 SVal V = I.getData(); 1232 const MemRegion *R = V.getAsRegion(); 1233 if (isa_and_nonnull<SymbolicRegion>(R)) 1234 VisitBinding(V); 1235 } 1236 } 1237 } 1238 conjure_default: 1239 // Set the default value of the array to conjured symbol. 1240 DefinedOrUnknownSVal V = 1241 svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, 1242 AT->getElementType(), Count); 1243 B = B.addBinding(baseR, BindingKey::Default, V); 1244 return; 1245 } 1246 1247 DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, 1248 T,Count); 1249 assert(SymbolManager::canSymbolicate(T) || V.isUnknown()); 1250 B = B.addBinding(baseR, BindingKey::Direct, V); 1251 } 1252 1253 bool InvalidateRegionsWorker::isInitiallyIncludedGlobalRegion( 1254 const MemRegion *R) { 1255 switch (GlobalsFilter) { 1256 case GFK_None: 1257 return false; 1258 case GFK_SystemOnly: 1259 return isa<GlobalSystemSpaceRegion>(R->getMemorySpace()); 1260 case GFK_All: 1261 return isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace()); 1262 } 1263 1264 llvm_unreachable("unknown globals filter"); 1265 } 1266 1267 bool InvalidateRegionsWorker::includeEntireMemorySpace(const MemRegion *Base) { 1268 if (isInitiallyIncludedGlobalRegion(Base)) 1269 return true; 1270 1271 const MemSpaceRegion *MemSpace = Base->getMemorySpace(); 1272 return ITraits.hasTrait(MemSpace, 1273 RegionAndSymbolInvalidationTraits::TK_EntireMemSpace); 1274 } 1275 1276 RegionBindingsRef 1277 RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K, 1278 const Expr *Ex, 1279 unsigned Count, 1280 const LocationContext *LCtx, 1281 RegionBindingsRef B, 1282 InvalidatedRegions *Invalidated) { 1283 // Bind the globals memory space to a new symbol that we will use to derive 1284 // the bindings for all globals. 1285 const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K); 1286 SVal V = svalBuilder.conjureSymbolVal(/* symbolTag = */ (const void*) GS, Ex, LCtx, 1287 /* type does not matter */ Ctx.IntTy, 1288 Count); 1289 1290 B = B.removeBinding(GS) 1291 .addBinding(BindingKey::Make(GS, BindingKey::Default), V); 1292 1293 // Even if there are no bindings in the global scope, we still need to 1294 // record that we touched it. 1295 if (Invalidated) 1296 Invalidated->push_back(GS); 1297 1298 return B; 1299 } 1300 1301 void RegionStoreManager::populateWorkList(InvalidateRegionsWorker &W, 1302 ArrayRef<SVal> Values, 1303 InvalidatedRegions *TopLevelRegions) { 1304 for (ArrayRef<SVal>::iterator I = Values.begin(), 1305 E = Values.end(); I != E; ++I) { 1306 SVal V = *I; 1307 if (Optional<nonloc::LazyCompoundVal> LCS = 1308 V.getAs<nonloc::LazyCompoundVal>()) { 1309 1310 const SValListTy &Vals = getInterestingValues(*LCS); 1311 1312 for (SValListTy::const_iterator I = Vals.begin(), 1313 E = Vals.end(); I != E; ++I) { 1314 // Note: the last argument is false here because these are 1315 // non-top-level regions. 1316 if (const MemRegion *R = (*I).getAsRegion()) 1317 W.AddToWorkList(R); 1318 } 1319 continue; 1320 } 1321 1322 if (const MemRegion *R = V.getAsRegion()) { 1323 if (TopLevelRegions) 1324 TopLevelRegions->push_back(R); 1325 W.AddToWorkList(R); 1326 continue; 1327 } 1328 } 1329 } 1330 1331 StoreRef 1332 RegionStoreManager::invalidateRegions(Store store, 1333 ArrayRef<SVal> Values, 1334 const Expr *Ex, unsigned Count, 1335 const LocationContext *LCtx, 1336 const CallEvent *Call, 1337 InvalidatedSymbols &IS, 1338 RegionAndSymbolInvalidationTraits &ITraits, 1339 InvalidatedRegions *TopLevelRegions, 1340 InvalidatedRegions *Invalidated) { 1341 GlobalsFilterKind GlobalsFilter; 1342 if (Call) { 1343 if (Call->isInSystemHeader()) 1344 GlobalsFilter = GFK_SystemOnly; 1345 else 1346 GlobalsFilter = GFK_All; 1347 } else { 1348 GlobalsFilter = GFK_None; 1349 } 1350 1351 RegionBindingsRef B = getRegionBindings(store); 1352 InvalidateRegionsWorker W(*this, StateMgr, B, Ex, Count, LCtx, IS, ITraits, 1353 Invalidated, GlobalsFilter); 1354 1355 // Scan the bindings and generate the clusters. 1356 W.GenerateClusters(); 1357 1358 // Add the regions to the worklist. 1359 populateWorkList(W, Values, TopLevelRegions); 1360 1361 W.RunWorkList(); 1362 1363 // Return the new bindings. 1364 B = W.getRegionBindings(); 1365 1366 // For calls, determine which global regions should be invalidated and 1367 // invalidate them. (Note that function-static and immutable globals are never 1368 // invalidated by this.) 1369 // TODO: This could possibly be more precise with modules. 1370 switch (GlobalsFilter) { 1371 case GFK_All: 1372 B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind, 1373 Ex, Count, LCtx, B, Invalidated); 1374 LLVM_FALLTHROUGH; 1375 case GFK_SystemOnly: 1376 B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind, 1377 Ex, Count, LCtx, B, Invalidated); 1378 LLVM_FALLTHROUGH; 1379 case GFK_None: 1380 break; 1381 } 1382 1383 return StoreRef(B.asStore(), *this); 1384 } 1385 1386 //===----------------------------------------------------------------------===// 1387 // Location and region casting. 1388 //===----------------------------------------------------------------------===// 1389 1390 /// ArrayToPointer - Emulates the "decay" of an array to a pointer 1391 /// type. 'Array' represents the lvalue of the array being decayed 1392 /// to a pointer, and the returned SVal represents the decayed 1393 /// version of that lvalue (i.e., a pointer to the first element of 1394 /// the array). This is called by ExprEngine when evaluating casts 1395 /// from arrays to pointers. 1396 SVal RegionStoreManager::ArrayToPointer(Loc Array, QualType T) { 1397 if (Array.getAs<loc::ConcreteInt>()) 1398 return Array; 1399 1400 if (!Array.getAs<loc::MemRegionVal>()) 1401 return UnknownVal(); 1402 1403 const SubRegion *R = 1404 cast<SubRegion>(Array.castAs<loc::MemRegionVal>().getRegion()); 1405 NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex(); 1406 return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, R, Ctx)); 1407 } 1408 1409 //===----------------------------------------------------------------------===// 1410 // Loading values from regions. 1411 //===----------------------------------------------------------------------===// 1412 1413 SVal RegionStoreManager::getBinding(RegionBindingsConstRef B, Loc L, QualType T) { 1414 assert(!L.getAs<UnknownVal>() && "location unknown"); 1415 assert(!L.getAs<UndefinedVal>() && "location undefined"); 1416 1417 // For access to concrete addresses, return UnknownVal. Checks 1418 // for null dereferences (and similar errors) are done by checkers, not 1419 // the Store. 1420 // FIXME: We can consider lazily symbolicating such memory, but we really 1421 // should defer this when we can reason easily about symbolicating arrays 1422 // of bytes. 1423 if (L.getAs<loc::ConcreteInt>()) { 1424 return UnknownVal(); 1425 } 1426 if (!L.getAs<loc::MemRegionVal>()) { 1427 return UnknownVal(); 1428 } 1429 1430 const MemRegion *MR = L.castAs<loc::MemRegionVal>().getRegion(); 1431 1432 if (isa<BlockDataRegion>(MR)) { 1433 return UnknownVal(); 1434 } 1435 1436 if (!isa<TypedValueRegion>(MR)) { 1437 if (T.isNull()) { 1438 if (const TypedRegion *TR = dyn_cast<TypedRegion>(MR)) 1439 T = TR->getLocationType()->getPointeeType(); 1440 else if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(MR)) 1441 T = SR->getSymbol()->getType()->getPointeeType(); 1442 } 1443 assert(!T.isNull() && "Unable to auto-detect binding type!"); 1444 assert(!T->isVoidType() && "Attempting to dereference a void pointer!"); 1445 MR = GetElementZeroRegion(cast<SubRegion>(MR), T); 1446 } else { 1447 T = cast<TypedValueRegion>(MR)->getValueType(); 1448 } 1449 1450 // FIXME: Perhaps this method should just take a 'const MemRegion*' argument 1451 // instead of 'Loc', and have the other Loc cases handled at a higher level. 1452 const TypedValueRegion *R = cast<TypedValueRegion>(MR); 1453 QualType RTy = R->getValueType(); 1454 1455 // FIXME: we do not yet model the parts of a complex type, so treat the 1456 // whole thing as "unknown". 1457 if (RTy->isAnyComplexType()) 1458 return UnknownVal(); 1459 1460 // FIXME: We should eventually handle funny addressing. e.g.: 1461 // 1462 // int x = ...; 1463 // int *p = &x; 1464 // char *q = (char*) p; 1465 // char c = *q; // returns the first byte of 'x'. 1466 // 1467 // Such funny addressing will occur due to layering of regions. 1468 if (RTy->isStructureOrClassType()) 1469 return getBindingForStruct(B, R); 1470 1471 // FIXME: Handle unions. 1472 if (RTy->isUnionType()) 1473 return createLazyBinding(B, R); 1474 1475 if (RTy->isArrayType()) { 1476 if (RTy->isConstantArrayType()) 1477 return getBindingForArray(B, R); 1478 else 1479 return UnknownVal(); 1480 } 1481 1482 // FIXME: handle Vector types. 1483 if (RTy->isVectorType()) 1484 return UnknownVal(); 1485 1486 if (const FieldRegion* FR = dyn_cast<FieldRegion>(R)) 1487 return svalBuilder.evalCast(getBindingForField(B, FR), T, QualType{}); 1488 1489 if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) { 1490 // FIXME: Here we actually perform an implicit conversion from the loaded 1491 // value to the element type. Eventually we want to compose these values 1492 // more intelligently. For example, an 'element' can encompass multiple 1493 // bound regions (e.g., several bound bytes), or could be a subset of 1494 // a larger value. 1495 return svalBuilder.evalCast(getBindingForElement(B, ER), T, QualType{}); 1496 } 1497 1498 if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) { 1499 // FIXME: Here we actually perform an implicit conversion from the loaded 1500 // value to the ivar type. What we should model is stores to ivars 1501 // that blow past the extent of the ivar. If the address of the ivar is 1502 // reinterpretted, it is possible we stored a different value that could 1503 // fit within the ivar. Either we need to cast these when storing them 1504 // or reinterpret them lazily (as we do here). 1505 return svalBuilder.evalCast(getBindingForObjCIvar(B, IVR), T, QualType{}); 1506 } 1507 1508 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) { 1509 // FIXME: Here we actually perform an implicit conversion from the loaded 1510 // value to the variable type. What we should model is stores to variables 1511 // that blow past the extent of the variable. If the address of the 1512 // variable is reinterpretted, it is possible we stored a different value 1513 // that could fit within the variable. Either we need to cast these when 1514 // storing them or reinterpret them lazily (as we do here). 1515 return svalBuilder.evalCast(getBindingForVar(B, VR), T, QualType{}); 1516 } 1517 1518 const SVal *V = B.lookup(R, BindingKey::Direct); 1519 1520 // Check if the region has a binding. 1521 if (V) 1522 return *V; 1523 1524 // The location does not have a bound value. This means that it has 1525 // the value it had upon its creation and/or entry to the analyzed 1526 // function/method. These are either symbolic values or 'undefined'. 1527 if (R->hasStackNonParametersStorage()) { 1528 // All stack variables are considered to have undefined values 1529 // upon creation. All heap allocated blocks are considered to 1530 // have undefined values as well unless they are explicitly bound 1531 // to specific values. 1532 return UndefinedVal(); 1533 } 1534 1535 // All other values are symbolic. 1536 return svalBuilder.getRegionValueSymbolVal(R); 1537 } 1538 1539 static QualType getUnderlyingType(const SubRegion *R) { 1540 QualType RegionTy; 1541 if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R)) 1542 RegionTy = TVR->getValueType(); 1543 1544 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) 1545 RegionTy = SR->getSymbol()->getType(); 1546 1547 return RegionTy; 1548 } 1549 1550 /// Checks to see if store \p B has a lazy binding for region \p R. 1551 /// 1552 /// If \p AllowSubregionBindings is \c false, a lazy binding will be rejected 1553 /// if there are additional bindings within \p R. 1554 /// 1555 /// Note that unlike RegionStoreManager::findLazyBinding, this will not search 1556 /// for lazy bindings for super-regions of \p R. 1557 static Optional<nonloc::LazyCompoundVal> 1558 getExistingLazyBinding(SValBuilder &SVB, RegionBindingsConstRef B, 1559 const SubRegion *R, bool AllowSubregionBindings) { 1560 Optional<SVal> V = B.getDefaultBinding(R); 1561 if (!V) 1562 return None; 1563 1564 Optional<nonloc::LazyCompoundVal> LCV = V->getAs<nonloc::LazyCompoundVal>(); 1565 if (!LCV) 1566 return None; 1567 1568 // If the LCV is for a subregion, the types might not match, and we shouldn't 1569 // reuse the binding. 1570 QualType RegionTy = getUnderlyingType(R); 1571 if (!RegionTy.isNull() && 1572 !RegionTy->isVoidPointerType()) { 1573 QualType SourceRegionTy = LCV->getRegion()->getValueType(); 1574 if (!SVB.getContext().hasSameUnqualifiedType(RegionTy, SourceRegionTy)) 1575 return None; 1576 } 1577 1578 if (!AllowSubregionBindings) { 1579 // If there are any other bindings within this region, we shouldn't reuse 1580 // the top-level binding. 1581 SmallVector<BindingPair, 16> Bindings; 1582 collectSubRegionBindings(Bindings, SVB, *B.lookup(R->getBaseRegion()), R, 1583 /*IncludeAllDefaultBindings=*/true); 1584 if (Bindings.size() > 1) 1585 return None; 1586 } 1587 1588 return *LCV; 1589 } 1590 1591 1592 std::pair<Store, const SubRegion *> 1593 RegionStoreManager::findLazyBinding(RegionBindingsConstRef B, 1594 const SubRegion *R, 1595 const SubRegion *originalRegion) { 1596 if (originalRegion != R) { 1597 if (Optional<nonloc::LazyCompoundVal> V = 1598 getExistingLazyBinding(svalBuilder, B, R, true)) 1599 return std::make_pair(V->getStore(), V->getRegion()); 1600 } 1601 1602 typedef std::pair<Store, const SubRegion *> StoreRegionPair; 1603 StoreRegionPair Result = StoreRegionPair(); 1604 1605 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) { 1606 Result = findLazyBinding(B, cast<SubRegion>(ER->getSuperRegion()), 1607 originalRegion); 1608 1609 if (Result.second) 1610 Result.second = MRMgr.getElementRegionWithSuper(ER, Result.second); 1611 1612 } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) { 1613 Result = findLazyBinding(B, cast<SubRegion>(FR->getSuperRegion()), 1614 originalRegion); 1615 1616 if (Result.second) 1617 Result.second = MRMgr.getFieldRegionWithSuper(FR, Result.second); 1618 1619 } else if (const CXXBaseObjectRegion *BaseReg = 1620 dyn_cast<CXXBaseObjectRegion>(R)) { 1621 // C++ base object region is another kind of region that we should blast 1622 // through to look for lazy compound value. It is like a field region. 1623 Result = findLazyBinding(B, cast<SubRegion>(BaseReg->getSuperRegion()), 1624 originalRegion); 1625 1626 if (Result.second) 1627 Result.second = MRMgr.getCXXBaseObjectRegionWithSuper(BaseReg, 1628 Result.second); 1629 } 1630 1631 return Result; 1632 } 1633 1634 Optional<SVal> RegionStoreManager::getConstantValFromConstArrayInitializer( 1635 RegionBindingsConstRef B, const VarRegion *VR, const ElementRegion *R) { 1636 assert(R && VR && "Regions should not be null"); 1637 1638 // Check if the containing array has an initialized value that we can trust. 1639 // We can trust a const value or a value of a global initializer in main(). 1640 const VarDecl *VD = VR->getDecl(); 1641 if (!VD->getType().isConstQualified() && 1642 !R->getElementType().isConstQualified() && 1643 (!B.isMainAnalysis() || !VD->hasGlobalStorage())) 1644 return None; 1645 1646 // Array's declaration should have `ConstantArrayType` type, because only this 1647 // type contains an array extent. It may happen that array type can be of 1648 // `IncompleteArrayType` type. To get the declaration of `ConstantArrayType` 1649 // type, we should find the declaration in the redeclarations chain that has 1650 // the initialization expression. 1651 // NOTE: `getAnyInitializer` has an out-parameter, which returns a new `VD` 1652 // from which an initializer is obtained. We replace current `VD` with the new 1653 // `VD`. If the return value of the function is null than `VD` won't be 1654 // replaced. 1655 const Expr *Init = VD->getAnyInitializer(VD); 1656 // NOTE: If `Init` is non-null, then a new `VD` is non-null for sure. So check 1657 // `Init` for null only and don't worry about the replaced `VD`. 1658 if (!Init) 1659 return None; 1660 1661 // Array's declaration should have ConstantArrayType type, because only this 1662 // type contains an array extent. 1663 const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(VD->getType()); 1664 if (!CAT) 1665 return None; 1666 1667 // Array should be one-dimensional. 1668 // TODO: Support multidimensional array. 1669 if (isa<ConstantArrayType>(CAT->getElementType())) // is multidimensional 1670 return None; 1671 1672 // Array's offset should be a concrete value. 1673 // Return Unknown value if symbolic index presented. 1674 // FIXME: We also need to take ElementRegions with symbolic 1675 // indexes into account. 1676 const auto OffsetVal = R->getIndex().getAs<nonloc::ConcreteInt>(); 1677 if (!OffsetVal.hasValue()) 1678 return UnknownVal(); 1679 1680 // Check offset for being out of bounds. 1681 // C++20 [expr.add] 7.6.6.4 (excerpt): 1682 // If P points to an array element i of an array object x with n 1683 // elements, where i < 0 or i > n, the behavior is undefined. 1684 // Dereferencing is not allowed on the "one past the last 1685 // element", when i == n. 1686 // Example: 1687 // const int arr[4] = {1, 2}; 1688 // const int *ptr = arr; 1689 // int x0 = ptr[0]; // 1 1690 // int x1 = ptr[1]; // 2 1691 // int x2 = ptr[2]; // 0 1692 // int x3 = ptr[3]; // 0 1693 // int x4 = ptr[4]; // UB 1694 // int x5 = ptr[-1]; // UB 1695 const llvm::APSInt &OffsetInt = OffsetVal->getValue(); 1696 const auto Offset = static_cast<uint64_t>(OffsetInt.getExtValue()); 1697 // Use `getZExtValue` because array extent can not be negative. 1698 const uint64_t Extent = CAT->getSize().getZExtValue(); 1699 // Check for `OffsetInt < 0` but NOT for `Offset < 0`, because `OffsetInt` 1700 // CAN be negative, but `Offset` can NOT, because `Offset` is an uint64_t. 1701 if (OffsetInt < 0 || Offset >= Extent) 1702 return UndefinedVal(); 1703 // From here `Offset` is in the bounds. 1704 1705 // Handle InitListExpr. 1706 // Example: 1707 // const char arr[] = { 1, 2, 3 }; 1708 if (const auto *ILE = dyn_cast<InitListExpr>(Init)) 1709 return getSValFromInitListExpr(ILE, Offset, R->getElementType()); 1710 1711 // Handle StringLiteral. 1712 // Example: 1713 // const char arr[] = "abc"; 1714 if (const auto *SL = dyn_cast<StringLiteral>(Init)) 1715 return getSValFromStringLiteral(SL, Offset, R->getElementType()); 1716 1717 // FIXME: Handle CompoundLiteralExpr. 1718 1719 return None; 1720 } 1721 1722 Optional<SVal> 1723 RegionStoreManager::getSValFromInitListExpr(const InitListExpr *ILE, 1724 uint64_t Offset, QualType ElemT) { 1725 assert(ILE && "InitListExpr should not be null"); 1726 1727 // C++20 [dcl.init.string] 9.4.2.1: 1728 // An array of ordinary character type [...] can be initialized by [...] 1729 // an appropriately-typed string-literal enclosed in braces. 1730 // Example: 1731 // const char arr[] = { "abc" }; 1732 if (ILE->isStringLiteralInit()) 1733 if (const auto *SL = dyn_cast<StringLiteral>(ILE->getInit(0))) 1734 return getSValFromStringLiteral(SL, Offset, ElemT); 1735 1736 // C++20 [expr.add] 9.4.17.5 (excerpt): 1737 // i-th array element is value-initialized for each k < i ≤ n, 1738 // where k is an expression-list size and n is an array extent. 1739 if (Offset >= ILE->getNumInits()) 1740 return svalBuilder.makeZeroVal(ElemT); 1741 1742 // Return a constant value, if it is presented. 1743 // FIXME: Support other SVals. 1744 const Expr *E = ILE->getInit(Offset); 1745 return svalBuilder.getConstantVal(E); 1746 } 1747 1748 /// Returns an SVal, if possible, for the specified position in a string 1749 /// literal. 1750 /// 1751 /// \param SL The given string literal. 1752 /// \param Offset The unsigned offset. E.g. for the expression 1753 /// `char x = str[42];` an offset should be 42. 1754 /// E.g. for the string "abc" offset: 1755 /// - 1 returns SVal{b}, because it's the second position in the string. 1756 /// - 42 returns SVal{0}, because there's no explicit value at this 1757 /// position in the string. 1758 /// \param ElemT The type of the result SVal expression. 1759 /// 1760 /// NOTE: We return `0` for every offset >= the literal length for array 1761 /// declarations, like: 1762 /// const char str[42] = "123"; // Literal length is 4. 1763 /// char c = str[41]; // Offset is 41. 1764 /// FIXME: Nevertheless, we can't do the same for pointer declaraions, like: 1765 /// const char * const str = "123"; // Literal length is 4. 1766 /// char c = str[41]; // Offset is 41. Returns `0`, but Undef 1767 /// // expected. 1768 /// It should be properly handled before reaching this point. 1769 /// The main problem is that we can't distinguish between these declarations, 1770 /// because in case of array we can get the Decl from VarRegion, but in case 1771 /// of pointer the region is a StringRegion, which doesn't contain a Decl. 1772 /// Possible solution could be passing an array extent along with the offset. 1773 SVal RegionStoreManager::getSValFromStringLiteral(const StringLiteral *SL, 1774 uint64_t Offset, 1775 QualType ElemT) { 1776 assert(SL && "StringLiteral should not be null"); 1777 // C++20 [dcl.init.string] 9.4.2.3: 1778 // If there are fewer initializers than there are array elements, each 1779 // element not explicitly initialized shall be zero-initialized [dcl.init]. 1780 uint32_t Code = (Offset >= SL->getLength()) ? 0 : SL->getCodeUnit(Offset); 1781 return svalBuilder.makeIntVal(Code, ElemT); 1782 } 1783 1784 SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B, 1785 const ElementRegion* R) { 1786 // Check if the region has a binding. 1787 if (const Optional<SVal> &V = B.getDirectBinding(R)) 1788 return *V; 1789 1790 const MemRegion* superR = R->getSuperRegion(); 1791 1792 // Check if the region is an element region of a string literal. 1793 if (const StringRegion *StrR = dyn_cast<StringRegion>(superR)) { 1794 // FIXME: Handle loads from strings where the literal is treated as 1795 // an integer, e.g., *((unsigned int*)"hello"). Such loads are UB according 1796 // to C++20 7.2.1.11 [basic.lval]. 1797 QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType(); 1798 if (!Ctx.hasSameUnqualifiedType(T, R->getElementType())) 1799 return UnknownVal(); 1800 if (const auto CI = R->getIndex().getAs<nonloc::ConcreteInt>()) { 1801 const llvm::APSInt &Idx = CI->getValue(); 1802 if (Idx < 0) 1803 return UndefinedVal(); 1804 const StringLiteral *SL = StrR->getStringLiteral(); 1805 return getSValFromStringLiteral(SL, Idx.getZExtValue(), T); 1806 } 1807 } else if (const VarRegion *VR = dyn_cast<VarRegion>(superR)) { 1808 if (Optional<SVal> V = getConstantValFromConstArrayInitializer(B, VR, R)) 1809 return *V; 1810 } 1811 1812 // Check for loads from a code text region. For such loads, just give up. 1813 if (isa<CodeTextRegion>(superR)) 1814 return UnknownVal(); 1815 1816 // Handle the case where we are indexing into a larger scalar object. 1817 // For example, this handles: 1818 // int x = ... 1819 // char *y = &x; 1820 // return *y; 1821 // FIXME: This is a hack, and doesn't do anything really intelligent yet. 1822 const RegionRawOffset &O = R->getAsArrayOffset(); 1823 1824 // If we cannot reason about the offset, return an unknown value. 1825 if (!O.getRegion()) 1826 return UnknownVal(); 1827 1828 if (const TypedValueRegion *baseR = 1829 dyn_cast_or_null<TypedValueRegion>(O.getRegion())) { 1830 QualType baseT = baseR->getValueType(); 1831 if (baseT->isScalarType()) { 1832 QualType elemT = R->getElementType(); 1833 if (elemT->isScalarType()) { 1834 if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) { 1835 if (const Optional<SVal> &V = B.getDirectBinding(superR)) { 1836 if (SymbolRef parentSym = V->getAsSymbol()) 1837 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); 1838 1839 if (V->isUnknownOrUndef()) 1840 return *V; 1841 // Other cases: give up. We are indexing into a larger object 1842 // that has some value, but we don't know how to handle that yet. 1843 return UnknownVal(); 1844 } 1845 } 1846 } 1847 } 1848 } 1849 return getBindingForFieldOrElementCommon(B, R, R->getElementType()); 1850 } 1851 1852 SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B, 1853 const FieldRegion* R) { 1854 1855 // Check if the region has a binding. 1856 if (const Optional<SVal> &V = B.getDirectBinding(R)) 1857 return *V; 1858 1859 // Is the field declared constant and has an in-class initializer? 1860 const FieldDecl *FD = R->getDecl(); 1861 QualType Ty = FD->getType(); 1862 if (Ty.isConstQualified()) 1863 if (const Expr *Init = FD->getInClassInitializer()) 1864 if (Optional<SVal> V = svalBuilder.getConstantVal(Init)) 1865 return *V; 1866 1867 // If the containing record was initialized, try to get its constant value. 1868 const MemRegion* superR = R->getSuperRegion(); 1869 if (const auto *VR = dyn_cast<VarRegion>(superR)) { 1870 const VarDecl *VD = VR->getDecl(); 1871 QualType RecordVarTy = VD->getType(); 1872 unsigned Index = FD->getFieldIndex(); 1873 // Either the record variable or the field has an initializer that we can 1874 // trust. We trust initializers of constants and, additionally, respect 1875 // initializers of globals when analyzing main(). 1876 if (RecordVarTy.isConstQualified() || Ty.isConstQualified() || 1877 (B.isMainAnalysis() && VD->hasGlobalStorage())) 1878 if (const Expr *Init = VD->getAnyInitializer()) 1879 if (const auto *InitList = dyn_cast<InitListExpr>(Init)) { 1880 if (Index < InitList->getNumInits()) { 1881 if (const Expr *FieldInit = InitList->getInit(Index)) 1882 if (Optional<SVal> V = svalBuilder.getConstantVal(FieldInit)) 1883 return *V; 1884 } else { 1885 return svalBuilder.makeZeroVal(Ty); 1886 } 1887 } 1888 } 1889 1890 return getBindingForFieldOrElementCommon(B, R, Ty); 1891 } 1892 1893 Optional<SVal> 1894 RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindingsConstRef B, 1895 const MemRegion *superR, 1896 const TypedValueRegion *R, 1897 QualType Ty) { 1898 1899 if (const Optional<SVal> &D = B.getDefaultBinding(superR)) { 1900 const SVal &val = D.getValue(); 1901 if (SymbolRef parentSym = val.getAsSymbol()) 1902 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); 1903 1904 if (val.isZeroConstant()) 1905 return svalBuilder.makeZeroVal(Ty); 1906 1907 if (val.isUnknownOrUndef()) 1908 return val; 1909 1910 // Lazy bindings are usually handled through getExistingLazyBinding(). 1911 // We should unify these two code paths at some point. 1912 if (val.getAs<nonloc::LazyCompoundVal>() || 1913 val.getAs<nonloc::CompoundVal>()) 1914 return val; 1915 1916 llvm_unreachable("Unknown default value"); 1917 } 1918 1919 return None; 1920 } 1921 1922 SVal RegionStoreManager::getLazyBinding(const SubRegion *LazyBindingRegion, 1923 RegionBindingsRef LazyBinding) { 1924 SVal Result; 1925 if (const ElementRegion *ER = dyn_cast<ElementRegion>(LazyBindingRegion)) 1926 Result = getBindingForElement(LazyBinding, ER); 1927 else 1928 Result = getBindingForField(LazyBinding, 1929 cast<FieldRegion>(LazyBindingRegion)); 1930 1931 // FIXME: This is a hack to deal with RegionStore's inability to distinguish a 1932 // default value for /part/ of an aggregate from a default value for the 1933 // /entire/ aggregate. The most common case of this is when struct Outer 1934 // has as its first member a struct Inner, which is copied in from a stack 1935 // variable. In this case, even if the Outer's default value is symbolic, 0, 1936 // or unknown, it gets overridden by the Inner's default value of undefined. 1937 // 1938 // This is a general problem -- if the Inner is zero-initialized, the Outer 1939 // will now look zero-initialized. The proper way to solve this is with a 1940 // new version of RegionStore that tracks the extent of a binding as well 1941 // as the offset. 1942 // 1943 // This hack only takes care of the undefined case because that can very 1944 // quickly result in a warning. 1945 if (Result.isUndef()) 1946 Result = UnknownVal(); 1947 1948 return Result; 1949 } 1950 1951 SVal 1952 RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B, 1953 const TypedValueRegion *R, 1954 QualType Ty) { 1955 1956 // At this point we have already checked in either getBindingForElement or 1957 // getBindingForField if 'R' has a direct binding. 1958 1959 // Lazy binding? 1960 Store lazyBindingStore = nullptr; 1961 const SubRegion *lazyBindingRegion = nullptr; 1962 std::tie(lazyBindingStore, lazyBindingRegion) = findLazyBinding(B, R, R); 1963 if (lazyBindingRegion) 1964 return getLazyBinding(lazyBindingRegion, 1965 getRegionBindings(lazyBindingStore)); 1966 1967 // Record whether or not we see a symbolic index. That can completely 1968 // be out of scope of our lookup. 1969 bool hasSymbolicIndex = false; 1970 1971 // FIXME: This is a hack to deal with RegionStore's inability to distinguish a 1972 // default value for /part/ of an aggregate from a default value for the 1973 // /entire/ aggregate. The most common case of this is when struct Outer 1974 // has as its first member a struct Inner, which is copied in from a stack 1975 // variable. In this case, even if the Outer's default value is symbolic, 0, 1976 // or unknown, it gets overridden by the Inner's default value of undefined. 1977 // 1978 // This is a general problem -- if the Inner is zero-initialized, the Outer 1979 // will now look zero-initialized. The proper way to solve this is with a 1980 // new version of RegionStore that tracks the extent of a binding as well 1981 // as the offset. 1982 // 1983 // This hack only takes care of the undefined case because that can very 1984 // quickly result in a warning. 1985 bool hasPartialLazyBinding = false; 1986 1987 const SubRegion *SR = R; 1988 while (SR) { 1989 const MemRegion *Base = SR->getSuperRegion(); 1990 if (Optional<SVal> D = getBindingForDerivedDefaultValue(B, Base, R, Ty)) { 1991 if (D->getAs<nonloc::LazyCompoundVal>()) { 1992 hasPartialLazyBinding = true; 1993 break; 1994 } 1995 1996 return *D; 1997 } 1998 1999 if (const ElementRegion *ER = dyn_cast<ElementRegion>(Base)) { 2000 NonLoc index = ER->getIndex(); 2001 if (!index.isConstant()) 2002 hasSymbolicIndex = true; 2003 } 2004 2005 // If our super region is a field or element itself, walk up the region 2006 // hierarchy to see if there is a default value installed in an ancestor. 2007 SR = dyn_cast<SubRegion>(Base); 2008 } 2009 2010 if (R->hasStackNonParametersStorage()) { 2011 if (isa<ElementRegion>(R)) { 2012 // Currently we don't reason specially about Clang-style vectors. Check 2013 // if superR is a vector and if so return Unknown. 2014 if (const TypedValueRegion *typedSuperR = 2015 dyn_cast<TypedValueRegion>(R->getSuperRegion())) { 2016 if (typedSuperR->getValueType()->isVectorType()) 2017 return UnknownVal(); 2018 } 2019 } 2020 2021 // FIXME: We also need to take ElementRegions with symbolic indexes into 2022 // account. This case handles both directly accessing an ElementRegion 2023 // with a symbolic offset, but also fields within an element with 2024 // a symbolic offset. 2025 if (hasSymbolicIndex) 2026 return UnknownVal(); 2027 2028 // Additionally allow introspection of a block's internal layout. 2029 if (!hasPartialLazyBinding && !isa<BlockDataRegion>(R->getBaseRegion())) 2030 return UndefinedVal(); 2031 } 2032 2033 // All other values are symbolic. 2034 return svalBuilder.getRegionValueSymbolVal(R); 2035 } 2036 2037 SVal RegionStoreManager::getBindingForObjCIvar(RegionBindingsConstRef B, 2038 const ObjCIvarRegion* R) { 2039 // Check if the region has a binding. 2040 if (const Optional<SVal> &V = B.getDirectBinding(R)) 2041 return *V; 2042 2043 const MemRegion *superR = R->getSuperRegion(); 2044 2045 // Check if the super region has a default binding. 2046 if (const Optional<SVal> &V = B.getDefaultBinding(superR)) { 2047 if (SymbolRef parentSym = V->getAsSymbol()) 2048 return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); 2049 2050 // Other cases: give up. 2051 return UnknownVal(); 2052 } 2053 2054 return getBindingForLazySymbol(R); 2055 } 2056 2057 SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B, 2058 const VarRegion *R) { 2059 2060 // Check if the region has a binding. 2061 if (Optional<SVal> V = B.getDirectBinding(R)) 2062 return *V; 2063 2064 if (Optional<SVal> V = B.getDefaultBinding(R)) 2065 return *V; 2066 2067 // Lazily derive a value for the VarRegion. 2068 const VarDecl *VD = R->getDecl(); 2069 const MemSpaceRegion *MS = R->getMemorySpace(); 2070 2071 // Arguments are always symbolic. 2072 if (isa<StackArgumentsSpaceRegion>(MS)) 2073 return svalBuilder.getRegionValueSymbolVal(R); 2074 2075 // Is 'VD' declared constant? If so, retrieve the constant value. 2076 if (VD->getType().isConstQualified()) { 2077 if (const Expr *Init = VD->getAnyInitializer()) { 2078 if (Optional<SVal> V = svalBuilder.getConstantVal(Init)) 2079 return *V; 2080 2081 // If the variable is const qualified and has an initializer but 2082 // we couldn't evaluate initializer to a value, treat the value as 2083 // unknown. 2084 return UnknownVal(); 2085 } 2086 } 2087 2088 // This must come after the check for constants because closure-captured 2089 // constant variables may appear in UnknownSpaceRegion. 2090 if (isa<UnknownSpaceRegion>(MS)) 2091 return svalBuilder.getRegionValueSymbolVal(R); 2092 2093 if (isa<GlobalsSpaceRegion>(MS)) { 2094 QualType T = VD->getType(); 2095 2096 // If we're in main(), then global initializers have not become stale yet. 2097 if (B.isMainAnalysis()) 2098 if (const Expr *Init = VD->getAnyInitializer()) 2099 if (Optional<SVal> V = svalBuilder.getConstantVal(Init)) 2100 return *V; 2101 2102 // Function-scoped static variables are default-initialized to 0; if they 2103 // have an initializer, it would have been processed by now. 2104 // FIXME: This is only true when we're starting analysis from main(). 2105 // We're losing a lot of coverage here. 2106 if (isa<StaticGlobalSpaceRegion>(MS)) 2107 return svalBuilder.makeZeroVal(T); 2108 2109 if (Optional<SVal> V = getBindingForDerivedDefaultValue(B, MS, R, T)) { 2110 assert(!V->getAs<nonloc::LazyCompoundVal>()); 2111 return V.getValue(); 2112 } 2113 2114 return svalBuilder.getRegionValueSymbolVal(R); 2115 } 2116 2117 return UndefinedVal(); 2118 } 2119 2120 SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) { 2121 // All other values are symbolic. 2122 return svalBuilder.getRegionValueSymbolVal(R); 2123 } 2124 2125 const RegionStoreManager::SValListTy & 2126 RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV) { 2127 // First, check the cache. 2128 LazyBindingsMapTy::iterator I = LazyBindingsMap.find(LCV.getCVData()); 2129 if (I != LazyBindingsMap.end()) 2130 return I->second; 2131 2132 // If we don't have a list of values cached, start constructing it. 2133 SValListTy List; 2134 2135 const SubRegion *LazyR = LCV.getRegion(); 2136 RegionBindingsRef B = getRegionBindings(LCV.getStore()); 2137 2138 // If this region had /no/ bindings at the time, there are no interesting 2139 // values to return. 2140 const ClusterBindings *Cluster = B.lookup(LazyR->getBaseRegion()); 2141 if (!Cluster) 2142 return (LazyBindingsMap[LCV.getCVData()] = std::move(List)); 2143 2144 SmallVector<BindingPair, 32> Bindings; 2145 collectSubRegionBindings(Bindings, svalBuilder, *Cluster, LazyR, 2146 /*IncludeAllDefaultBindings=*/true); 2147 for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(), 2148 E = Bindings.end(); 2149 I != E; ++I) { 2150 SVal V = I->second; 2151 if (V.isUnknownOrUndef() || V.isConstant()) 2152 continue; 2153 2154 if (Optional<nonloc::LazyCompoundVal> InnerLCV = 2155 V.getAs<nonloc::LazyCompoundVal>()) { 2156 const SValListTy &InnerList = getInterestingValues(*InnerLCV); 2157 List.insert(List.end(), InnerList.begin(), InnerList.end()); 2158 continue; 2159 } 2160 2161 List.push_back(V); 2162 } 2163 2164 return (LazyBindingsMap[LCV.getCVData()] = std::move(List)); 2165 } 2166 2167 NonLoc RegionStoreManager::createLazyBinding(RegionBindingsConstRef B, 2168 const TypedValueRegion *R) { 2169 if (Optional<nonloc::LazyCompoundVal> V = 2170 getExistingLazyBinding(svalBuilder, B, R, false)) 2171 return *V; 2172 2173 return svalBuilder.makeLazyCompoundVal(StoreRef(B.asStore(), *this), R); 2174 } 2175 2176 static bool isRecordEmpty(const RecordDecl *RD) { 2177 if (!RD->field_empty()) 2178 return false; 2179 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) 2180 return CRD->getNumBases() == 0; 2181 return true; 2182 } 2183 2184 SVal RegionStoreManager::getBindingForStruct(RegionBindingsConstRef B, 2185 const TypedValueRegion *R) { 2186 const RecordDecl *RD = R->getValueType()->castAs<RecordType>()->getDecl(); 2187 if (!RD->getDefinition() || isRecordEmpty(RD)) 2188 return UnknownVal(); 2189 2190 return createLazyBinding(B, R); 2191 } 2192 2193 SVal RegionStoreManager::getBindingForArray(RegionBindingsConstRef B, 2194 const TypedValueRegion *R) { 2195 assert(Ctx.getAsConstantArrayType(R->getValueType()) && 2196 "Only constant array types can have compound bindings."); 2197 2198 return createLazyBinding(B, R); 2199 } 2200 2201 bool RegionStoreManager::includedInBindings(Store store, 2202 const MemRegion *region) const { 2203 RegionBindingsRef B = getRegionBindings(store); 2204 region = region->getBaseRegion(); 2205 2206 // Quick path: if the base is the head of a cluster, the region is live. 2207 if (B.lookup(region)) 2208 return true; 2209 2210 // Slow path: if the region is the VALUE of any binding, it is live. 2211 for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); RI != RE; ++RI) { 2212 const ClusterBindings &Cluster = RI.getData(); 2213 for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end(); 2214 CI != CE; ++CI) { 2215 const SVal &D = CI.getData(); 2216 if (const MemRegion *R = D.getAsRegion()) 2217 if (R->getBaseRegion() == region) 2218 return true; 2219 } 2220 } 2221 2222 return false; 2223 } 2224 2225 //===----------------------------------------------------------------------===// 2226 // Binding values to regions. 2227 //===----------------------------------------------------------------------===// 2228 2229 StoreRef RegionStoreManager::killBinding(Store ST, Loc L) { 2230 if (Optional<loc::MemRegionVal> LV = L.getAs<loc::MemRegionVal>()) 2231 if (const MemRegion* R = LV->getRegion()) 2232 return StoreRef(getRegionBindings(ST).removeBinding(R) 2233 .asImmutableMap() 2234 .getRootWithoutRetain(), 2235 *this); 2236 2237 return StoreRef(ST, *this); 2238 } 2239 2240 RegionBindingsRef 2241 RegionStoreManager::bind(RegionBindingsConstRef B, Loc L, SVal V) { 2242 if (L.getAs<loc::ConcreteInt>()) 2243 return B; 2244 2245 // If we get here, the location should be a region. 2246 const MemRegion *R = L.castAs<loc::MemRegionVal>().getRegion(); 2247 2248 // Check if the region is a struct region. 2249 if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) { 2250 QualType Ty = TR->getValueType(); 2251 if (Ty->isArrayType()) 2252 return bindArray(B, TR, V); 2253 if (Ty->isStructureOrClassType()) 2254 return bindStruct(B, TR, V); 2255 if (Ty->isVectorType()) 2256 return bindVector(B, TR, V); 2257 if (Ty->isUnionType()) 2258 return bindAggregate(B, TR, V); 2259 } 2260 2261 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) { 2262 // Binding directly to a symbolic region should be treated as binding 2263 // to element 0. 2264 QualType T = SR->getSymbol()->getType(); 2265 if (T->isAnyPointerType() || T->isReferenceType()) 2266 T = T->getPointeeType(); 2267 2268 R = GetElementZeroRegion(SR, T); 2269 } 2270 2271 assert((!isa<CXXThisRegion>(R) || !B.lookup(R)) && 2272 "'this' pointer is not an l-value and is not assignable"); 2273 2274 // Clear out bindings that may overlap with this binding. 2275 RegionBindingsRef NewB = removeSubRegionBindings(B, cast<SubRegion>(R)); 2276 return NewB.addBinding(BindingKey::Make(R, BindingKey::Direct), V); 2277 } 2278 2279 RegionBindingsRef 2280 RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B, 2281 const MemRegion *R, 2282 QualType T) { 2283 SVal V; 2284 2285 if (Loc::isLocType(T)) 2286 V = svalBuilder.makeNull(); 2287 else if (T->isIntegralOrEnumerationType()) 2288 V = svalBuilder.makeZeroVal(T); 2289 else if (T->isStructureOrClassType() || T->isArrayType()) { 2290 // Set the default value to a zero constant when it is a structure 2291 // or array. The type doesn't really matter. 2292 V = svalBuilder.makeZeroVal(Ctx.IntTy); 2293 } 2294 else { 2295 // We can't represent values of this type, but we still need to set a value 2296 // to record that the region has been initialized. 2297 // If this assertion ever fires, a new case should be added above -- we 2298 // should know how to default-initialize any value we can symbolicate. 2299 assert(!SymbolManager::canSymbolicate(T) && "This type is representable"); 2300 V = UnknownVal(); 2301 } 2302 2303 return B.addBinding(R, BindingKey::Default, V); 2304 } 2305 2306 RegionBindingsRef 2307 RegionStoreManager::bindArray(RegionBindingsConstRef B, 2308 const TypedValueRegion* R, 2309 SVal Init) { 2310 2311 const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType())); 2312 QualType ElementTy = AT->getElementType(); 2313 Optional<uint64_t> Size; 2314 2315 if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT)) 2316 Size = CAT->getSize().getZExtValue(); 2317 2318 // Check if the init expr is a literal. If so, bind the rvalue instead. 2319 // FIXME: It's not responsibility of the Store to transform this lvalue 2320 // to rvalue. ExprEngine or maybe even CFG should do this before binding. 2321 if (Optional<loc::MemRegionVal> MRV = Init.getAs<loc::MemRegionVal>()) { 2322 SVal V = getBinding(B.asStore(), *MRV, R->getValueType()); 2323 return bindAggregate(B, R, V); 2324 } 2325 2326 // Handle lazy compound values. 2327 if (Init.getAs<nonloc::LazyCompoundVal>()) 2328 return bindAggregate(B, R, Init); 2329 2330 if (Init.isUnknown()) 2331 return bindAggregate(B, R, UnknownVal()); 2332 2333 // Remaining case: explicit compound values. 2334 const nonloc::CompoundVal& CV = Init.castAs<nonloc::CompoundVal>(); 2335 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); 2336 uint64_t i = 0; 2337 2338 RegionBindingsRef NewB(B); 2339 2340 for (; Size.hasValue() ? i < Size.getValue() : true ; ++i, ++VI) { 2341 // The init list might be shorter than the array length. 2342 if (VI == VE) 2343 break; 2344 2345 const NonLoc &Idx = svalBuilder.makeArrayIndex(i); 2346 const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx); 2347 2348 if (ElementTy->isStructureOrClassType()) 2349 NewB = bindStruct(NewB, ER, *VI); 2350 else if (ElementTy->isArrayType()) 2351 NewB = bindArray(NewB, ER, *VI); 2352 else 2353 NewB = bind(NewB, loc::MemRegionVal(ER), *VI); 2354 } 2355 2356 // If the init list is shorter than the array length (or the array has 2357 // variable length), set the array default value. Values that are already set 2358 // are not overwritten. 2359 if (!Size.hasValue() || i < Size.getValue()) 2360 NewB = setImplicitDefaultValue(NewB, R, ElementTy); 2361 2362 return NewB; 2363 } 2364 2365 RegionBindingsRef RegionStoreManager::bindVector(RegionBindingsConstRef B, 2366 const TypedValueRegion* R, 2367 SVal V) { 2368 QualType T = R->getValueType(); 2369 const VectorType *VT = T->castAs<VectorType>(); // Use castAs for typedefs. 2370 2371 // Handle lazy compound values and symbolic values. 2372 if (V.getAs<nonloc::LazyCompoundVal>() || V.getAs<nonloc::SymbolVal>()) 2373 return bindAggregate(B, R, V); 2374 2375 // We may get non-CompoundVal accidentally due to imprecise cast logic or 2376 // that we are binding symbolic struct value. Kill the field values, and if 2377 // the value is symbolic go and bind it as a "default" binding. 2378 if (!V.getAs<nonloc::CompoundVal>()) { 2379 return bindAggregate(B, R, UnknownVal()); 2380 } 2381 2382 QualType ElemType = VT->getElementType(); 2383 nonloc::CompoundVal CV = V.castAs<nonloc::CompoundVal>(); 2384 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); 2385 unsigned index = 0, numElements = VT->getNumElements(); 2386 RegionBindingsRef NewB(B); 2387 2388 for ( ; index != numElements ; ++index) { 2389 if (VI == VE) 2390 break; 2391 2392 NonLoc Idx = svalBuilder.makeArrayIndex(index); 2393 const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx); 2394 2395 if (ElemType->isArrayType()) 2396 NewB = bindArray(NewB, ER, *VI); 2397 else if (ElemType->isStructureOrClassType()) 2398 NewB = bindStruct(NewB, ER, *VI); 2399 else 2400 NewB = bind(NewB, loc::MemRegionVal(ER), *VI); 2401 } 2402 return NewB; 2403 } 2404 2405 Optional<RegionBindingsRef> 2406 RegionStoreManager::tryBindSmallStruct(RegionBindingsConstRef B, 2407 const TypedValueRegion *R, 2408 const RecordDecl *RD, 2409 nonloc::LazyCompoundVal LCV) { 2410 FieldVector Fields; 2411 2412 if (const CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(RD)) 2413 if (Class->getNumBases() != 0 || Class->getNumVBases() != 0) 2414 return None; 2415 2416 for (const auto *FD : RD->fields()) { 2417 if (FD->isUnnamedBitfield()) 2418 continue; 2419 2420 // If there are too many fields, or if any of the fields are aggregates, 2421 // just use the LCV as a default binding. 2422 if (Fields.size() == SmallStructLimit) 2423 return None; 2424 2425 QualType Ty = FD->getType(); 2426 if (!(Ty->isScalarType() || Ty->isReferenceType())) 2427 return None; 2428 2429 Fields.push_back(FD); 2430 } 2431 2432 RegionBindingsRef NewB = B; 2433 2434 for (FieldVector::iterator I = Fields.begin(), E = Fields.end(); I != E; ++I){ 2435 const FieldRegion *SourceFR = MRMgr.getFieldRegion(*I, LCV.getRegion()); 2436 SVal V = getBindingForField(getRegionBindings(LCV.getStore()), SourceFR); 2437 2438 const FieldRegion *DestFR = MRMgr.getFieldRegion(*I, R); 2439 NewB = bind(NewB, loc::MemRegionVal(DestFR), V); 2440 } 2441 2442 return NewB; 2443 } 2444 2445 RegionBindingsRef RegionStoreManager::bindStruct(RegionBindingsConstRef B, 2446 const TypedValueRegion* R, 2447 SVal V) { 2448 if (!Features.supportsFields()) 2449 return B; 2450 2451 QualType T = R->getValueType(); 2452 assert(T->isStructureOrClassType()); 2453 2454 const RecordType* RT = T->castAs<RecordType>(); 2455 const RecordDecl *RD = RT->getDecl(); 2456 2457 if (!RD->isCompleteDefinition()) 2458 return B; 2459 2460 // Handle lazy compound values and symbolic values. 2461 if (Optional<nonloc::LazyCompoundVal> LCV = 2462 V.getAs<nonloc::LazyCompoundVal>()) { 2463 if (Optional<RegionBindingsRef> NewB = tryBindSmallStruct(B, R, RD, *LCV)) 2464 return *NewB; 2465 return bindAggregate(B, R, V); 2466 } 2467 if (V.getAs<nonloc::SymbolVal>()) 2468 return bindAggregate(B, R, V); 2469 2470 // We may get non-CompoundVal accidentally due to imprecise cast logic or 2471 // that we are binding symbolic struct value. Kill the field values, and if 2472 // the value is symbolic go and bind it as a "default" binding. 2473 if (V.isUnknown() || !V.getAs<nonloc::CompoundVal>()) 2474 return bindAggregate(B, R, UnknownVal()); 2475 2476 // The raw CompoundVal is essentially a symbolic InitListExpr: an (immutable) 2477 // list of other values. It appears pretty much only when there's an actual 2478 // initializer list expression in the program, and the analyzer tries to 2479 // unwrap it as soon as possible. 2480 // This code is where such unwrap happens: when the compound value is put into 2481 // the object that it was supposed to initialize (it's an *initializer* list, 2482 // after all), instead of binding the whole value to the whole object, we bind 2483 // sub-values to sub-objects. Sub-values may themselves be compound values, 2484 // and in this case the procedure becomes recursive. 2485 // FIXME: The annoying part about compound values is that they don't carry 2486 // any sort of information about which value corresponds to which sub-object. 2487 // It's simply a list of values in the middle of nowhere; we expect to match 2488 // them to sub-objects, essentially, "by index": first value binds to 2489 // the first field, second value binds to the second field, etc. 2490 // It would have been much safer to organize non-lazy compound values as 2491 // a mapping from fields/bases to values. 2492 const nonloc::CompoundVal& CV = V.castAs<nonloc::CompoundVal>(); 2493 nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); 2494 2495 RegionBindingsRef NewB(B); 2496 2497 // In C++17 aggregates may have base classes, handle those as well. 2498 // They appear before fields in the initializer list / compound value. 2499 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) { 2500 // If the object was constructed with a constructor, its value is a 2501 // LazyCompoundVal. If it's a raw CompoundVal, it means that we're 2502 // performing aggregate initialization. The only exception from this 2503 // rule is sending an Objective-C++ message that returns a C++ object 2504 // to a nil receiver; in this case the semantics is to return a 2505 // zero-initialized object even if it's a C++ object that doesn't have 2506 // this sort of constructor; the CompoundVal is empty in this case. 2507 assert((CRD->isAggregate() || (Ctx.getLangOpts().ObjC && VI == VE)) && 2508 "Non-aggregates are constructed with a constructor!"); 2509 2510 for (const auto &B : CRD->bases()) { 2511 // (Multiple inheritance is fine though.) 2512 assert(!B.isVirtual() && "Aggregates cannot have virtual base classes!"); 2513 2514 if (VI == VE) 2515 break; 2516 2517 QualType BTy = B.getType(); 2518 assert(BTy->isStructureOrClassType() && "Base classes must be classes!"); 2519 2520 const CXXRecordDecl *BRD = BTy->getAsCXXRecordDecl(); 2521 assert(BRD && "Base classes must be C++ classes!"); 2522 2523 const CXXBaseObjectRegion *BR = 2524 MRMgr.getCXXBaseObjectRegion(BRD, R, /*IsVirtual=*/false); 2525 2526 NewB = bindStruct(NewB, BR, *VI); 2527 2528 ++VI; 2529 } 2530 } 2531 2532 RecordDecl::field_iterator FI, FE; 2533 2534 for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) { 2535 2536 if (VI == VE) 2537 break; 2538 2539 // Skip any unnamed bitfields to stay in sync with the initializers. 2540 if (FI->isUnnamedBitfield()) 2541 continue; 2542 2543 QualType FTy = FI->getType(); 2544 const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R); 2545 2546 if (FTy->isArrayType()) 2547 NewB = bindArray(NewB, FR, *VI); 2548 else if (FTy->isStructureOrClassType()) 2549 NewB = bindStruct(NewB, FR, *VI); 2550 else 2551 NewB = bind(NewB, loc::MemRegionVal(FR), *VI); 2552 ++VI; 2553 } 2554 2555 // There may be fewer values in the initialize list than the fields of struct. 2556 if (FI != FE) { 2557 NewB = NewB.addBinding(R, BindingKey::Default, 2558 svalBuilder.makeIntVal(0, false)); 2559 } 2560 2561 return NewB; 2562 } 2563 2564 RegionBindingsRef 2565 RegionStoreManager::bindAggregate(RegionBindingsConstRef B, 2566 const TypedRegion *R, 2567 SVal Val) { 2568 // Remove the old bindings, using 'R' as the root of all regions 2569 // we will invalidate. Then add the new binding. 2570 return removeSubRegionBindings(B, R).addBinding(R, BindingKey::Default, Val); 2571 } 2572 2573 //===----------------------------------------------------------------------===// 2574 // State pruning. 2575 //===----------------------------------------------------------------------===// 2576 2577 namespace { 2578 class RemoveDeadBindingsWorker 2579 : public ClusterAnalysis<RemoveDeadBindingsWorker> { 2580 SmallVector<const SymbolicRegion *, 12> Postponed; 2581 SymbolReaper &SymReaper; 2582 const StackFrameContext *CurrentLCtx; 2583 2584 public: 2585 RemoveDeadBindingsWorker(RegionStoreManager &rm, 2586 ProgramStateManager &stateMgr, 2587 RegionBindingsRef b, SymbolReaper &symReaper, 2588 const StackFrameContext *LCtx) 2589 : ClusterAnalysis<RemoveDeadBindingsWorker>(rm, stateMgr, b), 2590 SymReaper(symReaper), CurrentLCtx(LCtx) {} 2591 2592 // Called by ClusterAnalysis. 2593 void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C); 2594 void VisitCluster(const MemRegion *baseR, const ClusterBindings *C); 2595 using ClusterAnalysis<RemoveDeadBindingsWorker>::VisitCluster; 2596 2597 using ClusterAnalysis::AddToWorkList; 2598 2599 bool AddToWorkList(const MemRegion *R); 2600 2601 bool UpdatePostponed(); 2602 void VisitBinding(SVal V); 2603 }; 2604 } 2605 2606 bool RemoveDeadBindingsWorker::AddToWorkList(const MemRegion *R) { 2607 const MemRegion *BaseR = R->getBaseRegion(); 2608 return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR)); 2609 } 2610 2611 void RemoveDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR, 2612 const ClusterBindings &C) { 2613 2614 if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) { 2615 if (SymReaper.isLive(VR)) 2616 AddToWorkList(baseR, &C); 2617 2618 return; 2619 } 2620 2621 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) { 2622 if (SymReaper.isLive(SR->getSymbol())) 2623 AddToWorkList(SR, &C); 2624 else 2625 Postponed.push_back(SR); 2626 2627 return; 2628 } 2629 2630 if (isa<NonStaticGlobalSpaceRegion>(baseR)) { 2631 AddToWorkList(baseR, &C); 2632 return; 2633 } 2634 2635 // CXXThisRegion in the current or parent location context is live. 2636 if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) { 2637 const auto *StackReg = 2638 cast<StackArgumentsSpaceRegion>(TR->getSuperRegion()); 2639 const StackFrameContext *RegCtx = StackReg->getStackFrame(); 2640 if (CurrentLCtx && 2641 (RegCtx == CurrentLCtx || RegCtx->isParentOf(CurrentLCtx))) 2642 AddToWorkList(TR, &C); 2643 } 2644 } 2645 2646 void RemoveDeadBindingsWorker::VisitCluster(const MemRegion *baseR, 2647 const ClusterBindings *C) { 2648 if (!C) 2649 return; 2650 2651 // Mark the symbol for any SymbolicRegion with live bindings as live itself. 2652 // This means we should continue to track that symbol. 2653 if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR)) 2654 SymReaper.markLive(SymR->getSymbol()); 2655 2656 for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; ++I) { 2657 // Element index of a binding key is live. 2658 SymReaper.markElementIndicesLive(I.getKey().getRegion()); 2659 2660 VisitBinding(I.getData()); 2661 } 2662 } 2663 2664 void RemoveDeadBindingsWorker::VisitBinding(SVal V) { 2665 // Is it a LazyCompoundVal? All referenced regions are live as well. 2666 if (Optional<nonloc::LazyCompoundVal> LCS = 2667 V.getAs<nonloc::LazyCompoundVal>()) { 2668 2669 const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS); 2670 2671 for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(), 2672 E = Vals.end(); 2673 I != E; ++I) 2674 VisitBinding(*I); 2675 2676 return; 2677 } 2678 2679 // If V is a region, then add it to the worklist. 2680 if (const MemRegion *R = V.getAsRegion()) { 2681 AddToWorkList(R); 2682 SymReaper.markLive(R); 2683 2684 // All regions captured by a block are also live. 2685 if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) { 2686 BlockDataRegion::referenced_vars_iterator I = BR->referenced_vars_begin(), 2687 E = BR->referenced_vars_end(); 2688 for ( ; I != E; ++I) 2689 AddToWorkList(I.getCapturedRegion()); 2690 } 2691 } 2692 2693 2694 // Update the set of live symbols. 2695 for (auto SI = V.symbol_begin(), SE = V.symbol_end(); SI!=SE; ++SI) 2696 SymReaper.markLive(*SI); 2697 } 2698 2699 bool RemoveDeadBindingsWorker::UpdatePostponed() { 2700 // See if any postponed SymbolicRegions are actually live now, after 2701 // having done a scan. 2702 bool Changed = false; 2703 2704 for (auto I = Postponed.begin(), E = Postponed.end(); I != E; ++I) { 2705 if (const SymbolicRegion *SR = *I) { 2706 if (SymReaper.isLive(SR->getSymbol())) { 2707 Changed |= AddToWorkList(SR); 2708 *I = nullptr; 2709 } 2710 } 2711 } 2712 2713 return Changed; 2714 } 2715 2716 StoreRef RegionStoreManager::removeDeadBindings(Store store, 2717 const StackFrameContext *LCtx, 2718 SymbolReaper& SymReaper) { 2719 RegionBindingsRef B = getRegionBindings(store); 2720 RemoveDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx); 2721 W.GenerateClusters(); 2722 2723 // Enqueue the region roots onto the worklist. 2724 for (SymbolReaper::region_iterator I = SymReaper.region_begin(), 2725 E = SymReaper.region_end(); I != E; ++I) { 2726 W.AddToWorkList(*I); 2727 } 2728 2729 do W.RunWorkList(); while (W.UpdatePostponed()); 2730 2731 // We have now scanned the store, marking reachable regions and symbols 2732 // as live. We now remove all the regions that are dead from the store 2733 // as well as update DSymbols with the set symbols that are now dead. 2734 for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; ++I) { 2735 const MemRegion *Base = I.getKey(); 2736 2737 // If the cluster has been visited, we know the region has been marked. 2738 // Otherwise, remove the dead entry. 2739 if (!W.isVisited(Base)) 2740 B = B.remove(Base); 2741 } 2742 2743 return StoreRef(B.asStore(), *this); 2744 } 2745 2746 //===----------------------------------------------------------------------===// 2747 // Utility methods. 2748 //===----------------------------------------------------------------------===// 2749 2750 void RegionStoreManager::printJson(raw_ostream &Out, Store S, const char *NL, 2751 unsigned int Space, bool IsDot) const { 2752 RegionBindingsRef Bindings = getRegionBindings(S); 2753 2754 Indent(Out, Space, IsDot) << "\"store\": "; 2755 2756 if (Bindings.isEmpty()) { 2757 Out << "null," << NL; 2758 return; 2759 } 2760 2761 Out << "{ \"pointer\": \"" << Bindings.asStore() << "\", \"items\": [" << NL; 2762 Bindings.printJson(Out, NL, Space + 1, IsDot); 2763 Indent(Out, Space, IsDot) << "]}," << NL; 2764 } 2765