1 //===- ExprEngine.h - Path-Sensitive Expression-Level Dataflow --*- 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 meta-engine for path-sensitive dataflow analysis that 10 // is built on CoreEngine, but provides the boilerplate to execute transfer 11 // functions and build the ExplodedGraph at the expression level. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H 16 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H 17 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/Type.h" 20 #include "clang/Analysis/CFG.h" 21 #include "clang/Analysis/DomainSpecific/ObjCNoReturn.h" 22 #include "clang/Analysis/ProgramPoint.h" 23 #include "clang/Basic/LLVM.h" 24 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 25 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 26 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h" 27 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 28 #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h" 29 #include "clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h" 30 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 31 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 32 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" 33 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h" 34 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h" 35 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" 36 #include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h" 37 #include "llvm/ADT/ArrayRef.h" 38 #include <cassert> 39 #include <optional> 40 #include <utility> 41 42 namespace clang { 43 44 class AnalysisDeclContextManager; 45 class AnalyzerOptions; 46 class ASTContext; 47 class CFGBlock; 48 class CFGElement; 49 class ConstructionContext; 50 class CXXBindTemporaryExpr; 51 class CXXCatchStmt; 52 class CXXConstructExpr; 53 class CXXDeleteExpr; 54 class CXXNewExpr; 55 class CXXThisExpr; 56 class Decl; 57 class DeclStmt; 58 class GCCAsmStmt; 59 class LambdaExpr; 60 class LocationContext; 61 class MaterializeTemporaryExpr; 62 class MSAsmStmt; 63 class NamedDecl; 64 class ObjCAtSynchronizedStmt; 65 class ObjCForCollectionStmt; 66 class ObjCIvarRefExpr; 67 class ObjCMessageExpr; 68 class ReturnStmt; 69 class Stmt; 70 71 namespace cross_tu { 72 73 class CrossTranslationUnitContext; 74 75 } // namespace cross_tu 76 77 namespace ento { 78 79 class AnalysisManager; 80 class BasicValueFactory; 81 class CallEvent; 82 class CheckerManager; 83 class ConstraintManager; 84 class ExplodedNodeSet; 85 class ExplodedNode; 86 class IndirectGotoNodeBuilder; 87 class MemRegion; 88 class NodeBuilderContext; 89 class NodeBuilderWithSinks; 90 class ProgramState; 91 class ProgramStateManager; 92 class RegionAndSymbolInvalidationTraits; 93 class SymbolManager; 94 class SwitchNodeBuilder; 95 96 /// Hints for figuring out of a call should be inlined during evalCall(). 97 struct EvalCallOptions { 98 /// This call is a constructor or a destructor for which we do not currently 99 /// compute the this-region correctly. 100 bool IsCtorOrDtorWithImproperlyModeledTargetRegion = false; 101 102 /// This call is a constructor or a destructor for a single element within 103 /// an array, a part of array construction or destruction. 104 bool IsArrayCtorOrDtor = false; 105 106 /// This call is a constructor or a destructor of a temporary value. 107 bool IsTemporaryCtorOrDtor = false; 108 109 /// This call is a constructor for a temporary that is lifetime-extended 110 /// by binding it to a reference-type field within an aggregate, 111 /// for example 'A { const C &c; }; A a = { C() };' 112 bool IsTemporaryLifetimeExtendedViaAggregate = false; 113 114 /// This call is a pre-C++17 elidable constructor that we failed to elide 115 /// because we failed to compute the target region into which 116 /// this constructor would have been ultimately elided. Analysis that 117 /// we perform in this case is still correct but it behaves differently, 118 /// as if copy elision is disabled. 119 bool IsElidableCtorThatHasNotBeenElided = false; 120 121 EvalCallOptions() {} 122 }; 123 124 class ExprEngine { 125 void anchor(); 126 127 public: 128 /// The modes of inlining, which override the default analysis-wide settings. 129 enum InliningModes { 130 /// Follow the default settings for inlining callees. 131 Inline_Regular = 0, 132 133 /// Do minimal inlining of callees. 134 Inline_Minimal = 0x1 135 }; 136 137 private: 138 cross_tu::CrossTranslationUnitContext &CTU; 139 bool IsCTUEnabled; 140 141 AnalysisManager &AMgr; 142 143 AnalysisDeclContextManager &AnalysisDeclContexts; 144 145 CoreEngine Engine; 146 147 /// G - the simulation graph. 148 ExplodedGraph &G; 149 150 /// StateMgr - Object that manages the data for all created states. 151 ProgramStateManager StateMgr; 152 153 /// SymMgr - Object that manages the symbol information. 154 SymbolManager &SymMgr; 155 156 /// MRMgr - MemRegionManager object that creates memory regions. 157 MemRegionManager &MRMgr; 158 159 /// svalBuilder - SValBuilder object that creates SVals from expressions. 160 SValBuilder &svalBuilder; 161 162 unsigned int currStmtIdx = 0; 163 const NodeBuilderContext *currBldrCtx = nullptr; 164 165 /// Helper object to determine if an Objective-C message expression 166 /// implicitly never returns. 167 ObjCNoReturn ObjCNoRet; 168 169 /// The BugReporter associated with this engine. It is important that 170 /// this object be placed at the very end of member variables so that its 171 /// destructor is called before the rest of the ExprEngine is destroyed. 172 PathSensitiveBugReporter BR; 173 174 /// The functions which have been analyzed through inlining. This is owned by 175 /// AnalysisConsumer. It can be null. 176 SetOfConstDecls *VisitedCallees; 177 178 /// The flag, which specifies the mode of inlining for the engine. 179 InliningModes HowToInline; 180 181 public: 182 ExprEngine(cross_tu::CrossTranslationUnitContext &CTU, AnalysisManager &mgr, 183 SetOfConstDecls *VisitedCalleesIn, 184 FunctionSummariesTy *FS, InliningModes HowToInlineIn); 185 186 virtual ~ExprEngine() = default; 187 188 /// Returns true if there is still simulation state on the worklist. 189 bool ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) { 190 assert(L->inTopFrame()); 191 BR.setAnalysisEntryPoint(L->getDecl()); 192 return Engine.ExecuteWorkList(L, Steps, nullptr); 193 } 194 195 /// getContext - Return the ASTContext associated with this analysis. 196 ASTContext &getContext() const { return AMgr.getASTContext(); } 197 198 AnalysisManager &getAnalysisManager() { return AMgr; } 199 200 AnalysisDeclContextManager &getAnalysisDeclContextManager() { 201 return AMgr.getAnalysisDeclContextManager(); 202 } 203 204 CheckerManager &getCheckerManager() const { 205 return *AMgr.getCheckerManager(); 206 } 207 208 SValBuilder &getSValBuilder() { return svalBuilder; } 209 210 BugReporter &getBugReporter() { return BR; } 211 212 cross_tu::CrossTranslationUnitContext * 213 getCrossTranslationUnitContext() { 214 return &CTU; 215 } 216 217 const NodeBuilderContext &getBuilderContext() { 218 assert(currBldrCtx); 219 return *currBldrCtx; 220 } 221 222 const Stmt *getStmt() const; 223 224 const LocationContext *getRootLocationContext() const { 225 assert(G.roots_begin() != G.roots_end()); 226 return (*G.roots_begin())->getLocation().getLocationContext(); 227 } 228 229 CFGBlock::ConstCFGElementRef getCFGElementRef() const { 230 const CFGBlock *blockPtr = currBldrCtx ? currBldrCtx->getBlock() : nullptr; 231 return {blockPtr, currStmtIdx}; 232 } 233 234 /// Dump graph to the specified filename. 235 /// If filename is empty, generate a temporary one. 236 /// \return The filename the graph is written into. 237 std::string DumpGraph(bool trim = false, StringRef Filename=""); 238 239 /// Dump the graph consisting of the given nodes to a specified filename. 240 /// Generate a temporary filename if it's not provided. 241 /// \return The filename the graph is written into. 242 std::string DumpGraph(ArrayRef<const ExplodedNode *> Nodes, 243 StringRef Filename = ""); 244 245 /// Visualize the ExplodedGraph created by executing the simulation. 246 void ViewGraph(bool trim = false); 247 248 /// Visualize a trimmed ExplodedGraph that only contains paths to the given 249 /// nodes. 250 void ViewGraph(ArrayRef<const ExplodedNode *> Nodes); 251 252 /// getInitialState - Return the initial state used for the root vertex 253 /// in the ExplodedGraph. 254 ProgramStateRef getInitialState(const LocationContext *InitLoc); 255 256 ExplodedGraph &getGraph() { return G; } 257 const ExplodedGraph &getGraph() const { return G; } 258 259 /// Run the analyzer's garbage collection - remove dead symbols and 260 /// bindings from the state. 261 /// 262 /// Checkers can participate in this process with two callbacks: 263 /// \c checkLiveSymbols and \c checkDeadSymbols. See the CheckerDocumentation 264 /// class for more information. 265 /// 266 /// \param Node The predecessor node, from which the processing should start. 267 /// \param Out The returned set of output nodes. 268 /// \param ReferenceStmt The statement which is about to be processed. 269 /// Everything needed for this statement should be considered live. 270 /// A null statement means that everything in child LocationContexts 271 /// is dead. 272 /// \param LC The location context of the \p ReferenceStmt. A null location 273 /// context means that we have reached the end of analysis and that 274 /// all statements and local variables should be considered dead. 275 /// \param DiagnosticStmt Used as a location for any warnings that should 276 /// occur while removing the dead (e.g. leaks). By default, the 277 /// \p ReferenceStmt is used. 278 /// \param K Denotes whether this is a pre- or post-statement purge. This 279 /// must only be ProgramPoint::PostStmtPurgeDeadSymbolsKind if an 280 /// entire location context is being cleared, in which case the 281 /// \p ReferenceStmt must either be a ReturnStmt or \c NULL. Otherwise, 282 /// it must be ProgramPoint::PreStmtPurgeDeadSymbolsKind (the default) 283 /// and \p ReferenceStmt must be valid (non-null). 284 void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out, 285 const Stmt *ReferenceStmt, const LocationContext *LC, 286 const Stmt *DiagnosticStmt = nullptr, 287 ProgramPoint::Kind K = ProgramPoint::PreStmtPurgeDeadSymbolsKind); 288 289 /// A tag to track convenience transitions, which can be removed at cleanup. 290 /// This tag applies to a node created after removeDead. 291 static const ProgramPointTag *cleanupNodeTag(); 292 293 /// processCFGElement - Called by CoreEngine. Used to generate new successor 294 /// nodes by processing the 'effects' of a CFG element. 295 void processCFGElement(const CFGElement E, ExplodedNode *Pred, 296 unsigned StmtIdx, NodeBuilderContext *Ctx); 297 298 void ProcessStmt(const Stmt *S, ExplodedNode *Pred); 299 300 void ProcessLoopExit(const Stmt* S, ExplodedNode *Pred); 301 302 void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred); 303 304 void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred); 305 306 void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred); 307 308 void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D, 309 ExplodedNode *Pred, ExplodedNodeSet &Dst); 310 void ProcessDeleteDtor(const CFGDeleteDtor D, 311 ExplodedNode *Pred, ExplodedNodeSet &Dst); 312 void ProcessBaseDtor(const CFGBaseDtor D, 313 ExplodedNode *Pred, ExplodedNodeSet &Dst); 314 void ProcessMemberDtor(const CFGMemberDtor D, 315 ExplodedNode *Pred, ExplodedNodeSet &Dst); 316 void ProcessTemporaryDtor(const CFGTemporaryDtor D, 317 ExplodedNode *Pred, ExplodedNodeSet &Dst); 318 319 /// Called by CoreEngine when processing the entrance of a CFGBlock. 320 void processCFGBlockEntrance(const BlockEdge &L, 321 NodeBuilderWithSinks &nodeBuilder, 322 ExplodedNode *Pred); 323 324 /// ProcessBranch - Called by CoreEngine. Used to generate successor nodes by 325 /// processing the 'effects' of a branch condition. If the branch condition 326 /// is a loop condition, IterationsCompletedInLoop is the number of completed 327 /// iterations (otherwise it's std::nullopt). 328 void processBranch(const Stmt *Condition, NodeBuilderContext &BuilderCtx, 329 ExplodedNode *Pred, ExplodedNodeSet &Dst, 330 const CFGBlock *DstT, const CFGBlock *DstF, 331 std::optional<unsigned> IterationsCompletedInLoop); 332 333 /// Called by CoreEngine. 334 /// Used to generate successor nodes for temporary destructors depending 335 /// on whether the corresponding constructor was visited. 336 void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, 337 NodeBuilderContext &BldCtx, 338 ExplodedNode *Pred, ExplodedNodeSet &Dst, 339 const CFGBlock *DstT, 340 const CFGBlock *DstF); 341 342 /// Called by CoreEngine. Used to processing branching behavior 343 /// at static initializers. 344 void processStaticInitializer(const DeclStmt *DS, 345 NodeBuilderContext& BuilderCtx, 346 ExplodedNode *Pred, 347 ExplodedNodeSet &Dst, 348 const CFGBlock *DstT, 349 const CFGBlock *DstF); 350 351 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 352 /// nodes by processing the 'effects' of a computed goto jump. 353 void processIndirectGoto(IndirectGotoNodeBuilder& builder); 354 355 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 356 /// nodes by processing the 'effects' of a switch statement. 357 void processSwitch(SwitchNodeBuilder& builder); 358 359 /// Called by CoreEngine. Used to notify checkers that processing a 360 /// function has begun. Called for both inlined and top-level functions. 361 void processBeginOfFunction(NodeBuilderContext &BC, 362 ExplodedNode *Pred, ExplodedNodeSet &Dst, 363 const BlockEdge &L); 364 365 /// Called by CoreEngine. Used to notify checkers that processing a 366 /// function has ended. Called for both inlined and top-level functions. 367 void processEndOfFunction(NodeBuilderContext& BC, 368 ExplodedNode *Pred, 369 const ReturnStmt *RS = nullptr); 370 371 /// Remove dead bindings/symbols before exiting a function. 372 void removeDeadOnEndOfFunction(NodeBuilderContext& BC, 373 ExplodedNode *Pred, 374 ExplodedNodeSet &Dst); 375 376 /// Generate the entry node of the callee. 377 void processCallEnter(NodeBuilderContext& BC, CallEnter CE, 378 ExplodedNode *Pred); 379 380 /// Generate the sequence of nodes that simulate the call exit and the post 381 /// visit for CallExpr. 382 void processCallExit(ExplodedNode *Pred); 383 384 /// Called by CoreEngine when the analysis worklist has terminated. 385 void processEndWorklist(); 386 387 /// evalAssume - Callback function invoked by the ConstraintManager when 388 /// making assumptions about state values. 389 ProgramStateRef processAssume(ProgramStateRef state, SVal cond, 390 bool assumption); 391 392 /// processRegionChanges - Called by ProgramStateManager whenever a change is made 393 /// to the store. Used to update checkers that track region values. 394 ProgramStateRef 395 processRegionChanges(ProgramStateRef state, 396 const InvalidatedSymbols *invalidated, 397 ArrayRef<const MemRegion *> ExplicitRegions, 398 ArrayRef<const MemRegion *> Regions, 399 const LocationContext *LCtx, 400 const CallEvent *Call); 401 402 inline ProgramStateRef 403 processRegionChange(ProgramStateRef state, 404 const MemRegion* MR, 405 const LocationContext *LCtx) { 406 return processRegionChanges(state, nullptr, MR, MR, LCtx, nullptr); 407 } 408 409 /// printJson - Called by ProgramStateManager to print checker-specific data. 410 void printJson(raw_ostream &Out, ProgramStateRef State, 411 const LocationContext *LCtx, const char *NL, 412 unsigned int Space, bool IsDot) const; 413 414 ProgramStateManager &getStateManager() { return StateMgr; } 415 416 StoreManager &getStoreManager() { return StateMgr.getStoreManager(); } 417 418 ConstraintManager &getConstraintManager() { 419 return StateMgr.getConstraintManager(); 420 } 421 422 // FIXME: Remove when we migrate over to just using SValBuilder. 423 BasicValueFactory &getBasicVals() { 424 return StateMgr.getBasicVals(); 425 } 426 427 SymbolManager &getSymbolManager() { return SymMgr; } 428 MemRegionManager &getRegionManager() { return MRMgr; } 429 430 DataTag::Factory &getDataTags() { return Engine.getDataTags(); } 431 432 // Functions for external checking of whether we have unfinished work 433 bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); } 434 bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); } 435 bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); } 436 437 const CoreEngine &getCoreEngine() const { return Engine; } 438 439 public: 440 /// Visit - Transfer function logic for all statements. Dispatches to 441 /// other functions that handle specific kinds of statements. 442 void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst); 443 444 /// VisitArrayInitLoopExpr - Transfer function for array init loop. 445 void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *Ex, ExplodedNode *Pred, 446 ExplodedNodeSet &Dst); 447 448 /// VisitArraySubscriptExpr - Transfer function for array accesses. 449 void VisitArraySubscriptExpr(const ArraySubscriptExpr *Ex, 450 ExplodedNode *Pred, 451 ExplodedNodeSet &Dst); 452 453 /// VisitGCCAsmStmt - Transfer function logic for inline asm. 454 void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, 455 ExplodedNodeSet &Dst); 456 457 /// VisitMSAsmStmt - Transfer function logic for MS inline asm. 458 void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, 459 ExplodedNodeSet &Dst); 460 461 /// VisitBlockExpr - Transfer function logic for BlockExprs. 462 void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, 463 ExplodedNodeSet &Dst); 464 465 /// VisitLambdaExpr - Transfer function logic for LambdaExprs. 466 void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, 467 ExplodedNodeSet &Dst); 468 469 /// VisitBinaryOperator - Transfer function logic for binary operators. 470 void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred, 471 ExplodedNodeSet &Dst); 472 473 474 /// VisitCall - Transfer function for function calls. 475 void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, 476 ExplodedNodeSet &Dst); 477 478 /// VisitCast - Transfer function logic for all casts (implicit and explicit). 479 void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred, 480 ExplodedNodeSet &Dst); 481 482 /// VisitCompoundLiteralExpr - Transfer function logic for compound literals. 483 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, 484 ExplodedNode *Pred, ExplodedNodeSet &Dst); 485 486 /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs. 487 void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D, 488 ExplodedNode *Pred, ExplodedNodeSet &Dst); 489 490 /// VisitDeclStmt - Transfer function logic for DeclStmts. 491 void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, 492 ExplodedNodeSet &Dst); 493 494 /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose 495 void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R, 496 ExplodedNode *Pred, ExplodedNodeSet &Dst); 497 498 void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred, 499 ExplodedNodeSet &Dst); 500 501 /// VisitLogicalExpr - Transfer function logic for '&&', '||' 502 void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred, 503 ExplodedNodeSet &Dst); 504 505 /// VisitMemberExpr - Transfer function for member expressions. 506 void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 507 ExplodedNodeSet &Dst); 508 509 /// VisitAtomicExpr - Transfer function for builtin atomic expressions 510 void VisitAtomicExpr(const AtomicExpr *E, ExplodedNode *Pred, 511 ExplodedNodeSet &Dst); 512 513 /// Transfer function logic for ObjCAtSynchronizedStmts. 514 void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, 515 ExplodedNode *Pred, ExplodedNodeSet &Dst); 516 517 /// Transfer function logic for computing the lvalue of an Objective-C ivar. 518 void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred, 519 ExplodedNodeSet &Dst); 520 521 /// VisitObjCForCollectionStmt - Transfer function logic for 522 /// ObjCForCollectionStmt. 523 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, 524 ExplodedNode *Pred, ExplodedNodeSet &Dst); 525 526 void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred, 527 ExplodedNodeSet &Dst); 528 529 /// VisitReturnStmt - Transfer function logic for return statements. 530 void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred, 531 ExplodedNodeSet &Dst); 532 533 /// VisitOffsetOfExpr - Transfer function for offsetof. 534 void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred, 535 ExplodedNodeSet &Dst); 536 537 /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof. 538 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, 539 ExplodedNode *Pred, ExplodedNodeSet &Dst); 540 541 /// VisitUnaryOperator - Transfer function logic for unary operators. 542 void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred, 543 ExplodedNodeSet &Dst); 544 545 /// Handle ++ and -- (both pre- and post-increment). 546 void VisitIncrementDecrementOperator(const UnaryOperator* U, 547 ExplodedNode *Pred, 548 ExplodedNodeSet &Dst); 549 550 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, 551 ExplodedNodeSet &PreVisit, 552 ExplodedNodeSet &Dst); 553 554 void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, 555 ExplodedNodeSet &Dst); 556 557 void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, 558 ExplodedNodeSet & Dst); 559 560 void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, 561 ExplodedNodeSet &Dst); 562 563 void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E, 564 ExplodedNode *Pred, ExplodedNodeSet &Dst); 565 566 void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest, 567 const Stmt *S, bool IsBaseDtor, 568 ExplodedNode *Pred, ExplodedNodeSet &Dst, 569 EvalCallOptions &Options); 570 571 void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, 572 ExplodedNode *Pred, 573 ExplodedNodeSet &Dst); 574 575 void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, 576 ExplodedNodeSet &Dst); 577 578 void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, 579 ExplodedNodeSet &Dst); 580 581 /// Create a C++ temporary object for an rvalue. 582 void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, 583 ExplodedNode *Pred, 584 ExplodedNodeSet &Dst); 585 586 /// evalEagerlyAssumeBifurcation - Given the nodes in 'Src', eagerly assume 587 /// concrete boolean values for 'Ex', storing the resulting nodes in 'Dst'. 588 void evalEagerlyAssumeBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, 589 const Expr *Ex); 590 591 bool didEagerlyAssumeBifurcateAt(ProgramStateRef State, const Expr *Ex) const; 592 593 static std::pair<const ProgramPointTag *, const ProgramPointTag *> 594 getEagerlyAssumeBifurcationTags(); 595 596 ProgramStateRef handleLValueBitCast(ProgramStateRef state, const Expr *Ex, 597 const LocationContext *LCtx, QualType T, 598 QualType ExTy, const CastExpr *CastE, 599 StmtNodeBuilder &Bldr, 600 ExplodedNode *Pred); 601 602 void handleUOExtension(ExplodedNode *N, const UnaryOperator *U, 603 StmtNodeBuilder &Bldr); 604 605 public: 606 SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op, 607 SVal LHS, SVal RHS, QualType T) { 608 return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T); 609 } 610 611 /// Retreives which element is being constructed in a non-POD type array. 612 static std::optional<unsigned> 613 getIndexOfElementToConstruct(ProgramStateRef State, const CXXConstructExpr *E, 614 const LocationContext *LCtx); 615 616 /// Retreives which element is being destructed in a non-POD type array. 617 static std::optional<unsigned> 618 getPendingArrayDestruction(ProgramStateRef State, 619 const LocationContext *LCtx); 620 621 /// Retreives the size of the array in the pending ArrayInitLoopExpr. 622 static std::optional<unsigned> 623 getPendingInitLoop(ProgramStateRef State, const CXXConstructExpr *E, 624 const LocationContext *LCtx); 625 626 /// By looking at a certain item that may be potentially part of an object's 627 /// ConstructionContext, retrieve such object's location. A particular 628 /// statement can be transparently passed as \p Item in most cases. 629 static std::optional<SVal> 630 getObjectUnderConstruction(ProgramStateRef State, 631 const ConstructionContextItem &Item, 632 const LocationContext *LC); 633 634 /// Call PointerEscape callback when a value escapes as a result of bind. 635 ProgramStateRef processPointerEscapedOnBind( 636 ProgramStateRef State, ArrayRef<std::pair<SVal, SVal>> LocAndVals, 637 const LocationContext *LCtx, PointerEscapeKind Kind, 638 const CallEvent *Call); 639 640 /// Call PointerEscape callback when a value escapes as a result of 641 /// region invalidation. 642 /// \param[in] ITraits Specifies invalidation traits for regions/symbols. 643 ProgramStateRef notifyCheckersOfPointerEscape( 644 ProgramStateRef State, 645 const InvalidatedSymbols *Invalidated, 646 ArrayRef<const MemRegion *> ExplicitRegions, 647 const CallEvent *Call, 648 RegionAndSymbolInvalidationTraits &ITraits); 649 650 private: 651 /// evalBind - Handle the semantics of binding a value to a specific location. 652 /// This method is used by evalStore, VisitDeclStmt, and others. 653 void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred, 654 SVal location, SVal Val, bool atDeclInit = false, 655 const ProgramPoint *PP = nullptr); 656 657 ProgramStateRef 658 processPointerEscapedOnBind(ProgramStateRef State, 659 SVal Loc, SVal Val, 660 const LocationContext *LCtx); 661 662 /// A simple wrapper when you only need to notify checkers of pointer-escape 663 /// of some values. 664 ProgramStateRef escapeValues(ProgramStateRef State, ArrayRef<SVal> Vs, 665 PointerEscapeKind K, 666 const CallEvent *Call = nullptr) const; 667 668 public: 669 // FIXME: 'tag' should be removed, and a LocationContext should be used 670 // instead. 671 // FIXME: Comment on the meaning of the arguments, when 'St' may not 672 // be the same as Pred->state, and when 'location' may not be the 673 // same as state->getLValue(Ex). 674 /// Simulate a read of the result of Ex. 675 void evalLoad(ExplodedNodeSet &Dst, 676 const Expr *NodeEx, /* Eventually will be a CFGStmt */ 677 const Expr *BoundExpr, 678 ExplodedNode *Pred, 679 ProgramStateRef St, 680 SVal location, 681 const ProgramPointTag *tag = nullptr, 682 QualType LoadTy = QualType()); 683 684 // FIXME: 'tag' should be removed, and a LocationContext should be used 685 // instead. 686 void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE, 687 ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val, 688 const ProgramPointTag *tag = nullptr); 689 690 /// Return the CFG element corresponding to the worklist element 691 /// that is currently being processed by ExprEngine. 692 CFGElement getCurrentCFGElement() { 693 return (*currBldrCtx->getBlock())[currStmtIdx]; 694 } 695 696 /// Create a new state in which the call return value is binded to the 697 /// call origin expression. 698 ProgramStateRef bindReturnValue(const CallEvent &Call, 699 const LocationContext *LCtx, 700 ProgramStateRef State); 701 702 /// Evaluate a call, running pre- and post-call checkers and allowing checkers 703 /// to be responsible for handling the evaluation of the call itself. 704 void evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, 705 const CallEvent &Call); 706 707 /// Default implementation of call evaluation. 708 void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred, 709 const CallEvent &Call, 710 const EvalCallOptions &CallOpts = {}); 711 712 /// Find location of the object that is being constructed by a given 713 /// constructor. This should ideally always succeed but due to not being 714 /// fully implemented it sometimes indicates that it failed via its 715 /// out-parameter CallOpts; in such cases a fake temporary region is 716 /// returned, which is better than nothing but does not represent 717 /// the actual behavior of the program. The Idx parameter is used if we 718 /// construct an array of objects. In that case it points to the index 719 /// of the continuous memory region. 720 /// E.g.: 721 /// For `int arr[4]` this index can be 0,1,2,3. 722 /// For `int arr2[3][3]` this index can be 0,1,...,7,8. 723 /// A multi-dimensional array is also a continuous memory location in a 724 /// row major order, so for arr[0][0] Idx is 0 and for arr[2][2] Idx is 8. 725 SVal computeObjectUnderConstruction(const Expr *E, ProgramStateRef State, 726 const NodeBuilderContext *BldrCtx, 727 const LocationContext *LCtx, 728 const ConstructionContext *CC, 729 EvalCallOptions &CallOpts, 730 unsigned Idx = 0); 731 732 /// Update the program state with all the path-sensitive information 733 /// that's necessary to perform construction of an object with a given 734 /// syntactic construction context. V and CallOpts have to be obtained from 735 /// computeObjectUnderConstruction() invoked with the same set of 736 /// the remaining arguments (E, State, LCtx, CC). 737 ProgramStateRef updateObjectsUnderConstruction( 738 SVal V, const Expr *E, ProgramStateRef State, const LocationContext *LCtx, 739 const ConstructionContext *CC, const EvalCallOptions &CallOpts); 740 741 /// A convenient wrapper around computeObjectUnderConstruction 742 /// and updateObjectsUnderConstruction. 743 std::pair<ProgramStateRef, SVal> handleConstructionContext( 744 const Expr *E, ProgramStateRef State, const NodeBuilderContext *BldrCtx, 745 const LocationContext *LCtx, const ConstructionContext *CC, 746 EvalCallOptions &CallOpts, unsigned Idx = 0) { 747 748 SVal V = computeObjectUnderConstruction(E, State, BldrCtx, LCtx, CC, 749 CallOpts, Idx); 750 State = updateObjectsUnderConstruction(V, E, State, LCtx, CC, CallOpts); 751 752 return std::make_pair(State, V); 753 } 754 755 private: 756 ProgramStateRef finishArgumentConstruction(ProgramStateRef State, 757 const CallEvent &Call); 758 void finishArgumentConstruction(ExplodedNodeSet &Dst, ExplodedNode *Pred, 759 const CallEvent &Call); 760 761 void evalLocation(ExplodedNodeSet &Dst, 762 const Stmt *NodeEx, /* This will eventually be a CFGStmt */ 763 const Stmt *BoundEx, 764 ExplodedNode *Pred, 765 ProgramStateRef St, 766 SVal location, 767 bool isLoad); 768 769 /// Count the stack depth and determine if the call is recursive. 770 void examineStackFrames(const Decl *D, const LocationContext *LCtx, 771 bool &IsRecursive, unsigned &StackDepth); 772 773 enum CallInlinePolicy { 774 CIP_Allowed, 775 CIP_DisallowedOnce, 776 CIP_DisallowedAlways 777 }; 778 779 /// See if a particular call should be inlined, by only looking 780 /// at the call event and the current state of analysis. 781 CallInlinePolicy mayInlineCallKind(const CallEvent &Call, 782 const ExplodedNode *Pred, 783 AnalyzerOptions &Opts, 784 const EvalCallOptions &CallOpts); 785 786 /// See if the given AnalysisDeclContext is built for a function that we 787 /// should always inline simply because it's small enough. 788 /// Apart from "small" functions, we also have "large" functions 789 /// (cf. isLarge()), some of which are huge (cf. isHuge()), and we classify 790 /// the remaining functions as "medium". 791 bool isSmall(AnalysisDeclContext *ADC) const; 792 793 /// See if the given AnalysisDeclContext is built for a function that we 794 /// should inline carefully because it looks pretty large. 795 bool isLarge(AnalysisDeclContext *ADC) const; 796 797 /// See if the given AnalysisDeclContext is built for a function that we 798 /// should never inline because it's legit gigantic. 799 bool isHuge(AnalysisDeclContext *ADC) const; 800 801 /// See if the given AnalysisDeclContext is built for a function that we 802 /// should inline, just by looking at the declaration of the function. 803 bool mayInlineDecl(AnalysisDeclContext *ADC) const; 804 805 /// Checks our policies and decides weither the given call should be inlined. 806 bool shouldInlineCall(const CallEvent &Call, const Decl *D, 807 const ExplodedNode *Pred, 808 const EvalCallOptions &CallOpts = {}); 809 810 /// Checks whether our policies allow us to inline a non-POD type array 811 /// construction. 812 bool shouldInlineArrayConstruction(const ProgramStateRef State, 813 const CXXConstructExpr *CE, 814 const LocationContext *LCtx); 815 816 /// Checks whether our policies allow us to inline a non-POD type array 817 /// destruction. 818 /// \param Size The size of the array. 819 bool shouldInlineArrayDestruction(uint64_t Size); 820 821 /// Prepares the program state for array destruction. If no error happens 822 /// the function binds a 'PendingArrayDestruction' entry to the state, which 823 /// it returns along with the index. If any error happens (we fail to read 824 /// the size, the index would be -1, etc.) the function will return the 825 /// original state along with an index of 0. The actual element count of the 826 /// array can be accessed by the optional 'ElementCountVal' parameter. \param 827 /// State The program state. \param Region The memory region where the array 828 /// is stored. \param ElementTy The type an element in the array. \param LCty 829 /// The location context. \param ElementCountVal A pointer to an optional 830 /// SVal. If specified, the size of the array will be returned in it. It can 831 /// be Unknown. 832 std::pair<ProgramStateRef, uint64_t> prepareStateForArrayDestruction( 833 const ProgramStateRef State, const MemRegion *Region, 834 const QualType &ElementTy, const LocationContext *LCtx, 835 SVal *ElementCountVal = nullptr); 836 837 /// Checks whether we construct an array of non-POD type, and decides if the 838 /// constructor should be inkoved once again. 839 bool shouldRepeatCtorCall(ProgramStateRef State, const CXXConstructExpr *E, 840 const LocationContext *LCtx); 841 842 void inlineCall(WorkList *WList, const CallEvent &Call, const Decl *D, 843 NodeBuilder &Bldr, ExplodedNode *Pred, ProgramStateRef State); 844 845 void ctuBifurcate(const CallEvent &Call, const Decl *D, NodeBuilder &Bldr, 846 ExplodedNode *Pred, ProgramStateRef State); 847 848 /// Returns true if the CTU analysis is running its second phase. 849 bool isSecondPhaseCTU() { return IsCTUEnabled && !Engine.getCTUWorkList(); } 850 851 /// Conservatively evaluate call by invalidating regions and binding 852 /// a conjured return value. 853 void conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr, 854 ExplodedNode *Pred, ProgramStateRef State); 855 856 /// Either inline or process the call conservatively (or both), based 857 /// on DynamicDispatchBifurcation data. 858 void BifurcateCall(const MemRegion *BifurReg, 859 const CallEvent &Call, const Decl *D, NodeBuilder &Bldr, 860 ExplodedNode *Pred); 861 862 bool replayWithoutInlining(ExplodedNode *P, const LocationContext *CalleeLC); 863 864 /// Models a trivial copy or move constructor or trivial assignment operator 865 /// call with a simple bind. 866 void performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred, 867 const CallEvent &Call); 868 869 /// If the value of the given expression \p InitWithAdjustments is a NonLoc, 870 /// copy it into a new temporary object region, and replace the value of the 871 /// expression with that. 872 /// 873 /// If \p Result is provided, the new region will be bound to this expression 874 /// instead of \p InitWithAdjustments. 875 /// 876 /// Returns the temporary region with adjustments into the optional 877 /// OutRegionWithAdjustments out-parameter if a new region was indeed needed, 878 /// otherwise sets it to nullptr. 879 ProgramStateRef createTemporaryRegionIfNeeded( 880 ProgramStateRef State, const LocationContext *LC, 881 const Expr *InitWithAdjustments, const Expr *Result = nullptr, 882 const SubRegion **OutRegionWithAdjustments = nullptr); 883 884 /// Returns a region representing the `Idx`th element of a (possibly 885 /// multi-dimensional) array, for the purposes of element construction or 886 /// destruction. 887 /// 888 /// On return, \p Ty will be set to the base type of the array. 889 /// 890 /// If the type is not an array type at all, the original value is returned. 891 /// Otherwise the "IsArray" flag is set. 892 static SVal makeElementRegion(ProgramStateRef State, SVal LValue, 893 QualType &Ty, bool &IsArray, unsigned Idx = 0); 894 895 /// Common code that handles either a CXXConstructExpr or a 896 /// CXXInheritedCtorInitExpr. 897 void handleConstructor(const Expr *E, ExplodedNode *Pred, 898 ExplodedNodeSet &Dst); 899 900 public: 901 /// Note whether this loop has any more iteratios to model. These methods are 902 /// essentially an interface for a GDM trait. Further reading in 903 /// ExprEngine::VisitObjCForCollectionStmt(). 904 [[nodiscard]] static ProgramStateRef 905 setWhetherHasMoreIteration(ProgramStateRef State, 906 const ObjCForCollectionStmt *O, 907 const LocationContext *LC, bool HasMoreIteraton); 908 909 [[nodiscard]] static ProgramStateRef 910 removeIterationState(ProgramStateRef State, const ObjCForCollectionStmt *O, 911 const LocationContext *LC); 912 913 [[nodiscard]] static bool hasMoreIteration(ProgramStateRef State, 914 const ObjCForCollectionStmt *O, 915 const LocationContext *LC); 916 917 private: 918 /// Assuming we construct an array of non-POD types, this method allows us 919 /// to store which element is to be constructed next. 920 static ProgramStateRef 921 setIndexOfElementToConstruct(ProgramStateRef State, const CXXConstructExpr *E, 922 const LocationContext *LCtx, unsigned Idx); 923 924 static ProgramStateRef 925 removeIndexOfElementToConstruct(ProgramStateRef State, 926 const CXXConstructExpr *E, 927 const LocationContext *LCtx); 928 929 /// Assuming we destruct an array of non-POD types, this method allows us 930 /// to store which element is to be destructed next. 931 static ProgramStateRef setPendingArrayDestruction(ProgramStateRef State, 932 const LocationContext *LCtx, 933 unsigned Idx); 934 935 static ProgramStateRef 936 removePendingArrayDestruction(ProgramStateRef State, 937 const LocationContext *LCtx); 938 939 /// Sets the size of the array in a pending ArrayInitLoopExpr. 940 static ProgramStateRef setPendingInitLoop(ProgramStateRef State, 941 const CXXConstructExpr *E, 942 const LocationContext *LCtx, 943 unsigned Idx); 944 945 static ProgramStateRef removePendingInitLoop(ProgramStateRef State, 946 const CXXConstructExpr *E, 947 const LocationContext *LCtx); 948 949 static ProgramStateRef 950 removeStateTraitsUsedForArrayEvaluation(ProgramStateRef State, 951 const CXXConstructExpr *E, 952 const LocationContext *LCtx); 953 954 /// Store the location of a C++ object corresponding to a statement 955 /// until the statement is actually encountered. For example, if a DeclStmt 956 /// has CXXConstructExpr as its initializer, the object would be considered 957 /// to be "under construction" between CXXConstructExpr and DeclStmt. 958 /// This allows, among other things, to keep bindings to variable's fields 959 /// made within the constructor alive until its declaration actually 960 /// goes into scope. 961 static ProgramStateRef 962 addObjectUnderConstruction(ProgramStateRef State, 963 const ConstructionContextItem &Item, 964 const LocationContext *LC, SVal V); 965 966 /// Mark the object sa fully constructed, cleaning up the state trait 967 /// that tracks objects under construction. 968 static ProgramStateRef 969 finishObjectConstruction(ProgramStateRef State, 970 const ConstructionContextItem &Item, 971 const LocationContext *LC); 972 973 /// If the given expression corresponds to a temporary that was used for 974 /// passing into an elidable copy/move constructor and that constructor 975 /// was actually elided, track that we also need to elide the destructor. 976 static ProgramStateRef elideDestructor(ProgramStateRef State, 977 const CXXBindTemporaryExpr *BTE, 978 const LocationContext *LC); 979 980 /// Stop tracking the destructor that corresponds to an elided constructor. 981 static ProgramStateRef 982 cleanupElidedDestructor(ProgramStateRef State, 983 const CXXBindTemporaryExpr *BTE, 984 const LocationContext *LC); 985 986 /// Returns true if the given expression corresponds to a temporary that 987 /// was constructed for passing into an elidable copy/move constructor 988 /// and that constructor was actually elided. 989 static bool isDestructorElided(ProgramStateRef State, 990 const CXXBindTemporaryExpr *BTE, 991 const LocationContext *LC); 992 993 /// Check if all objects under construction have been fully constructed 994 /// for the given context range (including FromLC, not including ToLC). 995 /// This is useful for assertions. Also checks if elided destructors 996 /// were cleaned up. 997 static bool areAllObjectsFullyConstructed(ProgramStateRef State, 998 const LocationContext *FromLC, 999 const LocationContext *ToLC); 1000 }; 1001 1002 /// Traits for storing the call processing policy inside GDM. 1003 /// The GDM stores the corresponding CallExpr pointer. 1004 // FIXME: This does not use the nice trait macros because it must be accessible 1005 // from multiple translation units. 1006 struct ReplayWithoutInlining{}; 1007 template <> 1008 struct ProgramStateTrait<ReplayWithoutInlining> : 1009 public ProgramStatePartialTrait<const void*> { 1010 static void *GDMIndex(); 1011 }; 1012 1013 } // namespace ento 1014 1015 } // namespace clang 1016 1017 #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H 1018