1 //===- CallEvent.h - Wrapper for all function and method calls --*- 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 /// \file This file defines CallEvent and its subclasses, which represent path- 10 /// sensitive instances of different kinds of function and method calls 11 /// (C, C++, and Objective-C). 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H 16 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H 17 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclBase.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/Stmt.h" 26 #include "clang/AST/Type.h" 27 #include "clang/Basic/IdentifierTable.h" 28 #include "clang/Basic/LLVM.h" 29 #include "clang/Basic/SourceLocation.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 32 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 33 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" 34 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" 35 #include "llvm/ADT/ArrayRef.h" 36 #include "llvm/ADT/IntrusiveRefCntPtr.h" 37 #include "llvm/ADT/PointerIntPair.h" 38 #include "llvm/ADT/PointerUnion.h" 39 #include "llvm/ADT/STLExtras.h" 40 #include "llvm/ADT/SmallVector.h" 41 #include "llvm/ADT/StringRef.h" 42 #include "llvm/ADT/iterator_range.h" 43 #include "llvm/Support/Allocator.h" 44 #include "llvm/Support/Casting.h" 45 #include "llvm/Support/ErrorHandling.h" 46 #include <cassert> 47 #include <limits> 48 #include <utility> 49 50 namespace clang { 51 52 class LocationContext; 53 class ProgramPoint; 54 class ProgramPointTag; 55 class StackFrameContext; 56 57 namespace ento { 58 59 enum CallEventKind { 60 CE_Function, 61 CE_CXXMember, 62 CE_CXXMemberOperator, 63 CE_CXXDestructor, 64 CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember, 65 CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor, 66 CE_CXXConstructor, 67 CE_CXXInheritedConstructor, 68 CE_BEG_CXX_CONSTRUCTOR_CALLS = CE_CXXConstructor, 69 CE_END_CXX_CONSTRUCTOR_CALLS = CE_CXXInheritedConstructor, 70 CE_CXXAllocator, 71 CE_CXXDeallocator, 72 CE_BEG_FUNCTION_CALLS = CE_Function, 73 CE_END_FUNCTION_CALLS = CE_CXXDeallocator, 74 CE_Block, 75 CE_ObjCMessage 76 }; 77 78 class CallEvent; 79 class CallDescription; 80 81 template<typename T = CallEvent> 82 class CallEventRef : public IntrusiveRefCntPtr<const T> { 83 public: 84 CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {} 85 CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {} 86 87 CallEventRef<T> cloneWithState(ProgramStateRef State) const { 88 return this->get()->template cloneWithState<T>(State); 89 } 90 91 // Allow implicit conversions to a superclass type, since CallEventRef 92 // behaves like a pointer-to-const. 93 template <typename SuperT> 94 operator CallEventRef<SuperT> () const { 95 return this->get(); 96 } 97 }; 98 99 /// \class RuntimeDefinition 100 /// Defines the runtime definition of the called function. 101 /// 102 /// Encapsulates the information we have about which Decl will be used 103 /// when the call is executed on the given path. When dealing with dynamic 104 /// dispatch, the information is based on DynamicTypeInfo and might not be 105 /// precise. 106 class RuntimeDefinition { 107 /// The Declaration of the function which could be called at runtime. 108 /// NULL if not available. 109 const Decl *D = nullptr; 110 111 /// The region representing an object (ObjC/C++) on which the method is 112 /// called. With dynamic dispatch, the method definition depends on the 113 /// runtime type of this object. NULL when the DynamicTypeInfo is 114 /// precise. 115 const MemRegion *R = nullptr; 116 117 public: 118 RuntimeDefinition() = default; 119 RuntimeDefinition(const Decl *InD): D(InD) {} 120 RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {} 121 122 const Decl *getDecl() { return D; } 123 124 /// Check if the definition we have is precise. 125 /// If not, it is possible that the call dispatches to another definition at 126 /// execution time. 127 bool mayHaveOtherDefinitions() { return R != nullptr; } 128 129 /// When other definitions are possible, returns the region whose runtime type 130 /// determines the method definition. 131 const MemRegion *getDispatchRegion() { return R; } 132 }; 133 134 /// Represents an abstract call to a function or method along a 135 /// particular path. 136 /// 137 /// CallEvents are created through the factory methods of CallEventManager. 138 /// 139 /// CallEvents should always be cheap to create and destroy. In order for 140 /// CallEventManager to be able to re-use CallEvent-sized memory blocks, 141 /// subclasses of CallEvent may not add any data members to the base class. 142 /// Use the "Data" and "Location" fields instead. 143 class CallEvent { 144 public: 145 using Kind = CallEventKind; 146 147 private: 148 ProgramStateRef State; 149 const LocationContext *LCtx; 150 llvm::PointerUnion<const Expr *, const Decl *> Origin; 151 152 protected: 153 // This is user data for subclasses. 154 const void *Data; 155 156 // This is user data for subclasses. 157 // This should come right before RefCount, so that the two fields can be 158 // packed together on LP64 platforms. 159 SourceLocation Location; 160 161 private: 162 template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo; 163 164 mutable unsigned RefCount = 0; 165 166 void Retain() const { ++RefCount; } 167 void Release() const; 168 169 protected: 170 friend class CallEventManager; 171 172 CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx) 173 : State(std::move(state)), LCtx(lctx), Origin(E) {} 174 175 CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx) 176 : State(std::move(state)), LCtx(lctx), Origin(D) {} 177 178 // DO NOT MAKE PUBLIC 179 CallEvent(const CallEvent &Original) 180 : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin), 181 Data(Original.Data), Location(Original.Location) {} 182 183 /// Copies this CallEvent, with vtable intact, into a new block of memory. 184 virtual void cloneTo(void *Dest) const = 0; 185 186 /// Get the value of arbitrary expressions at this point in the path. 187 SVal getSVal(const Stmt *S) const { 188 return getState()->getSVal(S, getLocationContext()); 189 } 190 191 using ValueList = SmallVectorImpl<SVal>; 192 193 /// Used to specify non-argument regions that will be invalidated as a 194 /// result of this call. 195 virtual void getExtraInvalidatedValues(ValueList &Values, 196 RegionAndSymbolInvalidationTraits *ETraits) const {} 197 198 public: 199 CallEvent &operator=(const CallEvent &) = delete; 200 virtual ~CallEvent() = default; 201 202 /// Returns the kind of call this is. 203 virtual Kind getKind() const = 0; 204 virtual StringRef getKindAsString() const = 0; 205 206 /// Returns the declaration of the function or method that will be 207 /// called. May be null. 208 virtual const Decl *getDecl() const { 209 return Origin.dyn_cast<const Decl *>(); 210 } 211 212 /// The state in which the call is being evaluated. 213 const ProgramStateRef &getState() const { 214 return State; 215 } 216 217 /// The context in which the call is being evaluated. 218 const LocationContext *getLocationContext() const { 219 return LCtx; 220 } 221 222 /// Returns the definition of the function or method that will be 223 /// called. 224 virtual RuntimeDefinition getRuntimeDefinition() const = 0; 225 226 /// Returns the expression whose value will be the result of this call. 227 /// May be null. 228 const Expr *getOriginExpr() const { 229 return Origin.dyn_cast<const Expr *>(); 230 } 231 232 /// Returns the number of arguments (explicit and implicit). 233 /// 234 /// Note that this may be greater than the number of parameters in the 235 /// callee's declaration, and that it may include arguments not written in 236 /// the source. 237 virtual unsigned getNumArgs() const = 0; 238 239 /// Returns true if the callee is known to be from a system header. 240 bool isInSystemHeader() const { 241 const Decl *D = getDecl(); 242 if (!D) 243 return false; 244 245 SourceLocation Loc = D->getLocation(); 246 if (Loc.isValid()) { 247 const SourceManager &SM = 248 getState()->getStateManager().getContext().getSourceManager(); 249 return SM.isInSystemHeader(D->getLocation()); 250 } 251 252 // Special case for implicitly-declared global operator new/delete. 253 // These should be considered system functions. 254 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 255 return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal(); 256 257 return false; 258 } 259 260 /// Returns true if the CallEvent is a call to a function that matches 261 /// the CallDescription. 262 /// 263 /// Note that this function is not intended to be used to match Obj-C method 264 /// calls. 265 bool isCalled(const CallDescription &CD) const; 266 267 /// Returns true whether the CallEvent is any of the CallDescriptions supplied 268 /// as a parameter. 269 template <typename FirstCallDesc, typename... CallDescs> 270 bool isCalled(const FirstCallDesc &First, const CallDescs &... Rest) const { 271 return isCalled(First) || isCalled(Rest...); 272 } 273 274 /// Returns a source range for the entire call, suitable for 275 /// outputting in diagnostics. 276 virtual SourceRange getSourceRange() const { 277 return getOriginExpr()->getSourceRange(); 278 } 279 280 /// Returns the value of a given argument at the time of the call. 281 virtual SVal getArgSVal(unsigned Index) const; 282 283 /// Returns the expression associated with a given argument. 284 /// May be null if this expression does not appear in the source. 285 virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; } 286 287 /// Returns the source range for errors associated with this argument. 288 /// 289 /// May be invalid if the argument is not written in the source. 290 virtual SourceRange getArgSourceRange(unsigned Index) const; 291 292 /// Returns the result type, adjusted for references. 293 QualType getResultType() const; 294 295 /// Returns the return value of the call. 296 /// 297 /// This should only be called if the CallEvent was created using a state in 298 /// which the return value has already been bound to the origin expression. 299 SVal getReturnValue() const; 300 301 /// Returns true if the type of any of the non-null arguments satisfies 302 /// the condition. 303 bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const; 304 305 /// Returns true if any of the arguments appear to represent callbacks. 306 bool hasNonZeroCallbackArg() const; 307 308 /// Returns true if any of the arguments is void*. 309 bool hasVoidPointerToNonConstArg() const; 310 311 /// Returns true if any of the arguments are known to escape to long- 312 /// term storage, even if this method will not modify them. 313 // NOTE: The exact semantics of this are still being defined! 314 // We don't really want a list of hardcoded exceptions in the long run, 315 // but we don't want duplicated lists of known APIs in the short term either. 316 virtual bool argumentsMayEscape() const { 317 return hasNonZeroCallbackArg(); 318 } 319 320 /// Returns true if the callee is an externally-visible function in the 321 /// top-level namespace, such as \c malloc. 322 /// 323 /// You can use this call to determine that a particular function really is 324 /// a library function and not, say, a C++ member function with the same name. 325 /// 326 /// If a name is provided, the function must additionally match the given 327 /// name. 328 /// 329 /// Note that this deliberately excludes C++ library functions in the \c std 330 /// namespace, but will include C library functions accessed through the 331 /// \c std namespace. This also does not check if the function is declared 332 /// as 'extern "C"', or if it uses C++ name mangling. 333 // FIXME: Add a helper for checking namespaces. 334 // FIXME: Move this down to AnyFunctionCall once checkers have more 335 // precise callbacks. 336 bool isGlobalCFunction(StringRef SpecificName = StringRef()) const; 337 338 /// Returns the name of the callee, if its name is a simple identifier. 339 /// 340 /// Note that this will fail for Objective-C methods, blocks, and C++ 341 /// overloaded operators. The former is named by a Selector rather than a 342 /// simple identifier, and the latter two do not have names. 343 // FIXME: Move this down to AnyFunctionCall once checkers have more 344 // precise callbacks. 345 const IdentifierInfo *getCalleeIdentifier() const { 346 const auto *ND = dyn_cast_or_null<NamedDecl>(getDecl()); 347 if (!ND) 348 return nullptr; 349 return ND->getIdentifier(); 350 } 351 352 /// Returns an appropriate ProgramPoint for this call. 353 ProgramPoint getProgramPoint(bool IsPreVisit = false, 354 const ProgramPointTag *Tag = nullptr) const; 355 356 /// Returns a new state with all argument regions invalidated. 357 /// 358 /// This accepts an alternate state in case some processing has already 359 /// occurred. 360 ProgramStateRef invalidateRegions(unsigned BlockCount, 361 ProgramStateRef Orig = nullptr) const; 362 363 using FrameBindingTy = std::pair<SVal, SVal>; 364 using BindingsTy = SmallVectorImpl<FrameBindingTy>; 365 366 /// Populates the given SmallVector with the bindings in the callee's stack 367 /// frame at the start of this call. 368 virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 369 BindingsTy &Bindings) const = 0; 370 371 /// Returns a copy of this CallEvent, but using the given state. 372 template <typename T> 373 CallEventRef<T> cloneWithState(ProgramStateRef NewState) const; 374 375 /// Returns a copy of this CallEvent, but using the given state. 376 CallEventRef<> cloneWithState(ProgramStateRef NewState) const { 377 return cloneWithState<CallEvent>(NewState); 378 } 379 380 /// Returns true if this is a statement is a function or method call 381 /// of some kind. 382 static bool isCallStmt(const Stmt *S); 383 384 /// Returns the result type of a function or method declaration. 385 /// 386 /// This will return a null QualType if the result type cannot be determined. 387 static QualType getDeclaredResultType(const Decl *D); 388 389 /// Returns true if the given decl is known to be variadic. 390 /// 391 /// \p D must not be null. 392 static bool isVariadic(const Decl *D); 393 394 /// Returns AnalysisDeclContext for the callee stack frame. 395 /// Currently may fail; returns null on failure. 396 AnalysisDeclContext *getCalleeAnalysisDeclContext() const; 397 398 /// Returns the callee stack frame. That stack frame will only be entered 399 /// during analysis if the call is inlined, but it may still be useful 400 /// in intermediate calculations even if the call isn't inlined. 401 /// May fail; returns null on failure. 402 const StackFrameContext *getCalleeStackFrame(unsigned BlockCount) const; 403 404 /// Returns memory location for a parameter variable within the callee stack 405 /// frame. The behavior is undefined if the block count is different from the 406 /// one that is there when call happens. May fail; returns null on failure. 407 const ParamVarRegion *getParameterLocation(unsigned Index, 408 unsigned BlockCount) const; 409 410 /// Returns true if on the current path, the argument was constructed by 411 /// calling a C++ constructor over it. This is an internal detail of the 412 /// analysis which doesn't necessarily represent the program semantics: 413 /// if we are supposed to construct an argument directly, we may still 414 /// not do that because we don't know how (i.e., construction context is 415 /// unavailable in the CFG or not supported by the analyzer). 416 bool isArgumentConstructedDirectly(unsigned Index) const { 417 // This assumes that the object was not yet removed from the state. 418 return ExprEngine::getObjectUnderConstruction( 419 getState(), {getOriginExpr(), Index}, getLocationContext()).hasValue(); 420 } 421 422 /// Some calls have parameter numbering mismatched from argument numbering. 423 /// This function converts an argument index to the corresponding 424 /// parameter index. Returns None is the argument doesn't correspond 425 /// to any parameter variable. 426 virtual Optional<unsigned> 427 getAdjustedParameterIndex(unsigned ASTArgumentIndex) const { 428 return ASTArgumentIndex; 429 } 430 431 /// Some call event sub-classes conveniently adjust mismatching AST indices 432 /// to match parameter indices. This function converts an argument index 433 /// as understood by CallEvent to the argument index as understood by the AST. 434 virtual unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const { 435 return CallArgumentIndex; 436 } 437 438 /// Returns the construction context of the call, if it is a C++ constructor 439 /// call or a call of a function returning a C++ class instance. Otherwise 440 /// return nullptr. 441 const ConstructionContext *getConstructionContext() const; 442 443 /// If the call returns a C++ record type then the region of its return value 444 /// can be retrieved from its construction context. 445 Optional<SVal> getReturnValueUnderConstruction() const; 446 447 // Iterator access to formal parameters and their types. 448 private: 449 struct GetTypeFn { 450 QualType operator()(ParmVarDecl *PD) const { return PD->getType(); } 451 }; 452 453 public: 454 /// Return call's formal parameters. 455 /// 456 /// Remember that the number of formal parameters may not match the number 457 /// of arguments for all calls. However, the first parameter will always 458 /// correspond with the argument value returned by \c getArgSVal(0). 459 virtual ArrayRef<ParmVarDecl *> parameters() const = 0; 460 461 using param_type_iterator = 462 llvm::mapped_iterator<ArrayRef<ParmVarDecl *>::iterator, GetTypeFn>; 463 464 /// Returns an iterator over the types of the call's formal parameters. 465 /// 466 /// This uses the callee decl found by default name lookup rather than the 467 /// definition because it represents a public interface, and probably has 468 /// more annotations. 469 param_type_iterator param_type_begin() const { 470 return llvm::map_iterator(parameters().begin(), GetTypeFn()); 471 } 472 /// \sa param_type_begin() 473 param_type_iterator param_type_end() const { 474 return llvm::map_iterator(parameters().end(), GetTypeFn()); 475 } 476 477 // For debugging purposes only 478 void dump(raw_ostream &Out) const; 479 void dump() const; 480 }; 481 482 /// Represents a call to any sort of function that might have a 483 /// FunctionDecl. 484 class AnyFunctionCall : public CallEvent { 485 protected: 486 AnyFunctionCall(const Expr *E, ProgramStateRef St, 487 const LocationContext *LCtx) 488 : CallEvent(E, St, LCtx) {} 489 AnyFunctionCall(const Decl *D, ProgramStateRef St, 490 const LocationContext *LCtx) 491 : CallEvent(D, St, LCtx) {} 492 AnyFunctionCall(const AnyFunctionCall &Other) = default; 493 494 public: 495 // This function is overridden by subclasses, but they must return 496 // a FunctionDecl. 497 const FunctionDecl *getDecl() const override { 498 return cast<FunctionDecl>(CallEvent::getDecl()); 499 } 500 501 RuntimeDefinition getRuntimeDefinition() const override; 502 503 bool argumentsMayEscape() const override; 504 505 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 506 BindingsTy &Bindings) const override; 507 508 ArrayRef<ParmVarDecl *> parameters() const override; 509 510 static bool classof(const CallEvent *CA) { 511 return CA->getKind() >= CE_BEG_FUNCTION_CALLS && 512 CA->getKind() <= CE_END_FUNCTION_CALLS; 513 } 514 }; 515 516 /// Represents a C function or static C++ member function call. 517 /// 518 /// Example: \c fun() 519 class SimpleFunctionCall : public AnyFunctionCall { 520 friend class CallEventManager; 521 522 protected: 523 SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St, 524 const LocationContext *LCtx) 525 : AnyFunctionCall(CE, St, LCtx) {} 526 SimpleFunctionCall(const SimpleFunctionCall &Other) = default; 527 528 void cloneTo(void *Dest) const override { 529 new (Dest) SimpleFunctionCall(*this); 530 } 531 532 public: 533 virtual const CallExpr *getOriginExpr() const { 534 return cast<CallExpr>(AnyFunctionCall::getOriginExpr()); 535 } 536 537 const FunctionDecl *getDecl() const override; 538 539 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); } 540 541 const Expr *getArgExpr(unsigned Index) const override { 542 return getOriginExpr()->getArg(Index); 543 } 544 545 Kind getKind() const override { return CE_Function; } 546 virtual StringRef getKindAsString() const override { 547 return "SimpleFunctionCall"; 548 } 549 550 static bool classof(const CallEvent *CA) { 551 return CA->getKind() == CE_Function; 552 } 553 }; 554 555 /// Represents a call to a block. 556 /// 557 /// Example: <tt>^{ statement-body }()</tt> 558 class BlockCall : public CallEvent { 559 friend class CallEventManager; 560 561 protected: 562 BlockCall(const CallExpr *CE, ProgramStateRef St, 563 const LocationContext *LCtx) 564 : CallEvent(CE, St, LCtx) {} 565 BlockCall(const BlockCall &Other) = default; 566 567 void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); } 568 569 void getExtraInvalidatedValues(ValueList &Values, 570 RegionAndSymbolInvalidationTraits *ETraits) const override; 571 572 public: 573 virtual const CallExpr *getOriginExpr() const { 574 return cast<CallExpr>(CallEvent::getOriginExpr()); 575 } 576 577 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); } 578 579 const Expr *getArgExpr(unsigned Index) const override { 580 return getOriginExpr()->getArg(Index); 581 } 582 583 /// Returns the region associated with this instance of the block. 584 /// 585 /// This may be NULL if the block's origin is unknown. 586 const BlockDataRegion *getBlockRegion() const; 587 588 const BlockDecl *getDecl() const override { 589 const BlockDataRegion *BR = getBlockRegion(); 590 if (!BR) 591 return nullptr; 592 return BR->getDecl(); 593 } 594 595 bool isConversionFromLambda() const { 596 const BlockDecl *BD = getDecl(); 597 if (!BD) 598 return false; 599 600 return BD->isConversionFromLambda(); 601 } 602 603 /// For a block converted from a C++ lambda, returns the block 604 /// VarRegion for the variable holding the captured C++ lambda record. 605 const VarRegion *getRegionStoringCapturedLambda() const { 606 assert(isConversionFromLambda()); 607 const BlockDataRegion *BR = getBlockRegion(); 608 assert(BR && "Block converted from lambda must have a block region"); 609 610 auto I = BR->referenced_vars_begin(); 611 assert(I != BR->referenced_vars_end()); 612 613 return I.getCapturedRegion(); 614 } 615 616 RuntimeDefinition getRuntimeDefinition() const override { 617 if (!isConversionFromLambda()) 618 return RuntimeDefinition(getDecl()); 619 620 // Clang converts lambdas to blocks with an implicit user-defined 621 // conversion operator method on the lambda record that looks (roughly) 622 // like: 623 // 624 // typedef R(^block_type)(P1, P2, ...); 625 // operator block_type() const { 626 // auto Lambda = *this; 627 // return ^(P1 p1, P2 p2, ...){ 628 // /* return Lambda(p1, p2, ...); */ 629 // }; 630 // } 631 // 632 // Here R is the return type of the lambda and P1, P2, ... are 633 // its parameter types. 'Lambda' is a fake VarDecl captured by the block 634 // that is initialized to a copy of the lambda. 635 // 636 // Sema leaves the body of a lambda-converted block empty (it is 637 // produced by CodeGen), so we can't analyze it directly. Instead, we skip 638 // the block body and analyze the operator() method on the captured lambda. 639 const VarDecl *LambdaVD = getRegionStoringCapturedLambda()->getDecl(); 640 const CXXRecordDecl *LambdaDecl = LambdaVD->getType()->getAsCXXRecordDecl(); 641 CXXMethodDecl* LambdaCallOperator = LambdaDecl->getLambdaCallOperator(); 642 643 return RuntimeDefinition(LambdaCallOperator); 644 } 645 646 bool argumentsMayEscape() const override { 647 return true; 648 } 649 650 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 651 BindingsTy &Bindings) const override; 652 653 ArrayRef<ParmVarDecl *> parameters() const override; 654 655 Kind getKind() const override { return CE_Block; } 656 virtual StringRef getKindAsString() const override { return "BlockCall"; } 657 658 static bool classof(const CallEvent *CA) { return CA->getKind() == CE_Block; } 659 }; 660 661 /// Represents a non-static C++ member function call, no matter how 662 /// it is written. 663 class CXXInstanceCall : public AnyFunctionCall { 664 protected: 665 CXXInstanceCall(const CallExpr *CE, ProgramStateRef St, 666 const LocationContext *LCtx) 667 : AnyFunctionCall(CE, St, LCtx) {} 668 CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St, 669 const LocationContext *LCtx) 670 : AnyFunctionCall(D, St, LCtx) {} 671 CXXInstanceCall(const CXXInstanceCall &Other) = default; 672 673 void getExtraInvalidatedValues(ValueList &Values, 674 RegionAndSymbolInvalidationTraits *ETraits) const override; 675 676 public: 677 /// Returns the expression representing the implicit 'this' object. 678 virtual const Expr *getCXXThisExpr() const { return nullptr; } 679 680 /// Returns the value of the implicit 'this' object. 681 virtual SVal getCXXThisVal() const; 682 683 const FunctionDecl *getDecl() const override; 684 685 RuntimeDefinition getRuntimeDefinition() const override; 686 687 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 688 BindingsTy &Bindings) const override; 689 690 static bool classof(const CallEvent *CA) { 691 return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS && 692 CA->getKind() <= CE_END_CXX_INSTANCE_CALLS; 693 } 694 }; 695 696 /// Represents a non-static C++ member function call. 697 /// 698 /// Example: \c obj.fun() 699 class CXXMemberCall : public CXXInstanceCall { 700 friend class CallEventManager; 701 702 protected: 703 CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St, 704 const LocationContext *LCtx) 705 : CXXInstanceCall(CE, St, LCtx) {} 706 CXXMemberCall(const CXXMemberCall &Other) = default; 707 708 void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); } 709 710 public: 711 virtual const CXXMemberCallExpr *getOriginExpr() const { 712 return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr()); 713 } 714 715 unsigned getNumArgs() const override { 716 if (const CallExpr *CE = getOriginExpr()) 717 return CE->getNumArgs(); 718 return 0; 719 } 720 721 const Expr *getArgExpr(unsigned Index) const override { 722 return getOriginExpr()->getArg(Index); 723 } 724 725 const Expr *getCXXThisExpr() const override; 726 727 RuntimeDefinition getRuntimeDefinition() const override; 728 729 Kind getKind() const override { return CE_CXXMember; } 730 virtual StringRef getKindAsString() const override { return "CXXMemberCall"; } 731 732 static bool classof(const CallEvent *CA) { 733 return CA->getKind() == CE_CXXMember; 734 } 735 }; 736 737 /// Represents a C++ overloaded operator call where the operator is 738 /// implemented as a non-static member function. 739 /// 740 /// Example: <tt>iter + 1</tt> 741 class CXXMemberOperatorCall : public CXXInstanceCall { 742 friend class CallEventManager; 743 744 protected: 745 CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St, 746 const LocationContext *LCtx) 747 : CXXInstanceCall(CE, St, LCtx) {} 748 CXXMemberOperatorCall(const CXXMemberOperatorCall &Other) = default; 749 750 void cloneTo(void *Dest) const override { 751 new (Dest) CXXMemberOperatorCall(*this); 752 } 753 754 public: 755 virtual const CXXOperatorCallExpr *getOriginExpr() const { 756 return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr()); 757 } 758 759 unsigned getNumArgs() const override { 760 return getOriginExpr()->getNumArgs() - 1; 761 } 762 763 const Expr *getArgExpr(unsigned Index) const override { 764 return getOriginExpr()->getArg(Index + 1); 765 } 766 767 const Expr *getCXXThisExpr() const override; 768 769 Kind getKind() const override { return CE_CXXMemberOperator; } 770 virtual StringRef getKindAsString() const override { 771 return "CXXMemberOperatorCall"; 772 } 773 774 static bool classof(const CallEvent *CA) { 775 return CA->getKind() == CE_CXXMemberOperator; 776 } 777 778 Optional<unsigned> 779 getAdjustedParameterIndex(unsigned ASTArgumentIndex) const override { 780 // For member operator calls argument 0 on the expression corresponds 781 // to implicit this-parameter on the declaration. 782 return (ASTArgumentIndex > 0) ? Optional<unsigned>(ASTArgumentIndex - 1) 783 : None; 784 } 785 786 unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const override { 787 // For member operator calls argument 0 on the expression corresponds 788 // to implicit this-parameter on the declaration. 789 return CallArgumentIndex + 1; 790 } 791 792 OverloadedOperatorKind getOverloadedOperator() const { 793 return getOriginExpr()->getOperator(); 794 } 795 }; 796 797 /// Represents an implicit call to a C++ destructor. 798 /// 799 /// This can occur at the end of a scope (for automatic objects), at the end 800 /// of a full-expression (for temporaries), or as part of a delete. 801 class CXXDestructorCall : public CXXInstanceCall { 802 friend class CallEventManager; 803 804 protected: 805 using DtorDataTy = llvm::PointerIntPair<const MemRegion *, 1, bool>; 806 807 /// Creates an implicit destructor. 808 /// 809 /// \param DD The destructor that will be called. 810 /// \param Trigger The statement whose completion causes this destructor call. 811 /// \param Target The object region to be destructed. 812 /// \param St The path-sensitive state at this point in the program. 813 /// \param LCtx The location context at this point in the program. 814 CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger, 815 const MemRegion *Target, bool IsBaseDestructor, 816 ProgramStateRef St, const LocationContext *LCtx) 817 : CXXInstanceCall(DD, St, LCtx) { 818 Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue(); 819 Location = Trigger->getEndLoc(); 820 } 821 822 CXXDestructorCall(const CXXDestructorCall &Other) = default; 823 824 void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);} 825 826 public: 827 SourceRange getSourceRange() const override { return Location; } 828 unsigned getNumArgs() const override { return 0; } 829 830 RuntimeDefinition getRuntimeDefinition() const override; 831 832 /// Returns the value of the implicit 'this' object. 833 SVal getCXXThisVal() const override; 834 835 /// Returns true if this is a call to a base class destructor. 836 bool isBaseDestructor() const { 837 return DtorDataTy::getFromOpaqueValue(Data).getInt(); 838 } 839 840 Kind getKind() const override { return CE_CXXDestructor; } 841 virtual StringRef getKindAsString() const override { 842 return "CXXDestructorCall"; 843 } 844 845 static bool classof(const CallEvent *CA) { 846 return CA->getKind() == CE_CXXDestructor; 847 } 848 }; 849 850 /// Represents any constructor invocation. This includes regular constructors 851 /// and inherited constructors. 852 class AnyCXXConstructorCall : public AnyFunctionCall { 853 protected: 854 AnyCXXConstructorCall(const Expr *E, const MemRegion *Target, 855 ProgramStateRef St, const LocationContext *LCtx) 856 : AnyFunctionCall(E, St, LCtx) { 857 assert(E && (isa<CXXConstructExpr>(E) || isa<CXXInheritedCtorInitExpr>(E))); 858 // Target may be null when the region is unknown. 859 Data = Target; 860 } 861 862 void getExtraInvalidatedValues(ValueList &Values, 863 RegionAndSymbolInvalidationTraits *ETraits) const override; 864 865 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 866 BindingsTy &Bindings) const override; 867 868 public: 869 /// Returns the value of the implicit 'this' object. 870 SVal getCXXThisVal() const; 871 872 static bool classof(const CallEvent *Call) { 873 return Call->getKind() >= CE_BEG_CXX_CONSTRUCTOR_CALLS && 874 Call->getKind() <= CE_END_CXX_CONSTRUCTOR_CALLS; 875 } 876 }; 877 878 /// Represents a call to a C++ constructor. 879 /// 880 /// Example: \c T(1) 881 class CXXConstructorCall : public AnyCXXConstructorCall { 882 friend class CallEventManager; 883 884 protected: 885 /// Creates a constructor call. 886 /// 887 /// \param CE The constructor expression as written in the source. 888 /// \param Target The region where the object should be constructed. If NULL, 889 /// a new symbolic region will be used. 890 /// \param St The path-sensitive state at this point in the program. 891 /// \param LCtx The location context at this point in the program. 892 CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target, 893 ProgramStateRef St, const LocationContext *LCtx) 894 : AnyCXXConstructorCall(CE, Target, St, LCtx) {} 895 896 CXXConstructorCall(const CXXConstructorCall &Other) = default; 897 898 void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); } 899 900 public: 901 virtual const CXXConstructExpr *getOriginExpr() const { 902 return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr()); 903 } 904 905 const CXXConstructorDecl *getDecl() const override { 906 return getOriginExpr()->getConstructor(); 907 } 908 909 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); } 910 911 const Expr *getArgExpr(unsigned Index) const override { 912 return getOriginExpr()->getArg(Index); 913 } 914 915 Kind getKind() const override { return CE_CXXConstructor; } 916 virtual StringRef getKindAsString() const override { 917 return "CXXConstructorCall"; 918 } 919 920 static bool classof(const CallEvent *CA) { 921 return CA->getKind() == CE_CXXConstructor; 922 } 923 }; 924 925 /// Represents a call to a C++ inherited constructor. 926 /// 927 /// Example: \c class T : public S { using S::S; }; T(1); 928 /// 929 // Note, it is difficult to model the parameters. This is one of the reasons 930 // why we skip analysis of inheriting constructors as top-level functions. 931 // CXXInheritedCtorInitExpr doesn't take arguments and doesn't model parameter 932 // initialization because there is none: the arguments in the outer 933 // CXXConstructExpr directly initialize the parameters of the base class 934 // constructor, and no copies are made. (Making a copy of the parameter is 935 // incorrect, at least if it's done in an observable way.) The derived class 936 // constructor doesn't even exist in the formal model. 937 /// E.g., in: 938 /// 939 /// struct X { X *p = this; ~X() {} }; 940 /// struct A { A(X x) : b(x.p == &x) {} bool b; }; 941 /// struct B : A { using A::A; }; 942 /// B b = X{}; 943 /// 944 /// ... b.b is initialized to true. 945 class CXXInheritedConstructorCall : public AnyCXXConstructorCall { 946 friend class CallEventManager; 947 948 protected: 949 CXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *CE, 950 const MemRegion *Target, ProgramStateRef St, 951 const LocationContext *LCtx) 952 : AnyCXXConstructorCall(CE, Target, St, LCtx) {} 953 954 CXXInheritedConstructorCall(const CXXInheritedConstructorCall &Other) = 955 default; 956 957 void cloneTo(void *Dest) const override { 958 new (Dest) CXXInheritedConstructorCall(*this); 959 } 960 961 public: 962 virtual const CXXInheritedCtorInitExpr *getOriginExpr() const { 963 return cast<CXXInheritedCtorInitExpr>(AnyFunctionCall::getOriginExpr()); 964 } 965 966 const CXXConstructorDecl *getDecl() const override { 967 return getOriginExpr()->getConstructor(); 968 } 969 970 /// Obtain the stack frame of the inheriting constructor. Argument expressions 971 /// can be found on the call site of that stack frame. 972 const StackFrameContext *getInheritingStackFrame() const; 973 974 /// Obtain the CXXConstructExpr for the sub-class that inherited the current 975 /// constructor (possibly indirectly). It's the statement that contains 976 /// argument expressions. 977 const CXXConstructExpr *getInheritingConstructor() const { 978 return cast<CXXConstructExpr>(getInheritingStackFrame()->getCallSite()); 979 } 980 981 unsigned getNumArgs() const override { 982 return getInheritingConstructor()->getNumArgs(); 983 } 984 985 const Expr *getArgExpr(unsigned Index) const override { 986 return getInheritingConstructor()->getArg(Index); 987 } 988 989 virtual SVal getArgSVal(unsigned Index) const override { 990 return getState()->getSVal( 991 getArgExpr(Index), 992 getInheritingStackFrame()->getParent()->getStackFrame()); 993 } 994 995 Kind getKind() const override { return CE_CXXInheritedConstructor; } 996 virtual StringRef getKindAsString() const override { 997 return "CXXInheritedConstructorCall"; 998 } 999 1000 static bool classof(const CallEvent *CA) { 1001 return CA->getKind() == CE_CXXInheritedConstructor; 1002 } 1003 }; 1004 1005 /// Represents the memory allocation call in a C++ new-expression. 1006 /// 1007 /// This is a call to "operator new". 1008 class CXXAllocatorCall : public AnyFunctionCall { 1009 friend class CallEventManager; 1010 1011 protected: 1012 CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St, 1013 const LocationContext *LCtx) 1014 : AnyFunctionCall(E, St, LCtx) {} 1015 CXXAllocatorCall(const CXXAllocatorCall &Other) = default; 1016 1017 void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); } 1018 1019 public: 1020 virtual const CXXNewExpr *getOriginExpr() const { 1021 return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr()); 1022 } 1023 1024 const FunctionDecl *getDecl() const override { 1025 return getOriginExpr()->getOperatorNew(); 1026 } 1027 1028 SVal getObjectUnderConstruction() const { 1029 return ExprEngine::getObjectUnderConstruction(getState(), getOriginExpr(), 1030 getLocationContext()) 1031 .getValue(); 1032 } 1033 1034 /// Number of non-placement arguments to the call. It is equal to 2 for 1035 /// C++17 aligned operator new() calls that have alignment implicitly 1036 /// passed as the second argument, and to 1 for other operator new() calls. 1037 unsigned getNumImplicitArgs() const { 1038 return getOriginExpr()->passAlignment() ? 2 : 1; 1039 } 1040 1041 unsigned getNumArgs() const override { 1042 return getOriginExpr()->getNumPlacementArgs() + getNumImplicitArgs(); 1043 } 1044 1045 const Expr *getArgExpr(unsigned Index) const override { 1046 // The first argument of an allocator call is the size of the allocation. 1047 if (Index < getNumImplicitArgs()) 1048 return nullptr; 1049 return getOriginExpr()->getPlacementArg(Index - getNumImplicitArgs()); 1050 } 1051 1052 /// Number of placement arguments to the operator new() call. For example, 1053 /// standard std::nothrow operator new and standard placement new both have 1054 /// 1 implicit argument (size) and 1 placement argument, while regular 1055 /// operator new() has 1 implicit argument and 0 placement arguments. 1056 const Expr *getPlacementArgExpr(unsigned Index) const { 1057 return getOriginExpr()->getPlacementArg(Index); 1058 } 1059 1060 Kind getKind() const override { return CE_CXXAllocator; } 1061 virtual StringRef getKindAsString() const override { 1062 return "CXXAllocatorCall"; 1063 } 1064 1065 static bool classof(const CallEvent *CE) { 1066 return CE->getKind() == CE_CXXAllocator; 1067 } 1068 }; 1069 1070 /// Represents the memory deallocation call in a C++ delete-expression. 1071 /// 1072 /// This is a call to "operator delete". 1073 // FIXME: CXXDeleteExpr isn't present for custom delete operators, or even for 1074 // some those that are in the standard library, like the no-throw or align_val 1075 // versions. 1076 // Some pointers: 1077 // http://lists.llvm.org/pipermail/cfe-dev/2020-April/065080.html 1078 // clang/test/Analysis/cxx-dynamic-memory-analysis-order.cpp 1079 // clang/unittests/StaticAnalyzer/CallEventTest.cpp 1080 class CXXDeallocatorCall : public AnyFunctionCall { 1081 friend class CallEventManager; 1082 1083 protected: 1084 CXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef St, 1085 const LocationContext *LCtx) 1086 : AnyFunctionCall(E, St, LCtx) {} 1087 CXXDeallocatorCall(const CXXDeallocatorCall &Other) = default; 1088 1089 void cloneTo(void *Dest) const override { 1090 new (Dest) CXXDeallocatorCall(*this); 1091 } 1092 1093 public: 1094 virtual const CXXDeleteExpr *getOriginExpr() const { 1095 return cast<CXXDeleteExpr>(AnyFunctionCall::getOriginExpr()); 1096 } 1097 1098 const FunctionDecl *getDecl() const override { 1099 return getOriginExpr()->getOperatorDelete(); 1100 } 1101 1102 unsigned getNumArgs() const override { return getDecl()->getNumParams(); } 1103 1104 const Expr *getArgExpr(unsigned Index) const override { 1105 // CXXDeleteExpr's only have a single argument. 1106 return getOriginExpr()->getArgument(); 1107 } 1108 1109 Kind getKind() const override { return CE_CXXDeallocator; } 1110 virtual StringRef getKindAsString() const override { 1111 return "CXXDeallocatorCall"; 1112 } 1113 1114 static bool classof(const CallEvent *CE) { 1115 return CE->getKind() == CE_CXXDeallocator; 1116 } 1117 }; 1118 1119 /// Represents the ways an Objective-C message send can occur. 1120 // 1121 // Note to maintainers: OCM_Message should always be last, since it does not 1122 // need to fit in the Data field's low bits. 1123 enum ObjCMessageKind { 1124 OCM_PropertyAccess, 1125 OCM_Subscript, 1126 OCM_Message 1127 }; 1128 1129 /// Represents any expression that calls an Objective-C method. 1130 /// 1131 /// This includes all of the kinds listed in ObjCMessageKind. 1132 class ObjCMethodCall : public CallEvent { 1133 friend class CallEventManager; 1134 1135 const PseudoObjectExpr *getContainingPseudoObjectExpr() const; 1136 1137 protected: 1138 ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St, 1139 const LocationContext *LCtx) 1140 : CallEvent(Msg, St, LCtx) { 1141 Data = nullptr; 1142 } 1143 1144 ObjCMethodCall(const ObjCMethodCall &Other) = default; 1145 1146 void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); } 1147 1148 void getExtraInvalidatedValues(ValueList &Values, 1149 RegionAndSymbolInvalidationTraits *ETraits) const override; 1150 1151 /// Check if the selector may have multiple definitions (may have overrides). 1152 virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, 1153 Selector Sel) const; 1154 1155 public: 1156 virtual const ObjCMessageExpr *getOriginExpr() const { 1157 return cast<ObjCMessageExpr>(CallEvent::getOriginExpr()); 1158 } 1159 1160 const ObjCMethodDecl *getDecl() const override { 1161 return getOriginExpr()->getMethodDecl(); 1162 } 1163 1164 unsigned getNumArgs() const override { 1165 return getOriginExpr()->getNumArgs(); 1166 } 1167 1168 const Expr *getArgExpr(unsigned Index) const override { 1169 return getOriginExpr()->getArg(Index); 1170 } 1171 1172 bool isInstanceMessage() const { 1173 return getOriginExpr()->isInstanceMessage(); 1174 } 1175 1176 ObjCMethodFamily getMethodFamily() const { 1177 return getOriginExpr()->getMethodFamily(); 1178 } 1179 1180 Selector getSelector() const { 1181 return getOriginExpr()->getSelector(); 1182 } 1183 1184 SourceRange getSourceRange() const override; 1185 1186 /// Returns the value of the receiver at the time of this call. 1187 SVal getReceiverSVal() const; 1188 1189 /// Get the interface for the receiver. 1190 /// 1191 /// This works whether this is an instance message or a class message. 1192 /// However, it currently just uses the static type of the receiver. 1193 const ObjCInterfaceDecl *getReceiverInterface() const { 1194 return getOriginExpr()->getReceiverInterface(); 1195 } 1196 1197 /// Checks if the receiver refers to 'self' or 'super'. 1198 bool isReceiverSelfOrSuper() const; 1199 1200 /// Returns how the message was written in the source (property access, 1201 /// subscript, or explicit message send). 1202 ObjCMessageKind getMessageKind() const; 1203 1204 /// Returns true if this property access or subscript is a setter (has the 1205 /// form of an assignment). 1206 bool isSetter() const { 1207 switch (getMessageKind()) { 1208 case OCM_Message: 1209 llvm_unreachable("This is not a pseudo-object access!"); 1210 case OCM_PropertyAccess: 1211 return getNumArgs() > 0; 1212 case OCM_Subscript: 1213 return getNumArgs() > 1; 1214 } 1215 llvm_unreachable("Unknown message kind"); 1216 } 1217 1218 // Returns the property accessed by this method, either explicitly via 1219 // property syntax or implicitly via a getter or setter method. Returns 1220 // nullptr if the call is not a prooperty access. 1221 const ObjCPropertyDecl *getAccessedProperty() const; 1222 1223 RuntimeDefinition getRuntimeDefinition() const override; 1224 1225 bool argumentsMayEscape() const override; 1226 1227 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 1228 BindingsTy &Bindings) const override; 1229 1230 ArrayRef<ParmVarDecl*> parameters() const override; 1231 1232 Kind getKind() const override { return CE_ObjCMessage; } 1233 virtual StringRef getKindAsString() const override { 1234 return "ObjCMethodCall"; 1235 } 1236 1237 static bool classof(const CallEvent *CA) { 1238 return CA->getKind() == CE_ObjCMessage; 1239 } 1240 }; 1241 1242 enum CallDescriptionFlags : int { 1243 /// Describes a C standard function that is sometimes implemented as a macro 1244 /// that expands to a compiler builtin with some __builtin prefix. 1245 /// The builtin may as well have a few extra arguments on top of the requested 1246 /// number of arguments. 1247 CDF_MaybeBuiltin = 1 << 0, 1248 }; 1249 1250 /// This class represents a description of a function call using the number of 1251 /// arguments and the name of the function. 1252 class CallDescription { 1253 friend CallEvent; 1254 1255 mutable IdentifierInfo *II = nullptr; 1256 mutable bool IsLookupDone = false; 1257 // The list of the qualified names used to identify the specified CallEvent, 1258 // e.g. "{a, b}" represent the qualified names, like "a::b". 1259 std::vector<const char *> QualifiedName; 1260 Optional<unsigned> RequiredArgs; 1261 Optional<size_t> RequiredParams; 1262 int Flags; 1263 1264 // A constructor helper. 1265 static Optional<size_t> readRequiredParams(Optional<unsigned> RequiredArgs, 1266 Optional<size_t> RequiredParams) { 1267 if (RequiredParams) 1268 return RequiredParams; 1269 if (RequiredArgs) 1270 return static_cast<size_t>(*RequiredArgs); 1271 return None; 1272 } 1273 1274 public: 1275 /// Constructs a CallDescription object. 1276 /// 1277 /// @param QualifiedName The list of the name qualifiers of the function that 1278 /// will be matched. The user is allowed to skip any of the qualifiers. 1279 /// For example, {"std", "basic_string", "c_str"} would match both 1280 /// std::basic_string<...>::c_str() and std::__1::basic_string<...>::c_str(). 1281 /// 1282 /// @param RequiredArgs The number of arguments that is expected to match a 1283 /// call. Omit this parameter to match every occurrence of call with a given 1284 /// name regardless the number of arguments. 1285 CallDescription(int Flags, ArrayRef<const char *> QualifiedName, 1286 Optional<unsigned> RequiredArgs = None, 1287 Optional<size_t> RequiredParams = None) 1288 : QualifiedName(QualifiedName), RequiredArgs(RequiredArgs), 1289 RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)), 1290 Flags(Flags) {} 1291 1292 /// Construct a CallDescription with default flags. 1293 CallDescription(ArrayRef<const char *> QualifiedName, 1294 Optional<unsigned> RequiredArgs = None, 1295 Optional<size_t> RequiredParams = None) 1296 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {} 1297 1298 /// Get the name of the function that this object matches. 1299 StringRef getFunctionName() const { return QualifiedName.back(); } 1300 }; 1301 1302 /// An immutable map from CallDescriptions to arbitrary data. Provides a unified 1303 /// way for checkers to react on function calls. 1304 template <typename T> class CallDescriptionMap { 1305 // Some call descriptions aren't easily hashable (eg., the ones with qualified 1306 // names in which some sections are omitted), so let's put them 1307 // in a simple vector and use linear lookup. 1308 // TODO: Implement an actual map for fast lookup for "hashable" call 1309 // descriptions (eg., the ones for C functions that just match the name). 1310 std::vector<std::pair<CallDescription, T>> LinearMap; 1311 1312 public: 1313 CallDescriptionMap( 1314 std::initializer_list<std::pair<CallDescription, T>> &&List) 1315 : LinearMap(List) {} 1316 1317 ~CallDescriptionMap() = default; 1318 1319 // These maps are usually stored once per checker, so let's make sure 1320 // we don't do redundant copies. 1321 CallDescriptionMap(const CallDescriptionMap &) = delete; 1322 CallDescriptionMap &operator=(const CallDescription &) = delete; 1323 1324 const T *lookup(const CallEvent &Call) const { 1325 // Slow path: linear lookup. 1326 // TODO: Implement some sort of fast path. 1327 for (const std::pair<CallDescription, T> &I : LinearMap) 1328 if (Call.isCalled(I.first)) 1329 return &I.second; 1330 1331 return nullptr; 1332 } 1333 }; 1334 1335 /// Manages the lifetime of CallEvent objects. 1336 /// 1337 /// CallEventManager provides a way to create arbitrary CallEvents "on the 1338 /// stack" as if they were value objects by keeping a cache of CallEvent-sized 1339 /// memory blocks. The CallEvents created by CallEventManager are only valid 1340 /// for the lifetime of the OwnedCallEvent that holds them; right now these 1341 /// objects cannot be copied and ownership cannot be transferred. 1342 class CallEventManager { 1343 friend class CallEvent; 1344 1345 llvm::BumpPtrAllocator &Alloc; 1346 SmallVector<void *, 8> Cache; 1347 1348 using CallEventTemplateTy = SimpleFunctionCall; 1349 1350 void reclaim(const void *Memory) { 1351 Cache.push_back(const_cast<void *>(Memory)); 1352 } 1353 1354 /// Returns memory that can be initialized as a CallEvent. 1355 void *allocate() { 1356 if (Cache.empty()) 1357 return Alloc.Allocate<CallEventTemplateTy>(); 1358 else 1359 return Cache.pop_back_val(); 1360 } 1361 1362 template <typename T, typename Arg> 1363 T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) { 1364 static_assert(sizeof(T) == sizeof(CallEventTemplateTy), 1365 "CallEvent subclasses are not all the same size"); 1366 return new (allocate()) T(A, St, LCtx); 1367 } 1368 1369 template <typename T, typename Arg1, typename Arg2> 1370 T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) { 1371 static_assert(sizeof(T) == sizeof(CallEventTemplateTy), 1372 "CallEvent subclasses are not all the same size"); 1373 return new (allocate()) T(A1, A2, St, LCtx); 1374 } 1375 1376 template <typename T, typename Arg1, typename Arg2, typename Arg3> 1377 T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St, 1378 const LocationContext *LCtx) { 1379 static_assert(sizeof(T) == sizeof(CallEventTemplateTy), 1380 "CallEvent subclasses are not all the same size"); 1381 return new (allocate()) T(A1, A2, A3, St, LCtx); 1382 } 1383 1384 template <typename T, typename Arg1, typename Arg2, typename Arg3, 1385 typename Arg4> 1386 T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St, 1387 const LocationContext *LCtx) { 1388 static_assert(sizeof(T) == sizeof(CallEventTemplateTy), 1389 "CallEvent subclasses are not all the same size"); 1390 return new (allocate()) T(A1, A2, A3, A4, St, LCtx); 1391 } 1392 1393 public: 1394 CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {} 1395 1396 /// Gets an outside caller given a callee context. 1397 CallEventRef<> 1398 getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State); 1399 1400 /// Gets a call event for a function call, Objective-C method call, 1401 /// or a 'new' call. 1402 CallEventRef<> 1403 getCall(const Stmt *S, ProgramStateRef State, 1404 const LocationContext *LC); 1405 1406 CallEventRef<> 1407 getSimpleCall(const CallExpr *E, ProgramStateRef State, 1408 const LocationContext *LCtx); 1409 1410 CallEventRef<ObjCMethodCall> 1411 getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, 1412 const LocationContext *LCtx) { 1413 return create<ObjCMethodCall>(E, State, LCtx); 1414 } 1415 1416 CallEventRef<CXXConstructorCall> 1417 getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target, 1418 ProgramStateRef State, const LocationContext *LCtx) { 1419 return create<CXXConstructorCall>(E, Target, State, LCtx); 1420 } 1421 1422 CallEventRef<CXXInheritedConstructorCall> 1423 getCXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *E, 1424 const MemRegion *Target, ProgramStateRef State, 1425 const LocationContext *LCtx) { 1426 return create<CXXInheritedConstructorCall>(E, Target, State, LCtx); 1427 } 1428 1429 CallEventRef<CXXDestructorCall> 1430 getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger, 1431 const MemRegion *Target, bool IsBase, 1432 ProgramStateRef State, const LocationContext *LCtx) { 1433 return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx); 1434 } 1435 1436 CallEventRef<CXXAllocatorCall> 1437 getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State, 1438 const LocationContext *LCtx) { 1439 return create<CXXAllocatorCall>(E, State, LCtx); 1440 } 1441 1442 CallEventRef<CXXDeallocatorCall> 1443 getCXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef State, 1444 const LocationContext *LCtx) { 1445 return create<CXXDeallocatorCall>(E, State, LCtx); 1446 } 1447 }; 1448 1449 template <typename T> 1450 CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const { 1451 assert(isa<T>(*this) && "Cloning to unrelated type"); 1452 static_assert(sizeof(T) == sizeof(CallEvent), 1453 "Subclasses may not add fields"); 1454 1455 if (NewState == State) 1456 return cast<T>(this); 1457 1458 CallEventManager &Mgr = State->getStateManager().getCallEventManager(); 1459 T *Copy = static_cast<T *>(Mgr.allocate()); 1460 cloneTo(Copy); 1461 assert(Copy->getKind() == this->getKind() && "Bad copy"); 1462 1463 Copy->State = NewState; 1464 return Copy; 1465 } 1466 1467 inline void CallEvent::Release() const { 1468 assert(RefCount > 0 && "Reference count is already zero."); 1469 --RefCount; 1470 1471 if (RefCount > 0) 1472 return; 1473 1474 CallEventManager &Mgr = State->getStateManager().getCallEventManager(); 1475 Mgr.reclaim(this); 1476 1477 this->~CallEvent(); 1478 } 1479 1480 } // namespace ento 1481 1482 } // namespace clang 1483 1484 namespace llvm { 1485 1486 // Support isa<>, cast<>, and dyn_cast<> for CallEventRef. 1487 template<class T> struct simplify_type< clang::ento::CallEventRef<T>> { 1488 using SimpleType = const T *; 1489 1490 static SimpleType 1491 getSimplifiedValue(clang::ento::CallEventRef<T> Val) { 1492 return Val.get(); 1493 } 1494 }; 1495 1496 } // namespace llvm 1497 1498 #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H 1499