1 //===- ExprEngine.h - Path-Sensitive Expression-Level Dataflow --*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines a meta-engine for path-sensitive dataflow analysis that 11 // is built on CoreEngine, but provides the boilerplate to execute transfer 12 // functions and build the ExplodedGraph at the expression level. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H 17 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H 18 19 #include "clang/AST/Expr.h" 20 #include "clang/AST/Type.h" 21 #include "clang/Analysis/CFG.h" 22 #include "clang/Analysis/DomainSpecific/ObjCNoReturn.h" 23 #include "clang/Analysis/ProgramPoint.h" 24 #include "clang/Basic/LLVM.h" 25 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 26 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 27 #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h" 28 #include "clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h" 29 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 30 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 31 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" 32 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h" 33 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" 34 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h" 35 #include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h" 36 #include "llvm/ADT/ArrayRef.h" 37 #include <cassert> 38 #include <utility> 39 40 namespace clang { 41 42 class AnalysisDeclContextManager; 43 class AnalyzerOptions; 44 class ASTContext; 45 class ConstructionContext; 46 class CXXBindTemporaryExpr; 47 class CXXCatchStmt; 48 class CXXConstructExpr; 49 class CXXDeleteExpr; 50 class CXXNewExpr; 51 class CXXThisExpr; 52 class Decl; 53 class DeclStmt; 54 class GCCAsmStmt; 55 class LambdaExpr; 56 class LocationContext; 57 class MaterializeTemporaryExpr; 58 class MSAsmStmt; 59 class NamedDecl; 60 class ObjCAtSynchronizedStmt; 61 class ObjCForCollectionStmt; 62 class ObjCIvarRefExpr; 63 class ObjCMessageExpr; 64 class ReturnStmt; 65 class Stmt; 66 67 namespace cross_tu { 68 69 class CrossTranslationUnitContext; 70 71 } // namespace cross_tu 72 73 namespace ento { 74 75 class BasicValueFactory; 76 class CallEvent; 77 class CheckerManager; 78 class ConstraintManager; 79 class CXXTempObjectRegion; 80 class MemRegion; 81 class RegionAndSymbolInvalidationTraits; 82 class SymbolManager; 83 84 class ExprEngine : public SubEngine { 85 public: 86 /// The modes of inlining, which override the default analysis-wide settings. 87 enum InliningModes { 88 /// Follow the default settings for inlining callees. 89 Inline_Regular = 0, 90 91 /// Do minimal inlining of callees. 92 Inline_Minimal = 0x1 93 }; 94 95 /// Hints for figuring out of a call should be inlined during evalCall(). 96 struct EvalCallOptions { 97 /// This call is a constructor or a destructor for which we do not currently 98 /// compute the this-region correctly. 99 bool IsCtorOrDtorWithImproperlyModeledTargetRegion = false; 100 101 /// This call is a constructor or a destructor for a single element within 102 /// an array, a part of array construction or destruction. 103 bool IsArrayCtorOrDtor = false; 104 105 /// This call is a constructor or a destructor of a temporary value. 106 bool IsTemporaryCtorOrDtor = false; 107 108 /// This call is a constructor for a temporary that is lifetime-extended 109 /// by binding it to a reference-type field within an aggregate, 110 /// for example 'A { const C &c; }; A a = { C() };' 111 bool IsTemporaryLifetimeExtendedViaAggregate = false; 112 EvalCallOptionsEvalCallOptions113 EvalCallOptions() {} 114 }; 115 116 private: 117 cross_tu::CrossTranslationUnitContext &CTU; 118 119 AnalysisManager &AMgr; 120 121 AnalysisDeclContextManager &AnalysisDeclContexts; 122 123 CoreEngine Engine; 124 125 /// G - the simulation graph. 126 ExplodedGraph &G; 127 128 /// StateMgr - Object that manages the data for all created states. 129 ProgramStateManager StateMgr; 130 131 /// SymMgr - Object that manages the symbol information. 132 SymbolManager &SymMgr; 133 134 /// svalBuilder - SValBuilder object that creates SVals from expressions. 135 SValBuilder &svalBuilder; 136 137 unsigned int currStmtIdx = 0; 138 const NodeBuilderContext *currBldrCtx = nullptr; 139 140 /// Helper object to determine if an Objective-C message expression 141 /// implicitly never returns. 142 ObjCNoReturn ObjCNoRet; 143 144 /// The BugReporter associated with this engine. It is important that 145 /// this object be placed at the very end of member variables so that its 146 /// destructor is called before the rest of the ExprEngine is destroyed. 147 GRBugReporter BR; 148 149 /// The functions which have been analyzed through inlining. This is owned by 150 /// AnalysisConsumer. It can be null. 151 SetOfConstDecls *VisitedCallees; 152 153 /// The flag, which specifies the mode of inlining for the engine. 154 InliningModes HowToInline; 155 156 public: 157 ExprEngine(cross_tu::CrossTranslationUnitContext &CTU, AnalysisManager &mgr, 158 SetOfConstDecls *VisitedCalleesIn, 159 FunctionSummariesTy *FS, InliningModes HowToInlineIn); 160 161 ~ExprEngine() override; 162 163 /// Returns true if there is still simulation state on the worklist. 164 bool ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) { 165 return Engine.ExecuteWorkList(L, Steps, nullptr); 166 } 167 168 /// Execute the work list with an initial state. Nodes that reaches the exit 169 /// of the function are added into the Dst set, which represent the exit 170 /// state of the function call. Returns true if there is still simulation 171 /// state on the worklist. ExecuteWorkListWithInitialState(const LocationContext * L,unsigned Steps,ProgramStateRef InitState,ExplodedNodeSet & Dst)172 bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps, 173 ProgramStateRef InitState, 174 ExplodedNodeSet &Dst) { 175 return Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst); 176 } 177 178 /// getContext - Return the ASTContext associated with this analysis. getContext()179 ASTContext &getContext() const { return AMgr.getASTContext(); } 180 getAnalysisManager()181 AnalysisManager &getAnalysisManager() override { return AMgr; } 182 getCheckerManager()183 CheckerManager &getCheckerManager() const { 184 return *AMgr.getCheckerManager(); 185 } 186 getSValBuilder()187 SValBuilder &getSValBuilder() { return svalBuilder; } 188 getBugReporter()189 BugReporter &getBugReporter() { return BR; } 190 191 cross_tu::CrossTranslationUnitContext * getCrossTranslationUnitContext()192 getCrossTranslationUnitContext() override { 193 return &CTU; 194 } 195 getBuilderContext()196 const NodeBuilderContext &getBuilderContext() { 197 assert(currBldrCtx); 198 return *currBldrCtx; 199 } 200 201 const Stmt *getStmt() const; 202 203 void GenerateAutoTransition(ExplodedNode *N); 204 void enqueueEndOfPath(ExplodedNodeSet &S); 205 void GenerateCallExitNode(ExplodedNode *N); 206 207 208 /// Dump graph to the specified filename. 209 /// If filename is empty, generate a temporary one. 210 /// \return The filename the graph is written into. 211 std::string DumpGraph(bool trim = false, StringRef Filename=""); 212 213 /// Dump the graph consisting of the given nodes to a specified filename. 214 /// Generate a temporary filename if it's not provided. 215 /// \return The filename the graph is written into. 216 std::string DumpGraph(ArrayRef<const ExplodedNode *> Nodes, 217 StringRef Filename = ""); 218 219 /// Visualize the ExplodedGraph created by executing the simulation. 220 void ViewGraph(bool trim = false); 221 222 /// Visualize a trimmed ExplodedGraph that only contains paths to the given 223 /// nodes. 224 void ViewGraph(ArrayRef<const ExplodedNode *> Nodes); 225 226 /// getInitialState - Return the initial state used for the root vertex 227 /// in the ExplodedGraph. 228 ProgramStateRef getInitialState(const LocationContext *InitLoc) override; 229 getGraph()230 ExplodedGraph &getGraph() { return G; } getGraph()231 const ExplodedGraph &getGraph() const { return G; } 232 233 /// Run the analyzer's garbage collection - remove dead symbols and 234 /// bindings from the state. 235 /// 236 /// Checkers can participate in this process with two callbacks: 237 /// \c checkLiveSymbols and \c checkDeadSymbols. See the CheckerDocumentation 238 /// class for more information. 239 /// 240 /// \param Node The predecessor node, from which the processing should start. 241 /// \param Out The returned set of output nodes. 242 /// \param ReferenceStmt The statement which is about to be processed. 243 /// Everything needed for this statement should be considered live. 244 /// A null statement means that everything in child LocationContexts 245 /// is dead. 246 /// \param LC The location context of the \p ReferenceStmt. A null location 247 /// context means that we have reached the end of analysis and that 248 /// all statements and local variables should be considered dead. 249 /// \param DiagnosticStmt Used as a location for any warnings that should 250 /// occur while removing the dead (e.g. leaks). By default, the 251 /// \p ReferenceStmt is used. 252 /// \param K Denotes whether this is a pre- or post-statement purge. This 253 /// must only be ProgramPoint::PostStmtPurgeDeadSymbolsKind if an 254 /// entire location context is being cleared, in which case the 255 /// \p ReferenceStmt must either be a ReturnStmt or \c NULL. Otherwise, 256 /// it must be ProgramPoint::PreStmtPurgeDeadSymbolsKind (the default) 257 /// and \p ReferenceStmt must be valid (non-null). 258 void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out, 259 const Stmt *ReferenceStmt, const LocationContext *LC, 260 const Stmt *DiagnosticStmt = nullptr, 261 ProgramPoint::Kind K = ProgramPoint::PreStmtPurgeDeadSymbolsKind); 262 263 /// processCFGElement - Called by CoreEngine. Used to generate new successor 264 /// nodes by processing the 'effects' of a CFG element. 265 void processCFGElement(const CFGElement E, ExplodedNode *Pred, 266 unsigned StmtIdx, NodeBuilderContext *Ctx) override; 267 268 void ProcessStmt(const Stmt *S, ExplodedNode *Pred); 269 270 void ProcessLoopExit(const Stmt* S, ExplodedNode *Pred); 271 272 void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred); 273 274 void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred); 275 276 void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred); 277 278 void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D, 279 ExplodedNode *Pred, ExplodedNodeSet &Dst); 280 void ProcessDeleteDtor(const CFGDeleteDtor D, 281 ExplodedNode *Pred, ExplodedNodeSet &Dst); 282 void ProcessBaseDtor(const CFGBaseDtor D, 283 ExplodedNode *Pred, ExplodedNodeSet &Dst); 284 void ProcessMemberDtor(const CFGMemberDtor D, 285 ExplodedNode *Pred, ExplodedNodeSet &Dst); 286 void ProcessTemporaryDtor(const CFGTemporaryDtor D, 287 ExplodedNode *Pred, ExplodedNodeSet &Dst); 288 289 /// Called by CoreEngine when processing the entrance of a CFGBlock. 290 void processCFGBlockEntrance(const BlockEdge &L, 291 NodeBuilderWithSinks &nodeBuilder, 292 ExplodedNode *Pred) override; 293 294 /// ProcessBranch - Called by CoreEngine. Used to generate successor 295 /// nodes by processing the 'effects' of a branch condition. 296 void processBranch(const Stmt *Condition, 297 NodeBuilderContext& BuilderCtx, 298 ExplodedNode *Pred, 299 ExplodedNodeSet &Dst, 300 const CFGBlock *DstT, 301 const CFGBlock *DstF) override; 302 303 /// Called by CoreEngine. 304 /// Used to generate successor nodes for temporary destructors depending 305 /// on whether the corresponding constructor was visited. 306 void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, 307 NodeBuilderContext &BldCtx, 308 ExplodedNode *Pred, ExplodedNodeSet &Dst, 309 const CFGBlock *DstT, 310 const CFGBlock *DstF) override; 311 312 /// Called by CoreEngine. Used to processing branching behavior 313 /// at static initializers. 314 void processStaticInitializer(const DeclStmt *DS, 315 NodeBuilderContext& BuilderCtx, 316 ExplodedNode *Pred, 317 ExplodedNodeSet &Dst, 318 const CFGBlock *DstT, 319 const CFGBlock *DstF) override; 320 321 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 322 /// nodes by processing the 'effects' of a computed goto jump. 323 void processIndirectGoto(IndirectGotoNodeBuilder& builder) override; 324 325 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 326 /// nodes by processing the 'effects' of a switch statement. 327 void processSwitch(SwitchNodeBuilder& builder) override; 328 329 /// Called by CoreEngine. Used to notify checkers that processing a 330 /// function has begun. Called for both inlined and and top-level functions. 331 void processBeginOfFunction(NodeBuilderContext &BC, 332 ExplodedNode *Pred, ExplodedNodeSet &Dst, 333 const BlockEdge &L) override; 334 335 /// Called by CoreEngine. Used to notify checkers that processing a 336 /// function has ended. Called for both inlined and and top-level functions. 337 void processEndOfFunction(NodeBuilderContext& BC, 338 ExplodedNode *Pred, 339 const ReturnStmt *RS = nullptr) override; 340 341 /// Remove dead bindings/symbols before exiting a function. 342 void removeDeadOnEndOfFunction(NodeBuilderContext& BC, 343 ExplodedNode *Pred, 344 ExplodedNodeSet &Dst); 345 346 /// Generate the entry node of the callee. 347 void processCallEnter(NodeBuilderContext& BC, CallEnter CE, 348 ExplodedNode *Pred) override; 349 350 /// Generate the sequence of nodes that simulate the call exit and the post 351 /// visit for CallExpr. 352 void processCallExit(ExplodedNode *Pred) override; 353 354 /// Called by CoreEngine when the analysis worklist has terminated. 355 void processEndWorklist() override; 356 357 /// evalAssume - Callback function invoked by the ConstraintManager when 358 /// making assumptions about state values. 359 ProgramStateRef processAssume(ProgramStateRef state, SVal cond, 360 bool assumption) override; 361 362 /// processRegionChanges - Called by ProgramStateManager whenever a change is made 363 /// to the store. Used to update checkers that track region values. 364 ProgramStateRef 365 processRegionChanges(ProgramStateRef state, 366 const InvalidatedSymbols *invalidated, 367 ArrayRef<const MemRegion *> ExplicitRegions, 368 ArrayRef<const MemRegion *> Regions, 369 const LocationContext *LCtx, 370 const CallEvent *Call) override; 371 372 /// printState - Called by ProgramStateManager to print checker-specific data. 373 void printState(raw_ostream &Out, ProgramStateRef State, const char *NL, 374 const char *Sep, 375 const LocationContext *LCtx = nullptr) override; 376 getStateManager()377 ProgramStateManager &getStateManager() override { return StateMgr; } 378 getStoreManager()379 StoreManager &getStoreManager() { return StateMgr.getStoreManager(); } 380 getConstraintManager()381 ConstraintManager &getConstraintManager() { 382 return StateMgr.getConstraintManager(); 383 } 384 385 // FIXME: Remove when we migrate over to just using SValBuilder. getBasicVals()386 BasicValueFactory &getBasicVals() { 387 return StateMgr.getBasicVals(); 388 } 389 390 // FIXME: Remove when we migrate over to just using ValueManager. getSymbolManager()391 SymbolManager &getSymbolManager() { return SymMgr; } getSymbolManager()392 const SymbolManager &getSymbolManager() const { return SymMgr; } 393 394 // Functions for external checking of whether we have unfinished work wasBlocksExhausted()395 bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); } hasEmptyWorkList()396 bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); } hasWorkRemaining()397 bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); } 398 getCoreEngine()399 const CoreEngine &getCoreEngine() const { return Engine; } 400 401 public: 402 /// Visit - Transfer function logic for all statements. Dispatches to 403 /// other functions that handle specific kinds of statements. 404 void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst); 405 406 /// VisitArraySubscriptExpr - Transfer function for array accesses. 407 void VisitArraySubscriptExpr(const ArraySubscriptExpr *Ex, 408 ExplodedNode *Pred, 409 ExplodedNodeSet &Dst); 410 411 /// VisitGCCAsmStmt - Transfer function logic for inline asm. 412 void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, 413 ExplodedNodeSet &Dst); 414 415 /// VisitMSAsmStmt - Transfer function logic for MS inline asm. 416 void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, 417 ExplodedNodeSet &Dst); 418 419 /// VisitBlockExpr - Transfer function logic for BlockExprs. 420 void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, 421 ExplodedNodeSet &Dst); 422 423 /// VisitLambdaExpr - Transfer function logic for LambdaExprs. 424 void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, 425 ExplodedNodeSet &Dst); 426 427 /// VisitBinaryOperator - Transfer function logic for binary operators. 428 void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred, 429 ExplodedNodeSet &Dst); 430 431 432 /// VisitCall - Transfer function for function calls. 433 void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, 434 ExplodedNodeSet &Dst); 435 436 /// VisitCast - Transfer function logic for all casts (implicit and explicit). 437 void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred, 438 ExplodedNodeSet &Dst); 439 440 /// VisitCompoundLiteralExpr - Transfer function logic for compound literals. 441 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, 442 ExplodedNode *Pred, ExplodedNodeSet &Dst); 443 444 /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs. 445 void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D, 446 ExplodedNode *Pred, ExplodedNodeSet &Dst); 447 448 /// VisitDeclStmt - Transfer function logic for DeclStmts. 449 void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, 450 ExplodedNodeSet &Dst); 451 452 /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose 453 void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R, 454 ExplodedNode *Pred, ExplodedNodeSet &Dst); 455 456 void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred, 457 ExplodedNodeSet &Dst); 458 459 /// VisitLogicalExpr - Transfer function logic for '&&', '||' 460 void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred, 461 ExplodedNodeSet &Dst); 462 463 /// VisitMemberExpr - Transfer function for member expressions. 464 void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 465 ExplodedNodeSet &Dst); 466 467 /// VisitAtomicExpr - Transfer function for builtin atomic expressions 468 void VisitAtomicExpr(const AtomicExpr *E, ExplodedNode *Pred, 469 ExplodedNodeSet &Dst); 470 471 /// Transfer function logic for ObjCAtSynchronizedStmts. 472 void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, 473 ExplodedNode *Pred, ExplodedNodeSet &Dst); 474 475 /// Transfer function logic for computing the lvalue of an Objective-C ivar. 476 void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred, 477 ExplodedNodeSet &Dst); 478 479 /// VisitObjCForCollectionStmt - Transfer function logic for 480 /// ObjCForCollectionStmt. 481 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, 482 ExplodedNode *Pred, ExplodedNodeSet &Dst); 483 484 void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred, 485 ExplodedNodeSet &Dst); 486 487 /// VisitReturnStmt - Transfer function logic for return statements. 488 void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred, 489 ExplodedNodeSet &Dst); 490 491 /// VisitOffsetOfExpr - Transfer function for offsetof. 492 void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred, 493 ExplodedNodeSet &Dst); 494 495 /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof. 496 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, 497 ExplodedNode *Pred, ExplodedNodeSet &Dst); 498 499 /// VisitUnaryOperator - Transfer function logic for unary operators. 500 void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred, 501 ExplodedNodeSet &Dst); 502 503 /// Handle ++ and -- (both pre- and post-increment). 504 void VisitIncrementDecrementOperator(const UnaryOperator* U, 505 ExplodedNode *Pred, 506 ExplodedNodeSet &Dst); 507 508 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, 509 ExplodedNodeSet &PreVisit, 510 ExplodedNodeSet &Dst); 511 512 void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, 513 ExplodedNodeSet &Dst); 514 515 void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, 516 ExplodedNodeSet & Dst); 517 518 void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, 519 ExplodedNodeSet &Dst); 520 521 void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest, 522 const Stmt *S, bool IsBaseDtor, 523 ExplodedNode *Pred, ExplodedNodeSet &Dst, 524 const EvalCallOptions &Options); 525 526 void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, 527 ExplodedNode *Pred, 528 ExplodedNodeSet &Dst); 529 530 void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, 531 ExplodedNodeSet &Dst); 532 533 void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, 534 ExplodedNodeSet &Dst); 535 536 /// Create a C++ temporary object for an rvalue. 537 void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, 538 ExplodedNode *Pred, 539 ExplodedNodeSet &Dst); 540 541 /// evalEagerlyAssumeBinOpBifurcation - Given the nodes in 'Src', eagerly assume symbolic 542 /// expressions of the form 'x != 0' and generate new nodes (stored in Dst) 543 /// with those assumptions. 544 void evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, 545 const Expr *Ex); 546 547 static std::pair<const ProgramPointTag *, const ProgramPointTag *> 548 geteagerlyAssumeBinOpBifurcationTags(); 549 evalMinus(SVal X)550 SVal evalMinus(SVal X) { 551 return X.isValid() ? svalBuilder.evalMinus(X.castAs<NonLoc>()) : X; 552 } 553 evalComplement(SVal X)554 SVal evalComplement(SVal X) { 555 return X.isValid() ? svalBuilder.evalComplement(X.castAs<NonLoc>()) : X; 556 } 557 558 ProgramStateRef handleLValueBitCast(ProgramStateRef state, const Expr *Ex, 559 const LocationContext *LCtx, QualType T, 560 QualType ExTy, const CastExpr *CastE, 561 StmtNodeBuilder &Bldr, 562 ExplodedNode *Pred); 563 564 ProgramStateRef handleLVectorSplat(ProgramStateRef state, 565 const LocationContext *LCtx, 566 const CastExpr *CastE, 567 StmtNodeBuilder &Bldr, 568 ExplodedNode *Pred); 569 570 void handleUOExtension(ExplodedNodeSet::iterator I, 571 const UnaryOperator* U, 572 StmtNodeBuilder &Bldr); 573 574 public: evalBinOp(ProgramStateRef state,BinaryOperator::Opcode op,NonLoc L,NonLoc R,QualType T)575 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, 576 NonLoc L, NonLoc R, QualType T) { 577 return svalBuilder.evalBinOpNN(state, op, L, R, T); 578 } 579 evalBinOp(ProgramStateRef state,BinaryOperator::Opcode op,NonLoc L,SVal R,QualType T)580 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, 581 NonLoc L, SVal R, QualType T) { 582 return R.isValid() ? svalBuilder.evalBinOpNN(state, op, L, 583 R.castAs<NonLoc>(), T) : R; 584 } 585 evalBinOp(ProgramStateRef ST,BinaryOperator::Opcode Op,SVal LHS,SVal RHS,QualType T)586 SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op, 587 SVal LHS, SVal RHS, QualType T) { 588 return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T); 589 } 590 591 /// By looking at a certain item that may be potentially part of an object's 592 /// ConstructionContext, retrieve such object's location. A particular 593 /// statement can be transparently passed as \p Item in most cases. 594 static Optional<SVal> 595 getObjectUnderConstruction(ProgramStateRef State, 596 const ConstructionContextItem &Item, 597 const LocationContext *LC); 598 599 protected: 600 /// evalBind - Handle the semantics of binding a value to a specific location. 601 /// This method is used by evalStore, VisitDeclStmt, and others. 602 void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred, 603 SVal location, SVal Val, bool atDeclInit = false, 604 const ProgramPoint *PP = nullptr); 605 606 /// Call PointerEscape callback when a value escapes as a result of bind. 607 ProgramStateRef processPointerEscapedOnBind(ProgramStateRef State, 608 SVal Loc, 609 SVal Val, 610 const LocationContext *LCtx) override; 611 /// Call PointerEscape callback when a value escapes as a result of 612 /// region invalidation. 613 /// \param[in] ITraits Specifies invalidation traits for regions/symbols. 614 ProgramStateRef notifyCheckersOfPointerEscape( 615 ProgramStateRef State, 616 const InvalidatedSymbols *Invalidated, 617 ArrayRef<const MemRegion *> ExplicitRegions, 618 const CallEvent *Call, 619 RegionAndSymbolInvalidationTraits &ITraits) override; 620 621 /// A simple wrapper when you only need to notify checkers of pointer-escape 622 /// of a single value. 623 ProgramStateRef escapeValue(ProgramStateRef State, SVal V, 624 PointerEscapeKind K) const; 625 626 public: 627 // FIXME: 'tag' should be removed, and a LocationContext should be used 628 // instead. 629 // FIXME: Comment on the meaning of the arguments, when 'St' may not 630 // be the same as Pred->state, and when 'location' may not be the 631 // same as state->getLValue(Ex). 632 /// Simulate a read of the result of Ex. 633 void evalLoad(ExplodedNodeSet &Dst, 634 const Expr *NodeEx, /* Eventually will be a CFGStmt */ 635 const Expr *BoundExpr, 636 ExplodedNode *Pred, 637 ProgramStateRef St, 638 SVal location, 639 const ProgramPointTag *tag = nullptr, 640 QualType LoadTy = QualType()); 641 642 // FIXME: 'tag' should be removed, and a LocationContext should be used 643 // instead. 644 void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE, 645 ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val, 646 const ProgramPointTag *tag = nullptr); 647 648 /// Return the CFG element corresponding to the worklist element 649 /// that is currently being processed by ExprEngine. getCurrentCFGElement()650 CFGElement getCurrentCFGElement() { 651 return (*currBldrCtx->getBlock())[currStmtIdx]; 652 } 653 654 /// Create a new state in which the call return value is binded to the 655 /// call origin expression. 656 ProgramStateRef bindReturnValue(const CallEvent &Call, 657 const LocationContext *LCtx, 658 ProgramStateRef State); 659 660 /// Evaluate a call, running pre- and post-call checks and allowing checkers 661 /// to be responsible for handling the evaluation of the call itself. 662 void evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, 663 const CallEvent &Call); 664 665 /// Default implementation of call evaluation. 666 void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred, 667 const CallEvent &Call, 668 const EvalCallOptions &CallOpts = {}); 669 670 private: 671 ProgramStateRef finishArgumentConstruction(ProgramStateRef State, 672 const CallEvent &Call); 673 void finishArgumentConstruction(ExplodedNodeSet &Dst, ExplodedNode *Pred, 674 const CallEvent &Call); 675 676 void evalLoadCommon(ExplodedNodeSet &Dst, 677 const Expr *NodeEx, /* Eventually will be a CFGStmt */ 678 const Expr *BoundEx, 679 ExplodedNode *Pred, 680 ProgramStateRef St, 681 SVal location, 682 const ProgramPointTag *tag, 683 QualType LoadTy); 684 685 void evalLocation(ExplodedNodeSet &Dst, 686 const Stmt *NodeEx, /* This will eventually be a CFGStmt */ 687 const Stmt *BoundEx, 688 ExplodedNode *Pred, 689 ProgramStateRef St, 690 SVal location, 691 bool isLoad); 692 693 /// Count the stack depth and determine if the call is recursive. 694 void examineStackFrames(const Decl *D, const LocationContext *LCtx, 695 bool &IsRecursive, unsigned &StackDepth); 696 697 enum CallInlinePolicy { 698 CIP_Allowed, 699 CIP_DisallowedOnce, 700 CIP_DisallowedAlways 701 }; 702 703 /// See if a particular call should be inlined, by only looking 704 /// at the call event and the current state of analysis. 705 CallInlinePolicy mayInlineCallKind(const CallEvent &Call, 706 const ExplodedNode *Pred, 707 AnalyzerOptions &Opts, 708 const EvalCallOptions &CallOpts); 709 710 /// Checks our policies and decides weither the given call should be inlined. 711 bool shouldInlineCall(const CallEvent &Call, const Decl *D, 712 const ExplodedNode *Pred, 713 const EvalCallOptions &CallOpts = {}); 714 715 bool inlineCall(const CallEvent &Call, const Decl *D, NodeBuilder &Bldr, 716 ExplodedNode *Pred, ProgramStateRef State); 717 718 /// Conservatively evaluate call by invalidating regions and binding 719 /// a conjured return value. 720 void conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr, 721 ExplodedNode *Pred, ProgramStateRef State); 722 723 /// Either inline or process the call conservatively (or both), based 724 /// on DynamicDispatchBifurcation data. 725 void BifurcateCall(const MemRegion *BifurReg, 726 const CallEvent &Call, const Decl *D, NodeBuilder &Bldr, 727 ExplodedNode *Pred); 728 729 bool replayWithoutInlining(ExplodedNode *P, const LocationContext *CalleeLC); 730 731 /// Models a trivial copy or move constructor or trivial assignment operator 732 /// call with a simple bind. 733 void performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred, 734 const CallEvent &Call); 735 736 /// If the value of the given expression \p InitWithAdjustments is a NonLoc, 737 /// copy it into a new temporary object region, and replace the value of the 738 /// expression with that. 739 /// 740 /// If \p Result is provided, the new region will be bound to this expression 741 /// instead of \p InitWithAdjustments. 742 /// 743 /// Returns the temporary region with adjustments into the optional 744 /// OutRegionWithAdjustments out-parameter if a new region was indeed needed, 745 /// otherwise sets it to nullptr. 746 ProgramStateRef createTemporaryRegionIfNeeded( 747 ProgramStateRef State, const LocationContext *LC, 748 const Expr *InitWithAdjustments, const Expr *Result = nullptr, 749 const SubRegion **OutRegionWithAdjustments = nullptr); 750 751 /// Returns a region representing the first element of a (possibly 752 /// multi-dimensional) array, for the purposes of element construction or 753 /// destruction. 754 /// 755 /// On return, \p Ty will be set to the base type of the array. 756 /// 757 /// If the type is not an array type at all, the original value is returned. 758 /// Otherwise the "IsArray" flag is set. 759 static SVal makeZeroElementRegion(ProgramStateRef State, SVal LValue, 760 QualType &Ty, bool &IsArray); 761 762 /// For a DeclStmt or CXXInitCtorInitializer, walk backward in the current CFG 763 /// block to find the constructor expression that directly constructed into 764 /// the storage for this statement. Returns null if the constructor for this 765 /// statement created a temporary object region rather than directly 766 /// constructing into an existing region. 767 const CXXConstructExpr *findDirectConstructorForCurrentCFGElement(); 768 769 /// Update the program state with all the path-sensitive information 770 /// that's necessary to perform construction of an object with a given 771 /// syntactic construction context. If the construction context is unavailable 772 /// or unusable for any reason, a dummy temporary region is returned, and the 773 /// IsConstructorWithImproperlyModeledTargetRegion flag is set in \p CallOpts. 774 /// Returns the updated program state and the new object's this-region. 775 std::pair<ProgramStateRef, SVal> prepareForObjectConstruction( 776 const Expr *E, ProgramStateRef State, const LocationContext *LCtx, 777 const ConstructionContext *CC, EvalCallOptions &CallOpts); 778 779 /// Store the location of a C++ object corresponding to a statement 780 /// until the statement is actually encountered. For example, if a DeclStmt 781 /// has CXXConstructExpr as its initializer, the object would be considered 782 /// to be "under construction" between CXXConstructExpr and DeclStmt. 783 /// This allows, among other things, to keep bindings to variable's fields 784 /// made within the constructor alive until its declaration actually 785 /// goes into scope. 786 static ProgramStateRef 787 addObjectUnderConstruction(ProgramStateRef State, 788 const ConstructionContextItem &Item, 789 const LocationContext *LC, SVal V); 790 791 /// Mark the object sa fully constructed, cleaning up the state trait 792 /// that tracks objects under construction. 793 static ProgramStateRef 794 finishObjectConstruction(ProgramStateRef State, 795 const ConstructionContextItem &Item, 796 const LocationContext *LC); 797 798 /// If the given expression corresponds to a temporary that was used for 799 /// passing into an elidable copy/move constructor and that constructor 800 /// was actually elided, track that we also need to elide the destructor. 801 static ProgramStateRef elideDestructor(ProgramStateRef State, 802 const CXXBindTemporaryExpr *BTE, 803 const LocationContext *LC); 804 805 /// Stop tracking the destructor that corresponds to an elided constructor. 806 static ProgramStateRef 807 cleanupElidedDestructor(ProgramStateRef State, 808 const CXXBindTemporaryExpr *BTE, 809 const LocationContext *LC); 810 811 /// Returns true if the given expression corresponds to a temporary that 812 /// was constructed for passing into an elidable copy/move constructor 813 /// and that constructor was actually elided. 814 static bool isDestructorElided(ProgramStateRef State, 815 const CXXBindTemporaryExpr *BTE, 816 const LocationContext *LC); 817 818 /// Check if all objects under construction have been fully constructed 819 /// for the given context range (including FromLC, not including ToLC). 820 /// This is useful for assertions. Also checks if elided destructors 821 /// were cleaned up. 822 static bool areAllObjectsFullyConstructed(ProgramStateRef State, 823 const LocationContext *FromLC, 824 const LocationContext *ToLC); 825 }; 826 827 /// Traits for storing the call processing policy inside GDM. 828 /// The GDM stores the corresponding CallExpr pointer. 829 // FIXME: This does not use the nice trait macros because it must be accessible 830 // from multiple translation units. 831 struct ReplayWithoutInlining{}; 832 template <> 833 struct ProgramStateTrait<ReplayWithoutInlining> : 834 public ProgramStatePartialTrait<const void*> { 835 static void *GDMIndex(); 836 }; 837 838 } // namespace ento 839 840 } // namespace clang 841 842 #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H 843