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